python embedding vector

1. Embedding Vector là gì?

Embedding vector là một vector nhiều chiều biểu diễn một thực thể (chẳng hạn như từ ngữ, câu, hình ảnh, người dùng, sản phẩm...) sao cho:

  • Những thực thể có ngữ nghĩa tương đồng sẽ có vector gần nhau trong không gian vector.

  • Khoảng cách giữa các vector có thể dùng để đo lường sự tương đồng (ví dụ: cosine similarity).

Ví dụ:

  • Vector biểu diễn từ "king" và "queen" sẽ có sự liên hệ với nhau thông qua giới tính.

  • Từ "Paris" và "France" có thể gần nhau hơn "Paris" và "banana".

Dưới đây là đoạn code demo để tạo embel mà các bạn có thể download về và tạo docker để chạy như 1 serverless

from fastapi import FastAPI
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
from typing import List
import uvicorn


app = FastAPI()
# model = SentenceTransformer("all-MiniLM-L6-v2")
model = SentenceTransformer("all-mpnet-base-v2")

class TextsRequest(BaseModel):
    texts: List[str]

@app.get("/")
async def index():
    return {"thongbao": "serveless tạo embedding vector"}

@app.post("/embed")
async def create_embeddings(request: TextsRequest):
    embeddings = model.encode(request.texts).tolist()
    return {"vectors": embeddings}

# Chạy app nếu chạy file trực tiếp
if __name__ == "__main__":
    uvicorn.run("main:app", reload=True)
# chạy command uvicorn app:app --host 127.0.0.1 --port 8888 --reload  sao không post uploads được

Vậy là bạn đã có thể có 1 serverless chạy để tạo vector import vào weaviate ,FAISS , redis vector ,Milvus ,...