{"slug": "why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be", "title": "Why Vector Search is Mathematically Right and Still Give the Answer Which Can be Least Expected", "summary": "A hands-on vector search experiment using NumPy and Matplotlib, with no embedding models, found that the highest cosine similarity score of 0.8660 returned an off-target answer to the question \"How can electricity from sunshine keep lamps running after dark?\" — the sentence \"Grid electricity can power streetlights during the night.\" The author built a hard-coded corpus of 15 short sentences about a solar-powered lighting project and mapped 8 concepts to numeric vectors to show why mathematically correct similarity ranking can still surface the least expected result, with code published on GitHub. The work argues that answering the question properly requires 3 concepts that the top-scoring sentence does not cover.", "body_md": "In Artificial Intelligence, we focus on language models, transformers, attention mechanisms etc. While exploring these advanced concepts, we should understand an important question - **How can a computer identify the relationship between pieces of information, though semantically these are completely different words?**\n\nVector Search gives us an starting point. It tries to connect reasoning with some of the important mathematical foundations of modern AI — vectors, embeddings, linear algebra, dot products, cosine similarity, and distance measurement. By representing the numbers as information and making mathematical operations on them, we try to identify relationships between them and thus we understand the principles behind semantic search, recommendation systems, information retrieval and other parts of AI. Eventually we understand that **AI compares and learns numerical representations for everyday data in which relationships between words or phrases can be calculated.**\n\nIn our experiment, the question about solar energy — **How can electricity from sunshine keep lamps running after dark?**, the first result that will come — **Grid electricity can power streetlights during the night.**\n\nHere we wanted to understand about solar energy specific things. But from the answer, we were not able to find this context in first answer(i.e. most appropriate answer to the question), though some more relevant information is there within our corpus. Here the sentence was not false and the similarity score is the highest in the repository - **0.8660** (All of the details are in the below writings, which we try to understand one-by-one).\n\nDuring my writing, I have used AI Tools to generate the sample data tables. Rest of the pictures/plots are generated through the python program and **matplotlib** library -which can be found in [Github](https://github.com/piyasde/article_companion/blob/main/vector_search.py).\n\nSo in our work, Most appropriate answer for the above question will need **3** concepts —\n\nAnd the above explanation is there in a sentence in the corpus. The corpus is hard-coded for our experiment in the code, shown in the first picture below.\n\nSo now we will try to understand the path of the vector search work and all the context optimization concepts further. This particular thing can give us the idea and explanation in the mathematically correct search and useful search.\n\nWe tried to make the process from scratch. The python numerical library we have used is **NumPy**. **Matplotlib** is used for the graphs. We had not used embedding models here, rather tried to organized the data with numeric identification intentionally to understand all the steps that are happening under the hood. In a large scale applications - all of those steps with mathematical optimizations are applied in Production Systems.\n\nFor our work, we have collected a set of 15 sentences related to solar-powered lighting project. These are just short notes in the work -\n\nThe corpus contains related information about solar projects. Some of the statements are for electricity concepts, some are for storage and some are for night time lighting. We will check those sentences with vector representation and their similarity impact, while we progress further in the work.\n\nA general keyword search always look for matching words or terms like database search with like search and famous **%** before and after word or phrase. With semantic search we try to get most similar concepts / word combination for the related question. And we try to map all these words in vector with suitable representation. For example, **photovoltaic** and **sunshine** in the above corpus relate to solar energy. **After sunset** and **after dark** both refer to night time. We make way to map those relations in vectors and thus measurable with mathematics.\n\nFor our conceptual work on the Vector Search, we elaborated 8 concepts with their logical same type of meaning. Some of the data examples are below. Full concept mapping will be in [near the top of the code](https://github.com/piyasde/article_companion/blob/main/vector_search.py).\n\nHere we will encode the sentences as numbers in a vector space. A **1** means a concept is there with the combination lookup in the above set; a **0** means that it is not there in our corpus. So the no 1 statement — which is for photovoltaic panels, sunlight and electricity — will become -\n\n**S01 = [1, 1, 0, 0, 0, 0, 0, 0]**\n\nRelated sentence is — ‘**Photovoltaic panels convert sunlight into electricity during the day.**’. If we go through the code, we will find **D1** and **D2** Dimensions are having matching words from the sentence. So first 2 dimensions are having the number as 1 and rest of the dimensions are not having any matching words and thus they are 0.\n\nThe statement for battery supplying electricity to lamps after sunset will become -\n\n**S03 = [0, 1, 1, 1, 1, 0, 0, 0]**\n\nAnd the query will become -\n\n**Q = [1, 1, 0, 1, 1, 0, 0, 0]**\n\nThe above 2 are applying same logic as **S01** for dimensions**. The** code snippet is worth of noting -\n\n```\n# Encode text for binary concept presence. Word boundaries are given.PATTERNS = [re.compile(r'\\b(?:' + '|'.join(re.escape(w) for w in words) + r')\\b', re.I)            for words in CONCEPTS.values()]def embed(text):    return np.array([float(bool(p.search(text))) for p in PATTERNS])\n```\n\nIn the regex pattern matching section, we are trying to find the matching word which are in dimensions and within **embed** function, we are setting boolean 1 and 0 value to each of the cells of dimensions.\n\nHere the missing part is **storage** dimension in the question. The query has to know how the process works, but the answer has not is with the intermediate mechanism. The missing part will significantly affect the work performance. All 15 sentence embeddings form one matrix, with a row for each sentence and a column for each concept with a shape of **(15, 8) — 15 rows for sentences and 8 words for columns.**\n\nA heatmap of the corpus — columns are concepts and rows are sentences. Dark or light cells represent concept presence or absence.\n\nWe need to remember — **this is an experimental encoder for the current work, and not a production semantic model.**\n\nA production embedding model is trained on many data and it learns numeric representations from multiple cycles of training. Its individual dimensions do not correspond to concepts like **solar** or **maintenance**. Those vectors contain continuous values which comes with raw data and related learned weight multiplication and other mathematical concepts such as activation functions and other relevant works of mathematical and statistical ideas. Once those are done, the subsequent similarity mathematics works in the same way as we have shown here.\n\nAs a first step we have all sentence vectors to have eight dimensions with feature representing by **1** or **0**, which can be compared with the question vector numerically. Here the first work is the **dot product**. For two vectors **A** and **B**, we multiply matching coordinates and add the products and so we find — **A · B = A1×B1 + A2×B2 + … + A8×B8**\n\nOur question and above S03 sentence share **electricity**, **lighting** and **night time**. Their dot product is **3**. To compare directions of the vectors, we divide by the the vector’s lengths. This gives us an important equation - **cosine similarity.**\n\n**cosine(A, B) = (A · B) / (||A|| × ||B||)**\n\nThe length, or L2 norm, is **||A|| = sqrt(A¹² + A²² + … + A⁸²).**\n\nHere Q(Question) and S03(Answer sentence) have 4 active or matching dimensions, so length is **sqrt(4) = 2**.\n\nSo **cosine(Q, S03) = 3 / (2 × 2) = 0.7500**\n\nBy Cosine similarity, we can identify — how closely two vectors point in the same direction. For non-zero vectors, its range is **−1 to +1**. In our example we have used binary dimension value **0** and **1** - so scores can not be negative. In production system, learned embeddings through multiple training cycle, can produce negative cosine similarities also.\n\nAt **0°**, cosine is 1. At **90°**, it is 0. The graph makes a geometric relationship visible — the real vectors live in hundreds of dimensions.\n\nAnother point is to remember — here normalization matters, as we need unit vectors.\n\nThe vectors **[1,1]**, **[2,2]** and **[10,10]** point in the same direction. Their dot products with **[1,1]** differ, but their cosine similarity with **[1,1]** is always 1.\n\nBy dividing the vector length, we normalize a vector and so it becomes a **unit vector**. The **dot product** of two unit vectors will be their cosine similarity.\n\nRelated code is -\n\n```\n# L2 normalization applied to stored sentencesdef unit(x):    x = np.asarray(x, dtype=float)    # Normalize here    length = np.linalg.norm(x, axis=-1, keepdims=True)    return np.divide(x, length, out=np.zeros_like(x), where=length != 0)# Exact retrieval - cosine is dot product of unit vectors.def search(index, q, k=5):    if np.linalg.norm(q) == 0:        raise ValueError('No known semantic concepts in query; cosine is undefined.')    scores = index @ unit(q)    order = np.argsort(-np.round(scores, 12), kind='stable')    return scores, order[:k]\n```\n\nIn the above code, the normalization and cosine similarity scoring is done. A little note about **L2 Normalization** — L2 Normalization converts a vector into a unit vector without changing any direction. Here we can compare compare vectors based on their direction rather than their magnitude. So when we look for directional relationship and similarity for 2 vectors, we make the l2 Normalization. After this step, the cosine similarity can be calculated using dot product between vectors, whit we had achieved in the above code snippet.\n\nOur code is in [Github](https://github.com/piyasde/article_companion/blob/main/vector_search.py). The full code file is **vector_search.py**, which includes the 15 sentences, the concept key-value dictionary, CSV export and seven plots.\n\nHere is the python code snippet in the main function, which uses the above functions -\n\n```\nD=np.stack([embed(s) for s in SENTENCES]); index=unit(D)q=embed(args.query)try: scores, order=search(index,q,len(IDS))except ValueError as e: parser.error(str(e))# Controlled query expansion - inject storage as a missing concept.q2=q.copy(); q2[list(CONCEPTS).index('Storage')]=1scores2, order2=search(index,q2,len(IDS))print('Dimensions:', ', '.join(CONCEPTS)); print('Query:',args.query)print('Query vector:',q.astype(int)); print('Matrix shape:',D.shape)for i in range(len(IDS)): print(IDS[i],D[i].astype(int),SENTENCES[i])print('\\nOriginal cosine ranking:')for i in order: print(f'{IDS[i]}  {scores[i]:.4f}  {SENTENCES[i]}')print('\\nExpanded query:',q2.astype(int))for i in order2[:5]: print(f'{IDS[i]}  {scores2[i]:.4f}  {SENTENCES[i]}')\n```\n\nNow the 8 dimensional mapping will be like -\n\n```\nS01 [1 1 0 0 0 0 0 0] Photovoltaic panels convert sunlight into electricity during the day.S02 [0 1 1 0 0 0 0 0] Rechargeable batteries store electrical energy for later use.S03 [0 1 1 1 1 0 0 0] Battery banks supply electricity to lamps after sunset.S04 [1 0 1 1 1 0 0 0] Solar-powered garden lights use stored energy at night.S05 [1 0 0 0 0 1 0 0] Solar thermal collectors use sunshine to heat water.S06 [0 1 0 0 0 1 0 0] Electric pumps move water into overhead tanks.S07 [0 1 0 1 0 0 0 0] LED bulbs consume less electricity than traditional bulbs.S08 [0 0 0 1 1 0 1 0] Outdoor lighting is switched off at midnight to reduce costs.S09 [0 0 1 0 0 0 0 1] Lithium batteries need periodic inspection and maintenance.S10 [0 0 0 0 0 0 1 0] A replacement inverter can increase installation costs.S11 [0 0 0 0 0 1 0 0] Rainwater harvesting reduces demand for municipal water.S12 [1 0 0 0 0 0 0 1] Solar panels need regular cleaning to maintain output.S13 [0 1 0 1 1 0 0 0] Grid electricity can power streetlights during the night.S14 [1 1 1 0 0 0 0 0] A charge controller regulates power flowing from solar panels to batteries.S15 [0 0 1 0 0 0 1 1] A maintenance contract covers battery replacement costs.\n```\n\nThe original cosine ranking is like -\n\n```\nOriginal cosine ranking:S13  0.8660  Grid electricity can power streetlights during the night.S03  0.7500  Battery banks supply electricity to lamps after sunset.S04  0.7500  Solar-powered garden lights use stored energy at night.S01  0.7071  Photovoltaic panels convert sunlight into electricity during the day.S07  0.7071  LED bulbs consume less electricity than traditional bulbs....\n```\n\nAfter Query expansion, the result will be -\n\n```\nExpanded query: [1 1 1 1 1 0 0 0]S03  0.8944  Battery banks supply electricity to lamps after sunset.S04  0.8944  Solar-powered garden lights use stored energy at night.S13  0.7746  Grid electricity can power streetlights during the night.S14  0.7746  A charge controller regulates power flowing from solar panels to batteries.S01  0.6325  Photovoltaic panels convert sunlight into electricity during the day.\n```\n\nThe result is a score for all the sentences. Here the program objective is retrieval using geometry.\n\nA bar chart is to see the ranking. The result with the largest score here is not the best piece of evidence.\n\nThe first 5 scores are -\n\nOur encoder has made all the calculation right. **We programmed a semantic representation which is weak to infer the answer with main concepts.** This is why - we should study the embedding quality irrespective of vector search performance or capability.\n\nWe have seen that energy storage is part of the question. This is a domain specific knowledge which is visible in the sentence repository. Now if we add the storage dimension to the query -\n\n**Q = [1, 1, 0, 1, 1, 0, 0, 0]** and **B = [0, 0, 1, 0, 0, 0, 0, 0]**\n\nSo **Q’ = Q + B = [1, 1, 1, 1, 1, 0, 0, 0]**\n\nIn the code, the work happens in the following line -\n\n```\nq2=q.copy(); q2[list(CONCEPTS).index('Storage')]=1\n```\n\nHere if we again compute the similarities, it becomes like -\n\nThe above image is about adding a concept which changes the query direction. It improves the ranking of battery-related information in our example.\n\nThe above works are part of **query expansion** and **vector addition**. In this particular work, the vector addition with relevant concept gives us better result. It depends on work nature — that we may need to add the vectors to improve the result, all the cases are different and we should go through the processes like the above case-by-case basis.Any wrong assumption can make the query in the wrong direction. For a production application, expansion are evaluated on the basis of a clearly testable set of questions.\n\nThere is another mathematical way to solve the case — by changing the weight of an important concept or give relevant weightages concept-by-concept. This is called **scalar multiplication**. By this workable way, we train the retrieval system with the aspects which matters more in giving answers. Each of the weight should be justified with the task in hand, and to be tested with multiple variations of questions i.e. not to have dependency for a small set of questions with improved results.\n\nIf we go through the sentences, we will mark S01, S02, S03 and S04 as the supporting facts and answer for the question.\n\nThe first result of top 5 contains 3 of these 4 sentences.\n\nSo **Precision@5 = relevant results retrieved / all results retrieved = 3 / 5 = 60%** and **Recall@5 = relevant results retrieved / all relevant results = 3 / 4 = 75%.** These are the basic metrics for the testing. By these metrics, we find different observations. With **Precision** metric we find - how much of the result list is useful. With **Recall** metric we find - how much of the useful information, we missed. These metrics do not measure whether a retrieval of answer is truthful or not — here we are not generating any rule based answer. Our training corpus are human judgments for the work. With this simple experiment we can find a pattern that is very relevant at production system — we should look at the answer relevance even before seeing the similarity score. So we should always test with a set of answers against a set of clearly defined questions, which will give us ways to make the answers more relevant.\n\nWe can inspect with **“Can sunlight heat water?**”. The model’s scoring and answers will clear the above facts about answers against the question. A **negation test** will help us in the findings. For the encoder - “**Use batteries for lamps**” and “** Do not use batteries for lamps**” will have the same similarity score for vectors as all the keywords appears in both the sentences. A trained semantic model in production system will handle such distinctions in better ways, though all those trained systems also require evaluation on negation, numbers, entities and domain-specific words.\n\nWe made hard-coded **8** coordinates to make an basic understanding for the experiment and so we wrote the dictionary.\n\nA pre-trained semantic model works in different ways. In machine learning training phase, the model in building works with many examples of related and unrelated sentences and phrases. The weightages and parameters are adjusted within the training of Feed Forward Network and backpropagation and other relevant calculations and useful relationships become measurable in the output vectors. The model may learn “**after sunset**” and “** at night**” are mostly related within current training corpus data i.e within the context, without having creating any hard-coded dictionary or combination of related words.\n\nThe production system work starts with token representations, it builds contextual representations with a neural encoder, and combines them into one sentence embedding with positional context also. At the search time, the same embedding space will be used for questions and documents and vast amount of the different query/document instructions are used to train the models for retrieval purpose.\n\nA **semantic encoder** is not a vector database.With the encoder we construct the representation of the data and the search mechanism compares such representations.\n\n**Query, Key and Value** calculations are used inside semantic model based on the architecture of the system to construct contextual embeddings. A vector search engine will not need transformer attention to compare the computed embeddings.\n\nHere the question embedding behaves like a query, stored embeddings are the comparison keys and the original texts are values for the retrieval of the answers. Actual QKV calculation and their contexts are different in **Attention** model. In an attention layer, the learned projections produce Q, K and V, and scaled dot-product values after which softmax creates a weighted representation.\n\nIn our search, we rank stored records using cosine similarity. Here the other formulas like **softmax** are not used.\n\nIn the [code](https://github.com/piyasde/article_companion/blob/main/vector_search.py), we included a softmax to show the differences for all of us by which we will be able to distinguish the similarity and the attention like part. Below is the code, which is having softmax function and attention like feature -\n\n``` python\ndef softmax(x):    e = np.exp(x - np.max(x))    return e/e.sum()def attention_demo(D, q):    K = D[:3]  # identity key projection; three selected sentences    V = np.eye(3)  # artificial one-hot values for the three facts    weights = softmax((K @ q)/np.sqrt(K.shape[1]))    return weights, weights @ V\n```\n\nOur code for the above work is in the [Github Repository](https://github.com/piyasde/article_companion/blob/main/vector_search.py). All the code segments are documented there. We should Install the **numpy** and **matplotlib** libraries -\n\n```\npython -m pip install numpy matplotlib\n```\n\nWe can run the work using following command -\n\n```\npython vector_search.py -- plots\n```\n\nWe made the the program to show the sentence vectors and rankings, we export result to a CSV, and the program creates plots for the matrix, similarity ranking, cosine curve, query-relative geometry, query expansion, attention like feature and the exact-search work which is kind of semantic search.\n\nWe can modify a synonym, add or delete one concept, change a weight or introducing a sentence containing the opposite meaning.\n\nFollowing is a useful call argument where we can change and check the results -\n\n```\npython vector_search.py --query 'Can sunlight heat water?'\n```\n\nFollowing 4 points we have learned with required results so far -\n\n1. **Embedding is a representation of data in numeric forms and structures -** It always preserve important relationship between words so that later works such as matrix manipulation and other statistical measures can meaningfully discover the information at later stage.\n\n2. **Cosine similarity is a geometric calculation which determines direction and magnitude of related data -** It measures vector alignment of the represented data which may or may not represent relevancy of the particular requirement in work.\n\n3. **Matrix multiplication makes search simple** - A query can be compared against an entire repository with simple numeric data representation in rows and columns without any specialized library of languages.\n\n4. **Relevance requires iterative evaluation -** A score is an input to a decision, it may be relevant or not. To make the relevancy, we need to evaluate training and testing data iteratively with continuous checking on the result of the work.\n\nWe can retrieve meaning-based records with the above concepts in mind. This is a Python program on a very small set of sentences to showcase the functionality for the vector search and how it works behind the scene.\n\nFor the production repositories which contain millions of records, several customers-products — their choice relationship etc, updated policy documents, many requests on these type of semantic queries, we generally use Vector Database in place, which is having functionalities like indexing, dynamic storing, filtering etc. We will discuss those soon in our next article, which will come within a few weeks.\n\nVector Search reveals how mathematical representations make it possible for computers to work with relationships between words and phrases. Our understanding on why two vectors are similar, how their directions and magnitudes affect calculations and why the mathematically close result may not be the most meaningful one- make us approachable to the advanced concepts of AI.\n\nEmbedding models learn useful representations, attention calculate relationships between token representations, vector databases organize these representations for semantic retrieval. These systems share important mathematical foundations.\n\n**Understanding Vector Search is like building the mathematical intuition needed to understand how AI systems represent, compare, and retrieve information.**\n\n[Sentence Transformers: Semantic Search](https://www.sbert.net/examples/sentence_transformer/applications/semantic-search/README.html)— practical background on sentence and query embeddings.[FAISS: Metric Types and Distances](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances) — cosine similarity using normalized vectors and inner products.[FAISS: Getting Started](https://github.com/facebookresearch/faiss/wiki/Getting-started) — an production entry point for the work.\n\n[Why Vector Search is Mathematically Right and Still Give the Answer Which Can be Least Expected](https://pub.towardsai.net/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be-least-expected-6de0687d3ab9) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.", "url": "https://wpnews.pro/news/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be", "canonical_source": "https://pub.towardsai.net/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be-least-expected-6de0687d3ab9?source=rss----98111c9905da---4", "published_at": "2026-11-24 14:31:02+00:00", "updated_at": "2026-11-24 14:44:59.352065+00:00", "lang": "en", "topics": ["ai-search", "natural-language-processing", "artificial-intelligence"], "entities": ["NumPy", "Matplotlib", "GitHub"], "also_reported_by": [], "takeaway": "A top cosine similarity score of 0.8660 returned an off-topic sentence for a solar-energy question, showing that raw vector similarity ranking alone can miss the concepts a query needs.", "recommendation": {"advice": "Inspect top-ranked vector search results against the concepts a query actually requires; the source's 0.8660 top match still missed the needed context, so add reranking or concept checks before trusting similarity scores.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be", "markdown": "https://wpnews.pro/news/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be.md", "text": "https://wpnews.pro/news/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be.txt", "jsonld": "https://wpnews.pro/news/why-vector-search-is-mathematically-right-and-still-give-the-answer-which-can-be.jsonld"}}