在构建基于 RAG(Retrieval-Augmented Generation)的系统时,向量化是核心步骤之一。它涉及将文本数据转换为数值向量,以便能够高效地进行相似性搜索和检索。以下是关于如何向量化以及向量化文件存放位置的详细说明。


1. 向量化的过程

(1) 文本嵌入

向量化的核心是将文本数据转化为高维向量表示(Embedding)。通常使用预训练的语言模型来生成这些向量。以下是常见的方法:

  • 使用 Sentence Transformers

    • Sentence Transformers 是一个强大的库,可以将文本直接转换为高质量的嵌入向量。
    • 示例代码:
      from sentence_transformers import SentenceTransformer
      
      # 加载预训练模型
      model = SentenceTransformer('all-MiniLM-L6-v2')
      
      # 将文本转换为向量
      texts = ["这是一个示例句子", "这是另一个示例"]
      embeddings = model.encode(texts)
      print(embeddings.shape)  # 输出:(2, 384),其中 384 是向量维度
  • 使用 Ollama 的 deepseek-R1 模型

    • 如果你希望直接使用 Ollama 的 deepseek-R1 模型生成嵌入向量,可以通过调用其 API 来实现。
    • 示例代码:
      import requests
      import json
      
      def get_embedding(text):
          response = requests.post(
              "http://localhost:11434/api/embeddings",
              json={"model": "deepseek-r1:1.5b", "input": text}
          )
          data = response.json()
          return data["embedding"]
      
      text = "这是一个示例句子"
      embedding = get_embedding(text)
      print(len(embedding))  # 输出向量维度
(2) 存储向量

生成的向量需要存储以便后续检索。常见的存储方式包括:

  • 本地文件

    • 使用 .npy 文件保存 NumPy 数组。
    • 示例代码:
      import numpy as np
      
      # 假设 embeddings 是一个形状为 (n, d) 的 NumPy 数组
      np.save("embeddings.npy", embeddings)
      
      # 加载向量
      loaded_embeddings = np.load("embeddings.npy")
  • 数据库

    • 使用专门的向量数据库(如 Milvus、Pinecone 或 Weaviate)存储向量。
    • 示例代码(以 Milvus 为例):
      from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection
      
      # 连接到 Milvus
      connections.connect("default", host="localhost", port="19530")
      
      # 定义集合 schema
      fields = [
          FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
          FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=384)
      ]
      schema = CollectionSchema(fields, "RAG Embeddings")
      
      # 创建集合
      collection = Collection("rag_embeddings", schema)
      
      # 插入向量
      data = [
          [i for i in range(len(embeddings))],  # ID 列
          embeddings.tolist()                  # 向量列
      ]
      collection.insert(data)
      
      # 创建索引
      index_params = {
          "index_type": "IVF_FLAT",
          "params": {"nlist": 128},
          "metric_type": "L2"
      }
      collection.create_index(field_name="embedding", index_params=index_params)

2. 向量化文件存放在哪里?

向量化文件的存放位置取决于你的需求和使用的工具:

(1) 本地存储
  • 如果项目规模较小,可以直接将向量存储在本地文件中,例如 .npy 或 .json 文件。
  • 示例路径:
    ./data/embeddings.npy
(2) 数据库存储
  • 对于大规模应用,建议使用向量数据库(如 Milvus、Pinecone 或 Weaviate)来存储和管理向量。
  • 数据库存放位置通常是服务器上的专用存储目录,具体路径由数据库配置决定。
(3) 云存储
  • 如果使用云服务(如 AWS S3、Google Cloud Storage),可以将向量文件上传到云端存储。
  • 示例路径:
    s3://your-bucket-name/embeddings/

3. 使用 Ollama 的 deepseek-R1 模型生成向量

Ollama 提供了 /api/embeddings 接口,可以用于生成文本嵌入向量。以下是完整的流程:

(1) 获取嵌入向量

通过 Ollama 的 API 获取文本的嵌入向量:

import requests
import json

def get_embedding(text):
    response = requests.post(
        "http://localhost:11434/api/embeddings",
        json={"model": "deepseek-r1:1.5b", "input": text}
    )
    if response.status_code == 200:
        data = response.json()
        return data["embedding"]
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None

# 示例
text = "这是一个示例句子"
embedding = get_embedding(text)
if embedding:
    print(f"Embedding shape: {len(embedding)}")
(2) 存储嵌入向量

将生成的嵌入向量存储到本地或数据库中:

  • 本地存储

    import numpy as np
    
    embeddings = [get_embedding(t) for t in texts]
    np.save("embeddings.npy", embeddings)
  • 数据库存储: 使用 Milvus 等向量数据库存储向量,参考前面的示例代码。


4. 总结

  • 向量化过程:使用 Sentence Transformers 或 Ollama 的 /api/embeddings 接口将文本转换为向量。
  • 向量化文件存放位置
    • 小规模应用:本地文件(如 .npy)。
    • 大规模应用:向量数据库(如 Milvus、Pinecone)或云存储。
  • Ollama deepseek-R1 模型:可以通过 /api/embeddings 接口生成高质量的嵌入向量。
Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐