Lesson 09 · 40 minutes
Turn text into vectors and search by meaning
- Turn short texts into vectors with TfidfVectorizer and TruncatedSVD
- Find the nearest text to a query with cosine similarity
- Explain how learned embeddings differ and why search and RAG use them
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your help desk keeps a folder of short security notes. Staff search it, but they find nothing when they use other words than the note does. A vendor offers "AI search that understands meaning" and your manager asks whether it is worth the money. You will build a small search from scratch, see where it works and where it fails, and then test it on ten new notes and three queries.
Recall
In lesson 2, what are the features of one example, and where do they go?
The features are the numbers that describe the example, such as the 64 pixel values of a digit. They form one row of the table X.
In lesson 8, what did a layer of a neural network do with its input?
It multiplied each input by a weight, added the results, and passed them through a simple bend. A learned embedding comes from the layers of such a network.
The idea
A model works on numbers, but security data is text: phishing mails, log lines, prompts, documents. An embedding (or vector) is a list of numbers that stands for a piece of text. Texts with similar content should get vectors that point in similar directions. Then "similar meaning" becomes a calculation.
- Text → Word weights: TfidfVectorizer scores each word
- Word weights → Dense vector: TruncatedSVD makes it short
- Dense vector → Similarity: cosine against every text
- Similarity → Nearest texts: sort, highest score first
Cosine similarity compares the direction of two vectors. For word-weight vectors the score runs from 0 to 1: it is 1 when the vectors point the same way and 0 when the texts share no word. For the compressed vectors it can also be below 0, which means that the texts point away from each other. The length of the text does not matter.
Two classic tools build vectors without a neural network:
TfidfVectorizergives each text one number for each word of the vocabulary. A word that is frequent in a text and rare in all the others scores high. The result has one column for each word.TruncatedSVDcompresses these long vectors to a few columns. It finds groups of words that appear together and describes each text by how much of each group it holds.
The honest limit: these vectors know only which words appear in your data.
Worked example
1. Make the tf-idf vectors
Go to the lab folder and activate the environment. Create embed.py with twelve short texts: eight about security, three about other things and one about a model. TfidfVectorizer(stop_words="english") skips common words such as "the" and "a", which carry no topic. fit_transform(texts) learns the vocabulary from the texts and returns the table of vectors, one row for each text. get_feature_names_out() lists the words, in alphabetical order.
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
texts = [
"reset your password from the account settings page",
"the attacker stole the password hashes from the database",
"stolen credentials were used to log in to the vpn",
"a firewall blocks traffic that does not match a rule",
"the firewall rule allows only port 443 from the internet",
"patch the web server to fix the known vulnerability",
"the vulnerability lets an attacker run code on the server",
"backup the database every night and test the restore",
"the cat sat on the warm windowsill all afternoon",
"bake the bread for forty minutes until it is golden",
"the football team won the match with a late goal",
"we trained a model to classify network traffic",
]
tfidf = TfidfVectorizer(stop_words="english")
A = tfidf.fit_transform(texts)
print("tf-idf matrix:", A.shape, "(texts x words)")
print("some words:", list(tfidf.get_feature_names_out()[:6]))cd ~/krlab/how-ai-works
source .venv/bin/activate
python embed.pytf-idf matrix: (12, 55) (texts x words)
some words: ['443', 'account', 'afternoon', 'allows', 'attacker', 'backup']2. Compress them to dense vectors
TruncatedSVD(n_components=8) keeps eight columns. Eight are enough for twelve short texts. Its random_state fixes a random start, so the result repeats. Add these lines and run the file again. The two new lines are the last two of the output. V[0, :4] is the first four numbers of the first text's vector. You do not need to read them: the point is that each text is now eight numbers.
svd = TruncatedSVD(n_components=8, random_state=0)
V = svd.fit_transform(A)
print("dense vectors:", V.shape)
print("first text:", V[0, :4].round(2))dense vectors: (12, 8)
first text: [0. 0.28 0.48 0.71]3. Search by similarity
The function turns a query into a vector in the same way, compares it with every text and prints the two nearest. def nearest(query, k=2) defines a function with a default for k. cosine_similarity(q, V) gives the score against every text. np.argsort(-sims) gives the positions of the texts from the highest score to the lowest. Add these lines, run the file, and read the last lines of the output.
def nearest(query, k=2):
q = svd.transform(tfidf.transform([query]))
sims = cosine_similarity(q, V)[0]
print(query)
for i in np.argsort(-sims)[:k]:
print(f" {sims[i]:.2f} {texts[i]}")
nearest("firewall port rule")
nearest("someone stole a login password")
nearest("how do I make bread")firewall port rule
0.99 the firewall rule allows only port 443 from the internet
0.90 a firewall blocks traffic that does not match a rule
someone stole a login password
0.94 the attacker stole the password hashes from the database
0.83 reset your password from the account settings page
how do I make bread
1.00 bake the bread for forty minutes until it is golden
0.13 the firewall rule allows only port 443 from the internetThe three queries work: the nearest texts are on the same topic. The second query is only partly right. "stole" matches the text with "stole", and the text with "stolen credentials" is not in the top two, because "stole" and "stolen" are different words to tf-idf.
4. Try a query that shares no word
The last query means "fix a vulnerability" but uses other words. Here the program compares the query with the tf-idf table A directly. .max() gives the best score. Add it and run the program.
q = tfidf.transform(["fixing a security hole"])
print("best score for 'fixing a security hole':", cosine_similarity(q, A).max())best score for 'fixing a security hole': 0.0The score is 0.0, because "fixing", "security" and "hole" do not appear in any text. A person sees at once that "patch the web server to fix the known vulnerability" is the answer. This method cannot.
5. Compare with learned embeddings
A learned embedding comes from a neural network (lesson 8) trained on huge amounts of text to place related texts close together. Such a model has seen "patch", "fix" and "update" in the same contexts, so their vectors are close, although they share no letters. Each vector has several hundred to a few thousand numbers. This course does not need one; later courses use them.
Retrieval-augmented generation (RAG) uses exactly the loop of step 3: embed the documents once, embed each question, take the nearest chunks and put them into the prompt of a language model. The language model never searches. The embedding does.
- Attacker → Documents: writes a note near common questions
- Documents → Vector index: each chunk is embedded once
- User → Embedding model: asks a question
- Embedding model → Vector index: nearest chunks by cosine score
- Vector index → Language model: the chunks go into the prompt
- Language model → User: answers from those chunks
6. The finished file
This is the whole file embed.py as it stands after the steps above. The lab files of the course hold it.
The finished file: embed.py
embed.py
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
texts = [
"reset your password from the account settings page",
"the attacker stole the password hashes from the database",
"stolen credentials were used to log in to the vpn",
"a firewall blocks traffic that does not match a rule",
"the firewall rule allows only port 443 from the internet",
"patch the web server to fix the known vulnerability",
"the vulnerability lets an attacker run code on the server",
"backup the database every night and test the restore",
"the cat sat on the warm windowsill all afternoon",
"bake the bread for forty minutes until it is golden",
"the football team won the match with a late goal",
"we trained a model to classify network traffic",
]
tfidf = TfidfVectorizer(stop_words="english")
A = tfidf.fit_transform(texts)
print("tf-idf matrix:", A.shape, "(texts x words)")
print("some words:", list(tfidf.get_feature_names_out()[:6]))
svd = TruncatedSVD(n_components=8, random_state=0)
V = svd.fit_transform(A)
print("dense vectors:", V.shape)
print("first text:", V[0, :4].round(2))
def nearest(query, k=2):
q = svd.transform(tfidf.transform([query]))
sims = cosine_similarity(q, V)[0]
print(query)
for i in np.argsort(-sims)[:k]:
print(f" {sims[i]:.2f} {texts[i]}")
nearest("firewall port rule")
nearest("someone stole a login password")
nearest("how do I make bread")
q = tfidf.transform(["fixing a security hole"])
print("best score for 'fixing a security hole':", cosine_similarity(q, A).max())Your turn
Build the search again on ten new notes. There is no code here: adapt embed.py. Number the texts from 0 in the order of the table.
| Number | Text |
|---|---|
| 0 | failed login attempts came from one address |
| 1 | the user entered a wrong password five times |
| 2 | the account was locked after many failed logins |
| 3 | the scanner found an open port on the server |
| 4 | close every port that the service does not need |
| 5 | the disk is almost full on the log server |
| 6 | rotate the logs and delete the old archives |
| 7 | the email asked the user to verify a password |
| 8 | a link in the email led to a fake login page |
| 9 | report the phishing email to the security team |
Use TfidfVectorizer(stop_words="english") and TruncatedSVD(n_components=6, random_state=0). Search with the dense vectors, and show the three nearest texts for each of these queries: fake email link, too many wrong passwords and someone tried to break in. For the last query, also compare it with the tf-idf table. Expect 0.00 for every text with this query: no query word is in any text, which is the point of the query.
Last, say which text a person would choose as the second answer to "too many wrong passwords", and explain in one sentence why the search chose text 7.
Check yourself
What does a cosine similarity of 0.0 tell you?
For word-weight vectors, the two texts have no word in common (after stop words are removed). For compressed vectors, 0 means that the vectors are at right angles. It does not mean that the texts are opposite in meaning.
Why does "fixing a security hole" score 0.0 against a text about a vulnerability patch?
TF-IDF counts words. No word of the query appears in any text, so nothing matches. A learned embedding can still place them close.
Why does "stole" fail to match "stolen"?
The vectoriser treats each different spelling as a different word. It has no idea of word forms. Learned embeddings, and a step called stemming, handle this better.
In a RAG system, an attacker can write a document into the knowledge base. Why is that a risk?
The embedding picks the nearest chunks by similarity, and the text of a chunk goes into the prompt. A document written to be near common questions will be retrieved and read by the language model, so it can carry false facts or instructions. Later courses cover this.
Field notes
- Retrieval systems must apply access control at retrieval time. If chunks of a private document are in the same index, a nearest-neighbour search can return them to a user who may not read the document. Filter by the identity of the user before the text reaches the prompt.
- Embeddings are not anonymous. Research has shown that text can sometimes be partly reconstructed from its embedding. Protect a vector store as you protect the documents.
- Fit the vectoriser on the training texts only, and keep it with the model. If you refit it on new data, the columns change and old vectors no longer fit.
- Use the same embedding model for the documents and for the queries, and record its name and version. Vectors from two different models cannot be compared.