{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Shawhin Talebi",
  "title_listed": "Text Embeddings, Classification, and Semantic Search",
  "keywords": "文本嵌入,语义搜索",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/text-embeddings-classification-and-semantic-search-8291746220be/",
  "publish_date": "2024-03",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "c46628e7fff9",
  "collected_at": "2026-10-01T22:58:16",
  "title": "Text Embeddings, Classification, and Semantic Search | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Text Embeddings, Classification, and Semantic Search\nAn introduction with example Python code\n[Shaw Talebi](https://towardsdatascience.com/author/shawhin/)\nMarch 27, 202412 min read\nThis article is part of a [larger series](https://shawhin.medium.com/list/large-language-models-llms-8e009ae3054c) on using large language models (LLMs) in practice. In the [previous post](https://towardsdatascience.com/how-to-improve-llms-with-rag-abdc132f76ac), we saw how to improve an LLM via retrieval-augmented generation (i.e. RAG). A key part of RAG was using text embeddings to retrieve relevant information from a knowledge base automatically. Here, I will discuss text embeddings more deeply and share two simple (yet powerful) applications: text classification and semantic search.\n![Photo by Daniel Lerman on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/0wka3oBwbhobH8HW_-scaled.jpg)\nPhoto by [Daniel Lerman](https://unsplash.com/@dlerman6?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n* * *\nChatGPT captured the world's imagination regarding AI and its potential. A key contributor to this impact was ChatGPT's chat interface, which made the power of AI more accessible than ever before.\nWhile this unlocked a new level of AI hype and awareness, all the excitement around this \"chatbot paradigm\" left another key innovation (largely) unnoticed.\n**LLMs brought** **major innovations** **in text embeddings**. Here, I'll explain these and how we can use them for simple yet high-value use cases.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist), [AI Engineer](https://roadmap.sh/ai-engineer) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\nPlease accept cookies to access this content\n## **Text embeddings**\nText embeddings **translate words into numbers**. However, these aren't just any numbers. They are numbers that capture the _meaning_ of the underlying text.\nThis is important because numbers are (much) easier to analyze than words.\nFor example, if you are at a networking event and want to know the typical height of people in the room, you can measure everyone's height and compute the average using Microsoft Excel. However, if you want to know the typical job title of the people in the room, there's no Excel function to help you.\nThis is where text embeddings can help. If we have a good way to turn text into numbers, **we unlock a massive toolbox of existing statistical and machine-learning techniques** to investigate textual data.\n## **Text embeddings (Visually Explained)**\nLet's look at a visual example to better understand what it means to \"translate text into numbers\" [1].\nConsider the following set of text: _tree_ , _lotus_ _flower_ , _daisy_ , _sun_ , _Saturn_ , _Jupiter_ , _satellite_ , _space_ _shuttle_ , _basketball_ , and _baseball_.\nWhile this may seem like a random assortment of words, **some of these concepts are more** _**similar**_**than others**. We can convey these similarities (and differences) in the following way.\n![Visual representation of text embeddings. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1YHxNDy26jDdpEZe3vKQDpg.png)\nVisual representation of text embeddings. Image by author.\nThe above visualization intuitively organizes the concepts. Similar items (e.g., tree, daisy, and lotus flower) tend to be close together, while dissimilar items (e.g., tree and baseball) tend to be far apart.\nNumbers fit into this picture because we can assign coordinates to each word based on its location in the plot above. **These coordinates (i.e. numbers) can then be used to analyze the underlying text**.\n![Coordinates can be used to analyze relationships between text. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1NI36ZN1MTHxRePIcZ3LGPw.png)\nCoordinates can be used to analyze relationships between text. Image by author.\n## **Where do they come from?**\nTurning text into numbers to make it more computable is not a new idea. Researchers have explored this since the early days of computing (circa 1950) [2].\nWhile there are countless ways people have done this over the years [2], these days, state-of-the-art text representations are derived from large language models (LLMs).\nThis works because **LLMs learn (very) good numerical representations of text** during their training. The layers that generate these representations can be dissected from the model and used in a stand-alone way. The result of this process is a text embedding model.\n![3-step recipe for creating an embedding model. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1hFYc2borW8dsRqyePdrw_A.png)\n3-step recipe for creating an embedding model. Image by author.\n## **Can't I just use ChatGPT?**\nBefore moving on to the example use cases, you might think, \"_Shaw, why should I care about these text embedding things? Can't I just make a custom ChatGPT to analyze the text for me?_ \"\nOf course, one can use techniques like [RAG](https://towardsdatascience.com/how-to-improve-llms-with-rag-abdc132f76ac) or [Fine-tuning](https://medium.com/towards-data-science/fine-tuning-large-language-models-llms-23473d763b91) to build an AI agent tailored to their specific problem set. However, it's still the early days for these systems, which makes **building a robust AI agent** (i.e. not a prototype) **an expensive and non-trivial engineering problem** (e.g. major computational costs, [LLM security risks](https://owasp.org/www-project-top-10-for-large-language-model-applications/), unpredictable responses, and hallucinations)\nOn the other hand, text embeddings have been around for decades, are lightweight, and non-stochastic (i.e. predictable). Thus, building AI systems with them is **much simpler and cheaper than building an AI agent** (while still capturing much of the value - if not more).\n## **Use Case 1: Text Classification**\nWith a basic understanding of text embeddings, let's see how we can use them to help solve real-world problems.\nFirst, we will discuss **text classification**. This consists of **assigning a label to a given text**. For example, labeling an email as spam or not spam, a credit application as high risk or low risk, or a security alert as the real deal or a false alarm.\nIn this example, I will use text embeddings to classify resumes as \"_Data Scientist_ \" or \"_Not Data Scientist_ ,\" which may be relevant for recruiters trying to navigate an ocean of job candidates.\nTo avoid privacy issues, I created a synthetic dataset of resumes using [gpt-3.5-turbo](https://platform.openai.com/docs/models/gpt-3-5-turbo). While using synthetic data requires us to take the results with a grain of salt, this example still provides an instructive demonstration of how to use text embeddings to classify.\nThe example code and data are freely available at the [GitHub repository](https://github.com/ShawhinT/YouTube-Blog/tree/main/LLMs/text-embeddings).\n* * *\n### Imports\nWe start by importing dependencies. In this example, I use a text embedding model from [OpenAI](https://platform.openai.com/docs/guides/embeddings), which requires an API key. If you are unfamiliar with the OpenAI API, I give a beginner-friendly primer in a [previous article](https://towardsdatascience.com/cracking-open-the-openai-python-api-230e4cae7971) of this series. Here, my API key is stored in a separate file called _sk.py_.\npython\n\n```\nimport openai\nfrom sk import my_sk\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score\n```\n\nNext, we read our synthetic training dataset as a Pandas dataframe. The data comes from a .csv file with two columns consisting of resume text and the associated role.\npython\n\n```\ndf_resume = pd.read_csv('resumes/resumes_train.csv')\n```\n\n### Generate Embeddings\nTo translate the resumes into embeddings, we can make a simple API call to the OpenAI API. This is done by the function below.\npython\n\n```\ndef generate_embeddings(text, my_sk):\n    # set credentials\n    client = openai.OpenAI(api_key = my_sk)\n\n    # make api call\n    response = client.embeddings.create(\n        input=text,\n        model=\"text-embedding-3-small\"\n    )\n\n    # return text embedding\n    return response.data\n```\n\nWe can now apply this function to each resume in our dataframe and store the result in a list.\npython\n\n```\n# generate embeddings\ntext_embeddings = generate_embeddings(df_resume['resume'], my_sk)\n\n# extract embeddings\ntext_embedding_list = \n  [text_embeddings[i].embedding for i in range(len(text_embeddings))]\n```\n\n### Store Embeddings in Dataframe\nNext, we'll create a new dataframe to store the text embeddings and our target variable for model training.\npython\n\n```\n# define df column names\ncolumn_names = \n  [\"embedding_\" + str(i) for i in range(len(text_embedding_list[0]))]\n\n# store text embeddings in dataframe\ndf_train = pd.DataFrame(text_embedding_list, columns=column_names)\n\n# create target variable\ndf_train['is_data_scientist'] = df_resume['role']==\"Data Scientist\"\n```\n\n### Model Training\nWith our training data prepared we can now train our classification model in one line of code. Here, I use a Random Forest classifier, which I discussed in a [past article](https://towardsdatascience.com/10-decision-trees-are-better-than-1-719406680564).\npython\n\n```\n# split variables by predictors and target\nX = df_train.iloc[:,:-1]\ny = df_train.iloc[:,-1]\n\n# train rf model\nclf = RandomForestClassifier(max_depth=2, random_state=0).fit(X, y)\n```\n\n### Model Evaluation\nTo get a quick sense of the model's performance we can evaluate it on the training data. Here, I compute the [mean accuracy](https://scikit-learn.org/stable/modules/model_evaluation.html#accuracy-score) and area under the ROC (i.e., [AUC](https://scikit-learn.org/stable/modules/model_evaluation.html#roc-metrics)).\npython\n\n```\n# model accuracy for training data\nprint(clf.score(X,y))\n\n# AUC value for training data\nprint(roc_auc_score(y, clf.predict_proba(X)[:,1]))\n\n# output\n# 1\n# 1\n```\n\nThe accuracy and AUC values of 1 indicate perfect performance on the training dataset, which is _suspicious_. So let's evaluate it on a testing dataset the model has never seen before.\nmakefile\n\n```\n# import testing data\ndf_resume = pd.read_csv('resumes/resumes_test.csv')\n\n# generate embeddings\ntext_embedding_list = generate_embeddings(df_resume['resume'], my_sk)\ntext_embedding_list = \n  [text_embedding_list[i].embedding for i in range(len(text_embedding_list))]\n\n# store text embeddings in dataframe\ndf_test = pd.DataFrame(text_embedding_list, columns=column_names)\n\n# create target variable\ndf_test['is_data_scientist'] = df_resume['role']==\"Data Scientist\"\n\n# define predictors and target\nX_test = df_test.iloc[:,:-1]\ny_test = df_test.iloc[:,-1]\n```\n\npython\n\n```\n# model accuracy for testing data\nprint(clf.score(X_test,y_test))\n\n# AUC value for testing data\nprint(roc_auc_score(y_test, clf.predict_proba(X_test)[:,1]))\n\n# output\n# 0.98\n# 0.9983333333333333\n```\n\n### **Resolving overfitting**\nAlthough the model performs well when applied to the testing data, it is still likely overfitting for two reasons.\n**One** , we have 1537 predictors and only 100 resumes to predict, so it wouldn't be hard for the model to \"memorize\" every example in the training data. **Two** , the training and testing data were generated from [gpt-3.5-turbo](https://platform.openai.com/docs/models/gpt-3-5-turbo) in a similar way. Thus, they share many characteristics, which makes the classification task easier than if applied to real data.\nThere are many tricks we can employ to **overcome the overfitting problem** , e.g., reducing predictor count using predictor importance ranking, increasing the minimum number of samples in a leaf node, or using a simpler classification technique like logistic regression. However, if our goal is to use this model in a practical setting, the best option would be to gather **more data** and use **resumes from the real world**.\n## **Use Case 2: Semantic Search**\nNext, let's look at semantic search. In contrast to keyword-based search, semantic search **generates results based on the** _**meaning**_**of a user's query** rather than the particular words or phrases used.\nFor example, keyword-based searches may not provide great results for the query \"_I need someone to build out my data infrastructure_ \" since it doesn't specifically mention the role that builds data infrastructure (i.e., a data engineer). However, this is not a concern for semantic search since it can match the query to candidates with experience like \"_Proficient in data modeling, ETL processes, and data warehousing._ \"\nHere, we will use text embeddings to enable this type of search over the same dataset as in the previous use case. Example code is (again) available at the [GitHub repo](https://github.com/ShawhinT/YouTube-Blog/tree/main/LLMs/text-embeddings).\n* * *\n### Imports\nWe start by importing dependencies and the synthetic dataset.\npython\n\n```\nimport numpy as np\nimport pandas as pd\n\nfrom sentence_transformers import SentenceTransformer\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import DistanceMetric\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n```\n\npython\n\n```\ndf_resume = pd.read_csv('resumes/resumes_train.csv')\n\n# relabel random role as \"other\"\ndf_resume['role'][df_resume['role'].iloc[-1] == df_resume['role']] = \"Other\" \n```\n\n### Generate Embeddings\nNext, we'll generate the text embeddings. Instead of using the [OpenAI API](https://platform.openai.com/docs/guides/embeddings), we will use an open-source model from the [Sentence Transformers](https://www.sbert.net/) Python library. This model was specifically fine-tuned for semantic search.\npython\n\n```\n# import pre-trained model (full list: https://www.sbert.net/docs/pretrained_models.html)\nmodel = SentenceTransformer(\"all-MiniLM-L6-v2\")\n\n# encode text\nembedding_arr = model.encode(df_resume['resume'])\n```\n\nTo see the different resumes in the dataset and their relative locations in concept space, we can use [PCA](https://towardsdatascience.com/principal-component-analysis-pca-79d228eb9d24) to reduce the dimensionality of the embedding vectors and visualize the data on a 2D plot (code is on [GitHub](https://github.com/ShawhinT/YouTube-Blog/blob/main/LLMs/text-embeddings/2-semantic-search.ipynb)).\nFrom this view we see the resumes for a given role tend to clump together.\n![2D plot of resume embeddings colored by role. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/16NMvNijuM5QLdgDwDKritg.png)\n2D plot of resume embeddings colored by role. Image by author.\n### Semantic Search\nNow, to do a semantic search over these resumes, we can take a user query, translate it into a text embedding, and then return the nearest resumes in the embedding space. Here's what that looks like in code.\npython\n\n```\n# define query\nquery = \"I need someone to build out my data infrastructure\"\n\n# encode query\nquery_embedding = model.encode(query)\n```\n\npython\n\n```\n# define distance metric (other options: manhattan, chebyshev)\ndist = DistanceMetric.get_metric('euclidean')\n\n# compute pair-wise distances between query embedding and resume embeddings\ndist_arr = \n  dist.pairwise(embedding_arr, query_embedding.reshape(1, -1)).flatten()\n# sort results\nidist_arr_sorted = np.argsort(dist_arr)\n```\n\nPrinting the roles of the top 10 results, we see almost all are data engineers, which is a good sign.\npython\n\n```\n# print roles of top 10 closest resumes to query in embedding space\nprint(df_resume['role'].iloc[idist_arr_sorted[:10]])\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1qWG9RH-oImP9vkBPyqHl_w.png)\nLet's look at the resume of the top search results.\npython\n\n```\n# print resume closest to query in embedding space\nprint(df_resume['resume'].iloc[idist_arr_sorted[0]])\n```\n\nplaintext\n\n```\n**John Doe**\n\n---\n\n**Summary:**\nHighly skilled and experienced Data Engineer with a strong background in \ndesigning, implementing, and maintaining data pipelines. Proficient in data \nmodeling, ETL processes, and data warehousing. Adept at working with large \ndatasets and optimizing data workflows to improve efficiency.\n\n---\n\n**Professional Experience:**\n- **Senior Data Engineer**  \n  XYZ Tech, Anytown, USA  \n  June 2018 - Present  \n  - Designed and developed scalable data pipelines to handle terabytes of data daily.\n  - Optimized ETL processes to improve data quality and processing time by 30%.\n  - Collaborated with cross-functional teams to implement data architecture best practices.\n\n- **Data Engineer**  \n  ABC Solutions, Sometown, USA  \n  January 2015 - May 2018  \n  - Built and maintained data pipelines for real-time data processing.\n  - Developed data models and implemented data governance policies.\n  - Worked on data integration projects to streamline data access for business users.\n\n---\n\n**Education:**\n- **Master of Science in Computer Science**  \n  University of Technology, Cityville, USA  \n  Graduated: 2014\n\n- **Bachelor of Science in Computer Engineering**  \n  State College, Hometown, USA  \n  Graduated: 2012\n\n---\n\n**Technical Skills:**\n- Programming: Python, SQL, Java\n- Big Data Technologies: Hadoop, Spark, Kafka\n- Databases: MySQL, PostgreSQL, MongoDB\n- Data Warehousing: Amazon Redshift, Snowflake\n- ETL Tools: Apache NiFi, Talend\n- Data Visualization: Tableau, Power BI\n\n---\n\n**Certifications:**\n- Certified Data Management Professional (CDMP)\n- AWS Certified Big Data - Specialty\n\n---\n\n**Awards and Honors:**\n- Employee of the Month - XYZ Tech (July 2020)\n- Outstanding Achievement in Data Engineering - ABC Solutions (2017)\n```\n\nAlthough this is a made-up resume, the candidate likely has all the necessary skills and experience to fulfill the user's needs.\nAnother way to look at the search results is via the 2D plot from before. Here's what that looks like for a few queries (see plot titles).\n![2D PCA plots for 3 different queries. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1SdJwEcsXf9s2cZ-fKsRGEg.png)\n2D PCA plots for 3 different queries. Image by author.\n### **Improving search**\nWhile this simple search example does a good job of matching particular candidates to a given query, it is not perfect. One shortcoming is when the user query includes a specific skill. For example, in the query \"_Data Engineer with Apache Airflow experience_ ,\" only 1 of the top 5 results have Airflow experience.\nThis highlights that **semantic search is not better than keyword-based search in all situations**. Each has its strengths and weaknesses.\nThus, a robust search system will employ so-called **hybrid search** , which **combines the best of both techniques**. While there are many ways to design such a system, a simple approach is applying keyword-based search to filter down results, followed by semantic search.\nTwo additional strategies for improving search are using a **Reranker** and **fine-tuning text embeddings**.\nA **Reranker** is a model that **directly compares two pieces of text**. In other words, instead of computing the similarity between pieces of text via a distance metric in the embedding space, a Reranker computes such a similarity score directly.\nRerankers are commonly used to refine search results. For example, one can return the top 25 results using semantic search and then refine to the top 5 with a Reranker.\n**Fine-tuning text embeddings** involves **adapting an embedding model for a particular domain**. This is a powerful approach because most embedding models are based on a broad collection of text and knowledge. Thus, they may not optimally organize concepts for a specific industry, e.g. data science and AI.\n> [**YouTube-Blog/LLMs/text-embeddings at main · ShawhinT/YouTube-Blog**](https://github.com/ShawhinT/YouTube-Blog/tree/main/LLMs/text-embeddings)\n## Conclusion\nAlthough everyone seems focused on the potential for AI agents and assistants, recent innovations in text-embedding models have unlocked countless opportunities for simple yet high-value ML use cases.\nHere, we reviewed two widely applicable use cases: text classification and semantic search. Text embeddings enable simpler and cheaper alternatives to LLM-based methods while still capturing much of the value.\n**More on LLMs 👇**\n> [**Large Language Models (LLMs)**](https://shawhin.medium.com/list/8e009ae3054c)\n* * *\n## Resources\n**Connect** : [My website](https://shawhintalebi.com/) | [Book a call](https://calendly.com/shawhintalebi)\n**Socials** : [YouTube 🎥 ](https://www.youtube.com/channel/UCa9gErQ9AE5jT2DZLjXBIdA) | [LinkedIn](https://www.linkedin.com/in/shawhintalebi/) | [Instagram](https://www.instagram.com/shawhintalebi)\n**Support** : [Buy me a coffee](https://www.buymeacoffee.com/shawhint) ☕️\n> [**Get FREE access to every new story I write**](https://shawhin.medium.com/subscribe)\n* * *\n[1] <https://youtu.be/A8HEPBdKVMA?si=PA4kCnfgd3nx24LR>\n[2] R. Patil, S. Boit, V. Gudivada and J. Nandigam, \"[A Survey of Text Representation and Embedding Techniques in NLP](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=10098736),\" in IEEE Access, vol. 11, pp. 36120–36146, 2023, doi: 10.1109/ACCESS.2023.3266377.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657074748_utev3i.jpeg)\nWritten By\n## [Shaw Talebi](https://towardsdatascience.com/author/shawhin/)\n[See all from Shaw Talebi](https://towardsdatascience.com/author/shawhin/)\n[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Large Language Models](https://towardsdatascience.com/tag/large-language-models/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Semantic Search](https://towardsdatascience.com/tag/semantic-search/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ftext-embeddings-classification-and-semantic-search-8291746220be%2F&title=Text%20Embeddings%2C%20Classification%2C%20and%20Semantic%20Search)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ftext-embeddings-classification-and-semantic-search-8291746220be%2F&title=Text%20Embeddings%2C%20Classification%2C%20and%20Semantic%20Search)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ftext-embeddings-classification-and-semantic-search-8291746220be%2F&text=Text%20Embeddings%2C%20Classification%2C%20and%20Semantic%20Search)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1Q2mWWABOtlN0SFU3J_0kPQ-scaled.jpeg)](https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922/)\n## [SQL vs NoSQL in 8 Examples](https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nPractical guide to compare basic operations in both\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJanuary 23, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/02/Zhyvov-1.png)](https://towardsdatascience.com/4-dimensional-data-visualization-time-in-bubble-charts/)\n## [4-Dimensional Data Visualization: Time in Bubble Charts](https://towardsdatascience.com/4-dimensional-data-visualization-time-in-bubble-charts/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nBubble charts typically display 3 dimensions using x, y, and bubble size, but adding time as a 4th dimension can provide deeper insights.\n[Vladimir Zhyvov](https://towardsdatascience.com/author/vzhyvov/)\nFebruary 11, 202510 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/1QPfQZPtqKV_Ju_zgngD72Q.png)](https://towardsdatascience.com/appworld-a-controllable-world-of-apps-and-people-for-benchmarking-interactive-coding-agents-37517dd9d498/)\n## [Can AI Agents Do Your Day-to-Day Tasks on Apps?](https://towardsdatascience.com/appworld-a-controllable-world-of-apps-and-people-for-benchmarking-interactive-coding-agents-37517dd9d498/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nBenchmarking coding agents in a world of apps and people\n[Harsh Trivedi](https://towardsdatascience.com/author/harshjtrivedi94/)\nJuly 28, 20247 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/1ZIqERFvQv4sZXsCjXg3cgw.jpg)](https://towardsdatascience.com/black-box-hyperparameter-tuning-in-python-478c10adc959/)\n## [Black-box Hyperparameter Tuning in Python](https://towardsdatascience.com/black-box-hyperparameter-tuning-in-python-478c10adc959/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nComparing Brute Force and Black-box Optimization Methods in Python\n[Sadrach Pierre, Ph.D.](https://towardsdatascience.com/author/spierre91/)\nAugust 12, 202210 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/1V7VIEu1j-CtUxblzFaXjzA.gif)](https://towardsdatascience.com/fourier-transforms-animated-visualization-5bdb43b4b3d2/)\n## [Fourier Transforms: Animated Visualization](https://towardsdatascience.com/fourier-transforms-animated-visualization-5bdb43b4b3d2/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAnimating a Simple Example of Fourier Transforms\n[Diego Unzueta](https://towardsdatascience.com/author/diegounzuetaruedas/)\nOctober 12, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/1-U9yz5lDZHIcpcXkb3K2zQ-scaled.jpeg)](https://towardsdatascience.com/10-tips-i-wish-i-had-known-before-starting-a-data-journey-905d83f06c33/)\n## [10 tips I wish I had known before starting a Data Journey](https://towardsdatascience.com/10-tips-i-wish-i-had-known-before-starting-a-data-journey-905d83f06c33/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAfter more than 6 years working with data, here's what I would have loved to know before starting this amazing journey\n[Carlos Bort](https://towardsdatascience.com/author/carlosbort/)\nSeptember 1, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/1i-84RINOvVFkD9txsVDjDQ-scaled.jpeg)](https://towardsdatascience.com/30-questions-to-ask-before-you-code-5f2c486641b0/)\n## [30 Questions to Ask Before You Code](https://towardsdatascience.com/30-questions-to-ask-before-you-code-5f2c486641b0/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nI ask these questions before coding my next data science engineering project.\n[Rose Day](https://towardsdatascience.com/author/rjday/)\nOctober 6, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1mCri8uXsIyFeRH26FVm5CQ.png)](https://towardsdatascience.com/implementing-gene-drives-into-genetic-algorithms-d245a5cc989f/)\n## [Implementing Gene Drives into Genetic Algorithms](https://towardsdatascience.com/implementing-gene-drives-into-genetic-algorithms-d245a5cc989f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHumans have turned to nature to find highly optimized systems, that have stood against the test of time. In the case of genetic algorithms...\n[Victor Sim](https://towardsdatascience.com/author/victorsim14/)\nNovember 6, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/04wqKU3rPkn4pTdi5-scaled.jpg)](https://towardsdatascience.com/multilevel-regression-models-and-simpsons-paradox-acb9820e836d/)\n## [Multilevel Regression Models and Simpson's paradox](https://towardsdatascience.com/multilevel-regression-models-and-simpsons-paradox-acb9820e836d/)\n[](https://towardsdatascience.com/text-embeddings-classification-and-semantic-search-8291746220be/)\nAvoiding false conclusions with the proper tooling\n[Dorian Drost](https://towardsdatascience.com/author/doriandrost/)\nAugust 8, 202310 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607631/image?etag=1781543525510&width=500&height=500) Critical Mistakes Companies Make When Integrating AI/ML into Their Processes ](https://towardsdatascience.com/critical-mistakes-companies-make-when-integrating-ai-ml-into-their-processes/ \"Critical Mistakes Companies Make When Integrating AI/ML into Their Processes\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n\n\n",
  "metadata": {
    "title": "Text Embeddings, Classification, and Semantic Search | Towards Data Science",
    "description": "An introduction with example Python code",
    "keywords": null,
    "author": "Shaw Talebi",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Text Embeddings, Classification, and Semantic Search",
    "og:description": "An introduction with example Python code",
    "og:url": "https://towardsdatascience.com/text-embeddings-classification-and-semantic-search-8291746220be/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/0wka3oBwbhobH8HW_-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1707",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Shaw Talebi",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2024-03-27T13:04:18.000Z",
    "article:modified_time": "2024-03-27T13:04:18.000Z",
    "article:author": "https://towardsdatascience.com/author/shawhin/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_000.txt",
      "chars": 202
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_001.txt",
      "chars": 53
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_002.txt",
      "chars": 285
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_003.txt",
      "chars": 203
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_004.txt",
      "chars": 310
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_005.txt",
      "chars": 178
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_006.txt",
      "chars": 157
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_007.txt",
      "chars": 554
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_008.txt",
      "chars": 195
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_009.txt",
      "chars": 234
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_010.txt",
      "chars": 165
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_011.txt",
      "chars": 203
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_012.txt",
      "chars": 130
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_013.txt",
      "chars": 326
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_014.txt",
      "chars": 121
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_015.txt",
      "chars": 104
    },
    {
      "language": "txt",
      "file": "attachments/c46628e7fff9/code/block_016.txt",
      "chars": 1760
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/0wka3oBwbhobH8HW_-scaled.jpg",
      "alt": "Photo by Daniel Lerman on Unsplash",
      "local_path": "attachments/c46628e7fff9/images/000.jpg",
      "bytes": 260906,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1YHxNDy26jDdpEZe3vKQDpg.png",
      "alt": "Visual representation of text embeddings. Image by author.",
      "local_path": "attachments/c46628e7fff9/images/001.png",
      "bytes": 23574,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1NI36ZN1MTHxRePIcZ3LGPw.png",
      "alt": "Coordinates can be used to analyze relationships between text. Image by author.",
      "local_path": "attachments/c46628e7fff9/images/002.png",
      "bytes": 34826,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1hFYc2borW8dsRqyePdrw_A.png",
      "alt": "3-step recipe for creating an embedding model. Image by author.",
      "local_path": "attachments/c46628e7fff9/images/003.png",
      "bytes": 47167,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/16NMvNijuM5QLdgDwDKritg.png",
      "alt": "2D plot of resume embeddings colored by role. Image by author.",
      "local_path": "attachments/c46628e7fff9/images/004.png",
      "bytes": 30678,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1SdJwEcsXf9s2cZ-fKsRGEg.png",
      "alt": "2D PCA plots for 3 different queries. Image by author.",
      "local_path": "attachments/c46628e7fff9/images/005.png",
      "bytes": 135753,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1Q2mWWABOtlN0SFU3J_0kPQ-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/006.jpeg",
      "bytes": 304287,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/02/Zhyvov-1.png",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/007.png",
      "bytes": 229712,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/1QPfQZPtqKV_Ju_zgngD72Q.png",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/008.png",
      "bytes": 613611,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/1ZIqERFvQv4sZXsCjXg3cgw.jpg",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/009.jpg",
      "bytes": 331833,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/1V7VIEu1j-CtUxblzFaXjzA.gif",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/010.gif",
      "bytes": 8715945,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/1-U9yz5lDZHIcpcXkb3K2zQ-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/011.jpeg",
      "bytes": 547182,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/1i-84RINOvVFkD9txsVDjDQ-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/012.jpeg",
      "bytes": 232368,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1mCri8uXsIyFeRH26FVm5CQ.png",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/013.png",
      "bytes": 231171,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/04wqKU3rPkn4pTdi5-scaled.jpg",
      "alt": "",
      "local_path": "attachments/c46628e7fff9/images/014.jpg",
      "bytes": 509265,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [
    {
      "src": "https://www.youtube.com/channel/UCa9gErQ9AE5jT2DZLjXBIdA",
      "quality": "unavailable",
      "local_path": "",
      "note": "无1080p且无720p，未交付更低清晰度"
    },
    {
      "src": "https://youtu.be/A8HEPBdKVMA?si=PA4kCnfgd3nx24LR>",
      "quality": "unavailable",
      "local_path": "",
      "note": "无1080p且无720p，未交付更低清晰度"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shawhin/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-improve-llms-with-rag-abdc132f76ac"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/cracking-open-the-openai-python-api-230e4cae7971"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/10-decision-trees-are-better-than-1-719406680564"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/principal-component-analysis-pca-79d228eb9d24"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/large-language-models/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/semantic-search/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/sql-vs-nosql-in-8-examples-25aebcf49922/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/sonery/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/4-dimensional-data-visualization-time-in-bubble-charts/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://shawhin.medium.com/list/large-language-models-llms-8e009ae3054c"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@dlerman6"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://medium.com/towards-data-science/fine-tuning-large-language-models-llms-23473d763b91"
    },
    {
      "type": "external",
      "href": "https://owasp.org/www-project-top-10-for-large-language-model-applications/"
    },
    {
      "type": "external",
      "href": "https://platform.openai.com/docs/models/gpt-3-5-turbo"
    },
    {
      "type": "external",
      "href": "https://github.com/ShawhinT/YouTube-Blog/tree/main/LLMs/text-embeddings"
    },
    {
      "type": "external",
      "href": "https://platform.openai.com/docs/guides/embeddings"
    },
    {
      "type": "external",
      "href": "https://scikit-learn.org/stable/modules/model_evaluation.html"
    },
    {
      "type": "external",
      "href": "https://www.sbert.net/"
    },
    {
      "type": "external",
      "href": "https://github.com/ShawhinT/YouTube-Blog/blob/main/LLMs/text-embeddings/2-semantic-search.ipynb"
    },
    {
      "type": "external",
      "href": "https://shawhin.medium.com/list/8e009ae3054c"
    },
    {
      "type": "external",
      "href": "https://shawhintalebi.com/"
    },
    {
      "type": "external",
      "href": "https://calendly.com/shawhintalebi"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:49Z",
  "source_url": "https://towardsdatascience.com/text-embeddings-classification-and-semantic-search-8291746220be/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}