---
title: text2vec-base-chinese-onnx
canonical_url: "https://www.modelscope.cn/models/QuadraV/text2vec-base-chinese-onnx"
md_url: "https://www.modelscope.cn/models/QuadraV/text2vec-base-chinese-onnx.md"
repository: QuadraV/text2vec-base-chinese-onnx
chinese_name: "句子向量onnx模型"
last_updated: 2024-10-28
license: "Apache License 2.0"
pipeline_tag: sentence-similarity
tasks:
  - sentence-similarity
library_name:
  - onnx
  - other
frameworks:
  - other
downloads: 35
stars: 1
---

# text2vec-base-chinese-onnx

> text2vec-base-chinese-onnx - QuadraV 在 ModelScope 开源的模型。当前模型的贡献者未提供更加详细的模型介绍。模型文件和权重，可浏览“模型文件”页面获取。 您可以通过如下git clone命令，或者ModelScope SDK来下载模型

QuadraV/text2vec-base-chinese-onnx 是 ModelScope 魔搭社区上的sentence-similarity模型，采用 Apache License 2.0 许可。

- **Repository**: QuadraV/text2vec-base-chinese-onnx
- **License**: Apache License 2.0
- **Tasks**: sentence-similarity
- **Downloads**: 35
- **Stars**: 1
- **Last updated**: 2024-10-28

Source: https://www.modelscope.cn/models/QuadraV/text2vec-base-chinese-onnx

---

### 当前模型的贡献者未提供更加详细的模型介绍。模型文件和权重，可浏览“模型文件”页面获取。
#### 您可以通过如下git clone命令，或者ModelScope SDK来下载模型

## Demo
```python
import os
from onnxruntime import InferenceSession
import numpy as np
class Text2Vector: 
    def __init__(self, model_dir="text2vec-base-chinese") -> None:
        self.model_path = os.path.join(model_dir,"text2vec-base-chinese.onnx")
        self.vocab_path = os.path.join(model_dir,"vocab.txt")
        self.vocab = self.load_vocab(self.vocab_path)
        self.onnx_session = InferenceSession(self.model_path)
        

    def load_vocab(self, vocab_path):
        """Load BERT vocabulary."""
        vocab = {}
        with open(vocab_path, 'r', encoding='utf-8') as f:
            for idx, line in enumerate(f):
                token = line.strip()
                vocab[token] = idx
        return vocab

    def tokenize(self, text):
        """Tokenize text into BERT input_ids."""
        tokens = ['[CLS]']
        for char in text:
            if char in self.vocab:
                tokens.append(char)
            else:
                tokens.append('[UNK]')
        tokens.append('[SEP]')
        input_ids = [self.vocab[token] if token in self.vocab else self.vocab['[UNK]'] for token in tokens]
        return input_ids

    def preprocess(self, texts, max_length=128):
        """Preprocess input texts for BERT model."""
        input_ids_list = []
        attention_mask_list = []
        
        for text in texts:
            input_ids = self.tokenize(text)
            # Truncate or pad to max_length
            if len(input_ids) > max_length:
                input_ids = input_ids[:max_length]
            else:
                input_ids += [0] * (max_length - len(input_ids))

            attention_mask = [1 if idx != 0 else 0 for idx in input_ids]
            
            input_ids_list.append(input_ids)
            attention_mask_list.append(attention_mask)

        # Convert to NumPy arrays
        inputs = {
            'input_ids': np.array(input_ids_list, dtype=np.int64),
            'attention_mask': np.array(attention_mask_list, dtype=np.int64)
        }
        return inputs

    def mean_pooling_numpy(self, model_output, attention_mask):
        """Mean pooling for model output."""
        token_embeddings = model_output
        input_mask_expanded = np.expand_dims(attention_mask, -1).astype(float)
        return np.sum(token_embeddings * input_mask_expanded, axis=1) / np.clip(np.sum(input_mask_expanded, axis=1), a_min=1e-9, a_max=None)

    def compute_embeddings(self, texts):
        """Compute sentence embeddings for input texts."""
        onnx_inputs = self.preprocess(texts)
        # Run the model with ONNX Runtime
        onnx_outputs = self.onnx_session.run(None, onnx_inputs)
        last_hidden_state = onnx_outputs[0]
        # Perform mean pooling
        sentence_embeddings = self.mean_pooling_numpy(last_hidden_state, onnx_inputs['attention_mask'])
        return sentence_embeddings

    def match(self, cmd_embeddings, text_embedding):

        # Compute cosine similarity between each command embedding and the text embedding
        cmd_embeddings_norm = cmd_embeddings / np.linalg.norm(cmd_embeddings, axis=1, keepdims=True)
        text_embedding_norm = text_embedding / np.linalg.norm(text_embedding, axis=1,keepdims=True)
        
        # Cosine similarity calculation
        similarity_scores = np.dot(cmd_embeddings_norm, text_embedding_norm.T).squeeze()
        # Find the best match index and score
        best_match_idx = np.argmax(similarity_scores)
        best_score = similarity_scores[best_match_idx]
        
        return best_match_idx, best_score

def main():
    # Initialize the PIPE_NLU instance
    nlu = Text2Vector(model_dir=r"D:\code\text2vec-base-chinese-onnx")

    # Define a list of command sentences
    commands = [
        "打开音乐",
        "播放视频",
        "关闭灯光",
        "查询天气",
        "设置闹钟"
    ]

    # Define a target sentence to match against the command sentences
    target_sentence = "请播放音乐"

    # Compute embeddings for commands and the target sentence
    cmd_embeddings = nlu.compute_embeddings(commands)
    target_embedding = nlu.compute_embeddings([target_sentence])

    # Match the target sentence against the command embeddings
    best_match_idx, best_score = nlu.match(cmd_embeddings, target_embedding)

    # Output the results
    print(f"Best match command: {commands[best_match_idx]}")
    print(f"Similarity score: {best_score:.4f}")

if __name__ == "__main__":
    main()
```
