File size: 11,416 Bytes
e386d7a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Intro to Embedding"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For text retrieval, pattern matching is the most intuitive way. People would use certain characters, words, phrases, or sentence patterns. However, not only for human, it is also extremely inefficient for computer to do pattern matching between a query and a collection of text files to find the possible results. \n",
"\n",
"For images and acoustic waves, there are rgb pixels and digital signals. Similarly, in order to accomplish more sophisticated tasks of natural language such as retrieval, classification, clustering, or semantic search, we need a way to represent text data. That's how text embedding comes in front of the stage."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Background"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Traditional text embedding methods like one-hot encoding and bag-of-words (BoW) represent words and sentences as sparse vectors based on their statistical features, such as word appearance and frequency within a document. More advanced methods like TF-IDF and BM25 improve on these by considering a word's importance across an entire corpus, while n-gram techniques capture word order in small groups. However, these approaches suffer from the \"curse of dimensionality\" and fail to capture semantic similarity like \"cat\" and \"kitty\", difference like \"play the watch\" and \"watch the play\"."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# example of bag-of-words\n",
"sentence1 = \"I love basketball\"\n",
"sentence2 = \"I have a basketball match\"\n",
"\n",
"words = ['I', 'love', 'basketball', 'have', 'a', 'match']\n",
"sen1_vec = [1, 1, 1, 0, 0, 0]\n",
"sen2_vec = [1, 0, 1, 1, 1, 1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To overcome these limitations, dense word embeddings were developed, mapping words to vectors in a low-dimensional space that captures semantic and relational information. Early models like Word2Vec demonstrated the power of dense embeddings using neural networks. Subsequent advancements with neural network architectures like RNNs, LSTMs, and Transformers have enabled more sophisticated models such as BERT, RoBERTa, and GPT to excel in capturing complex word relationships and contexts. **BAAI General Embedding (BGE)** provide a series of open-source models that could satisfy all kinds of demands."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Get Embedding"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first step of modern text retrieval is embedding the text. So let's take a look at how to use the embedding models."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Install the packages:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"%%capture\n",
"%pip install -U FlagEmbedding sentence_transformers openai cohere"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os \n",
"os.environ['TRANSFORMERS_NO_ADVISORY_WARNINGS'] = 'true'\n",
"# single GPU is better for small tasks\n",
"os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll use the following three sentences as the inputs:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"sentences = [\n",
" \"That is a happy dog\",\n",
" \"That is a very happy person\",\n",
" \"Today is a sunny day\",\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Open-source Models"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A huge portion of embedding models are in the open source community. The advantages of open-source models include:\n",
"- Free, no extra cost. But make sure to check the License and your use case before using.\n",
"- No frequency limit, can accelerate a lot if you have enough GPUs to parallelize.\n",
"- Transparent and might be reproducible.\n",
"\n",
"Let's take a look at two representatives:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### BGE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"BGE is a series of embedding models and rerankers published by BAAI. Several of them reached SOTA at the time they released."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"initial target device: 100%|ββββββββββ| 8/8 [00:31<00:00, 3.89s/it]\n",
"Chunks: 100%|ββββββββββ| 3/3 [00:04<00:00, 1.61s/it]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Embeddings:\n",
"(3, 768)\n",
"Similarity scores:\n",
"[[1. 0.79 0.575 ]\n",
" [0.79 0.9995 0.592 ]\n",
" [0.575 0.592 0.999 ]]\n"
]
}
],
"source": [
"from FlagEmbedding import FlagModel\n",
"\n",
"# Load BGE model\n",
"model = FlagModel('BAAI/bge-base-en-v1.5')\n",
"\n",
"# encode the queries and corpus\n",
"embeddings = model.encode(sentences)\n",
"print(f\"Embeddings:\\n{embeddings.shape}\")\n",
"\n",
"scores = embeddings @ embeddings.T\n",
"print(f\"Similarity scores:\\n{scores}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Sentence Transformers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sentence Transformers is a library for sentence embeddings with a huge amount of embedding models and datasets for related tasks."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Embeddings:\n",
"(3, 384)\n",
"Similarity scores:\n",
"[[0.99999976 0.6210502 0.24906276]\n",
" [0.6210502 0.9999997 0.21061528]\n",
" [0.24906276 0.21061528 0.9999999 ]]\n"
]
}
],
"source": [
"from sentence_transformers import SentenceTransformer\n",
"\n",
"model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n",
"\n",
"embeddings = model.encode(sentences, normalize_embeddings=True)\n",
"print(f\"Embeddings:\\n{embeddings.shape}\")\n",
"\n",
"scores = embeddings @ embeddings.T\n",
"print(f\"Similarity scores:\\n{scores}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Commercial Models"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are also plenty choices of commercial models. They have the advantages of:\n",
"- Efficient memory usage, fast inference with no need of GPUs.\n",
"- Systematic support, commercial models have closer connections with their other products.\n",
"- Better training data, commercial models might be trained on larger, higher-quality datasets than some open-source models."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### OpenAI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Along with GPT series, OpenAI has their own embedding models. Make sure to fill in your own API key in the field `\"YOUR_API_KEY\"`"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"YOUR_API_KEY\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then run the following cells to get the embeddings. Check their official [documentation](https://platform.openai.com/docs/guides/embeddings) for more details."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"from openai import OpenAI\n",
"\n",
"client = OpenAI()\n",
"\n",
"response = client.embeddings.create(input = sentences, model=\"text-embedding-3-small\")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Embeddings:\n",
"(3, 1536)\n",
"Similarity scores:\n",
"[[1.00000004 0.697673 0.34739798]\n",
" [0.697673 1.00000005 0.31969923]\n",
" [0.34739798 0.31969923 0.99999998]]\n"
]
}
],
"source": [
"embeddings = np.asarray([response.data[i].embedding for i in range(len(sentences))])\n",
"print(f\"Embeddings:\\n{embeddings.shape}\")\n",
"\n",
"scores = embeddings @ embeddings.T\n",
"print(f\"Similarity scores:\\n{scores}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Voyage AI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Voyage AI provides embedding models and rerankers for different purpus and in various fields. Their API keys can be freely used in low frequency and token length."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"os.environ[\"VOYAGE_API_KEY\"] = \"YOUR_API_KEY\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Check their official [documentation](https://docs.voyageai.com/docs/api-key-and-installation) for more details."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"import voyageai\n",
"\n",
"vo = voyageai.Client()\n",
"\n",
"result = vo.embed(sentences, model=\"voyage-large-2-instruct\")"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Embeddings:\n",
"(3, 1024)\n",
"Similarity scores:\n",
"[[0.99999997 0.87282517 0.63276503]\n",
" [0.87282517 0.99999998 0.64720015]\n",
" [0.63276503 0.64720015 0.99999999]]\n"
]
}
],
"source": [
"embeddings = np.asarray(result.embeddings)\n",
"print(f\"Embeddings:\\n{embeddings.shape}\")\n",
"\n",
"scores = embeddings @ embeddings.T\n",
"print(f\"Similarity scores:\\n{scores}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "dev",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|