本篇通过将句子数组转换为句子的向量表现,并通过均匀池化和归一化处置惩罚,天生适当呆板学习或深度学习任务使用的特性向量为例,演示通过NodeJS 的方式调用Xenova/all-MiniLM-L6-v2 的过程。
关于 all-MiniLM-L6-v2 的先容,可以参照上一篇:
一篇吃透模子:all-MiniLM-L6-v2
可以访问 Hugging Face的状态
Hugging 的站点是:
https://huggingface.co/
如果可以访问该站点的话,则直接安装 Hugging Face 的 Transformers 库。
- npm i @huggingface/transformers
复制代码 之后就可以编写代码:
- import { pipeline } from '@huggingface/transformers';
- // Create a feature-extraction pipeline
- const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
- // Compute sentence embeddings
- const sentences = ['This is an example sentence', 'Each sentence is converted'];
- const output = await extractor(sentences, { pooling: 'mean', normalize: true });
- console.log(output);
复制代码 上面代码作用就是加载模子,将语句转换为向量,细节的部分下面再先容,实行的效果如下:

到此,就乐成的运行了。
但是如果无法访问Hugging Face 的化, 运行就会出现如下错误:

- PS D:\devworkspace\vs\ai_ency\ai_nodejs_ency> node .\src\llm\minilm\huggingface-minilm.js
- node:internal/deps/undici/undici:12502
- Error.captureStackTrace(err, this);
- ^
- TypeError: fetch failed
- at node:internal/deps/undici/undici:12502:13
- at processTicksAndRejections (node:internal/process/task_queues:95:5)
- at runNextTicks (node:internal/process/task_queues:64:3)
- at process.processImmediate (node:internal/timers:449:9)
- at async getModelFile (file:///D:/devworkspace/vs/ai_ency/ai_nodejs_ency/node_modules/@huggingface/transformers/dist/transformers.mjs:31325:24)
- at async getModelJSON (file:///D:/devworkspace/vs/ai_ency/ai_nodejs_ency/node_modules/@huggingface/transformers/dist/transformers.mjs:31427:18)
- at async Promise.all (index 0)
- at async loadTokenizer (file:///D:/devworkspace/vs/ai_ency/ai_nodejs_ency/node_modules/@huggingface/transformers/dist/transformers.mjs:24731:18)
- at async AutoTokenizer.from_pretrained (file:///D:/devworkspace/vs/ai_ency/ai_nodejs_ency/node_modules/@huggingface/transformers/dist/transformers.mjs:29020:50)
- at async Promise.all (index 0) {
- [cause]: ConnectTimeoutError: Connect Timeout Error
- at onConnectTimeout (node:internal/deps/undici/undici:6635:28)
- at node:internal/deps/undici/undici:6587:50
- at Immediate._onImmediate (node:internal/deps/undici/undici:6617:37)
- at process.processImmediate (node:internal/timers:478:21) {
- code: 'UND_ERR_CONNECT_TIMEOUT'
- }
- }
复制代码 由于默认会从Hugging Face下载模子文件,无法下载,报上面的fetch 获取错误, 有办理方法吗?
答案就是从ModelScope 下载模子文件。
从 ModelScope 下载模子文件
ModelScope上面也维护了 Xenova/all-MiniLM-L6-v2 的模子文件, 地点是:
https://www.modelscope.cn/models/Xenova/all-MiniLM-L6-v2/files
但是,ModelScope提供了Python的库,却没有NodeJS的库,以是无法直接通过ModelScope的来下载,但是可以下载模子的文件,下载方式就是先安装ModelScope,然后用ModelScope 的下令行下载模子文件:
- modelscope download --model Xenova/all-MiniLM-L6-v2
复制代码 下载后的文件目次如下图:
下载后,将这个目次中的内容复制到NodeJS 项目标node_modules 目次下的 node_modules@huggingface\transformers.cache 目次下, 这也是Hugging Face下载模子文件的目次,结构如下图:
复制完成之后,就可以正常运行了。
增补先容: Transformers 是什么?
Transformers 是由 Hugging Face 团队开辟的开源 库,专注于提供基于 Transformer 架构 的预练习模子和工具。它简化了自然语言处置惩罚(NLP)任务的实现流程,支持文本天生、翻译、分类、问答等场景,并兼容 PyTorch、TensorFlow 等深度学习框架。
Transformers 有Python 和 NodeJS 两个版本。
如果Hugging Face无法访问
- Python 版本可以使用ModelScope提供的库
- NodeJS
增补先容: 代码具体表明
const extractor = await pipeline(...) 是使用 Hugging Face Transformers.js 库的核心方法之一,用于创建一个 预练习模子的推理管道。通过 pipeline,可以轻松加载模子并实行各种任务(如文天职类、特性提取、问答等)。
pipeline 的作用是:
- 加载模子:从本地或长途加载预练习模子和分词器。
- 封装推理逻辑:将模子的输入预处置惩罚、推理和后处置惩罚逻辑封装成一个简朴的接口。
- 实使用命:根据任务范例(如 feature-extraction、text-classification 等),对输入数据举行处置惩罚并返回效果。
参数详解
pipeline 方法的完备署名如下:
- const pipeline = await transformers.pipeline(task, model, options);
复制代码 1. task(必须)
指定要实行的任务范例。常见的任务包罗:
- feature-extraction:特性提取(天生句子或词的嵌入向量)。
- text-classification:文天职类。
- question-answering:问答任务。
- translation:翻译任务。
- text-generation:文本天生。
- 其他任务:如 summarization、fill-mask 等。
示例:
- const extractor = await pipeline('feature-extraction');
复制代码 2. model(可选)
指定要加载的模子。可以是以下之一:
- 模子名称:从 Hugging Face Hub 加载的模子名称(如 Xenova/all-MiniLM-L6-v2)。
- 本地路径:本地模子文件的路径(如 ./custom_model)。
- 未指定:如果不提供,库会加载默认模子。
示例:
- // 从 Hugging Face Hub 加载模型
- const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
- // 从本地路径加载模型
- const extractor = await pipeline('feature-extraction', './custom_model');
复制代码 3. options(可选)
一个设置对象,用于自界说模子加载和推理举动。常见选项包罗:
选项范例形貌local_files_onlyboolean是否仅从本地加载模子(默认 false)。设置为 true 可禁用网络哀求。revisionstring模子版本(如 main 或特定 commit hash)。cache_dirstring缓存目次路径。设置为 null 可禁用缓存。quantizedboolean是否加载量化模子(默认 false)。progress_callbackfunction加载模子时的进度回调函数。devicestring推理装备(如 cpu 或 gpu)。poolingstring特性提取时的池化方式(如 mean、max)。normalizeboolean是否对特性向量举行归一化(默认 false)。示例:
- const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', {
- local_files_only: true, // 仅从本地加载
- revision: 'main', // 使用主分支版本
- pooling: 'mean', // 使用均值池化
- normalize: true, // 对输出向量归一化
- });
复制代码 返回值
pipeline 返回一个 推理函数,可以直接用于处置惩罚输入数据。具体返回值范例取决于任务范例。
示例:
- // 特性提取任务const extractor = await pipeline('feature-extraction');
- // 使用推理函数const sentences = ['This is an example sentence'];const embeddings = await extractor(sentences, { pooling: 'mean' });console.log(embeddings);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|