14

Short answer: Cosine distance is not the overall best performing distance metric out there Although similarity measures are often expressed using a distance metric, it is in fact a more flexible measure as it is not required to be symmetric or fulfill the triangle inequality. Nevertheless, it is very common to use a proper distance metric like the Euclidian ...


14

Based on the documentation cosine_similarity(X, Y=None, dense_output=True) returns an array with shape (n_samples_X, n_samples_Y). Your mistake is that you are passing [vec1, vec2] as the first input to the method. Also your vectors should be numpy arrays: from sklearn.metrics.pairwise import cosine_similarity import numpy as np vec1 = np.array([[1,1,0,1,1]]...


10

The cosine distance formula is: And the formula used by the cosine function of the spatial class of scipy is: So, the actual cosine similarity metric is: -0.9998. So, it signifies complete dissimilarity.


9

You're asking two questions here. Does this mean the magnitude of the vectors is irrelevant? Yes. Cosine distance is $ D_{cos} = \frac{A \cdot B}{\|A\|\|B\|} $, which just comes from the definition of inner product, $A \cdot B = \|A\|\|B\|\cos\theta$. Why is the cosine distance used? Or, to think of it another way, why is the answer to (1) a desirable ...


8

There's a related example to your problem in the Spark repo here. The strategy is to represent the documents as a RowMatrix and then use its columnSimilarities() method. That will get you a matrix of all the cosine similarities. Extract the row which corresponds to your query document and sort. That will give the indices of the most-similar documents. ...


6

Your input matrices (with 3 rows and multiple columns) are saying that there are 3 samples, with multiple attributes. So the output you will get will be a 3x3 matrix, where each value is the similarity to one other sample (there are 3 x 3 = 9 such combinations) If you were to print out the pairwise similarities in sparse format, then it might look closer to ...


5

Let us try and understand how Word2Vector actually works before looking at distances: There are 2 ways of generating vectors for a word : Continuous bag of words Skip grams The following diagram explains the difference between the two approaches. In case you want to further understand the nitty gritty of these two approaches, there are tons of blogs out ...


5

As mentioned in other answers, traditionally cosine is used to measure similarity between vectors whereas Levenshtein is used as a string similarity measure, i.e. measuring the distance between sequences of characters. Nevertheless they both can be used in non-traditional settings and are indeed comparable: the vectors compared with cosine can for instance ...


4

Disclaimer: This is actually a tentative explanation, it provides a possible answer, but it does not contain proof. First of all, contrary to added comments, cosine similarity is not always in the range $[0,1]$. This range is valid if the vectors contain positive values, but if negative values are allowed, negative cosine similarity is possible. Take for ...


3

Since the time-series are annual, the data points you have for each time-series are limited and also quite distant (the values are 1 year apart). So I wouldn't use Dynamic Time Wrapping on your data. If you are interested in comparing the patterns, a very simple approach would be Pearson's correlation. Keep in mind that this will not compare the actual ...


3

Similarity measures are subjective and so are they ways to combine them. You should decide what is your subjective definition of similarity and then find a way to combine them that fit your definition. In general, I like to reduce similarity problems into classification problems. Given the dataset of items you have, create a new dataset of item pairs. The ...


2

As you ask specifically for the Cosine Similarity technique, it has magnitude and direction, and similar to a vector which is used in Physics, as Cosine Similarity deals with vectors in an inner product space. So, the magnitude of vectors is exactly the same as the formula in Physics (summating over the squares of the vector elements.)


2

"Source credibility" of Internet articles is best calculated through the Page Rank algorithm. Algorithmically determining writing quality might be intractable. However Page Rank could be a proxy. If an article is a hub then it is the authority on the topic and can be assumed well written (or at least very useful).


2

If you have trained a gensim model, that object can act as a dictionary to give you the vector projection (via https://radimrehurek.com/gensim/models/word2vec.html) $ model['computer'] # raw numpy vector of a word array([-0.00449447, -0.00310097, 0.02421786, ...], dtype=float32) So it is possible to manually implement any vector comparison that you ...


2

My question is, do I need to normalize each product's vector before using columnSimilarities()? No, you do not need to normalize each product's vector before using columnSimilarities() since it is performed within the operation already. I think your confusion comes from the fact that your considering dot product and cosine similarity to be the same. They ...


2

This is talking about RAM. There are a few factors that will decide how many rows/columns you can use. Instead of rows/columns, it is maybe easier to just think in total number of elements: num_rows * num_cols. The memory you will require is going to have a relationship to this number. There are ways that might take less working memory to solve the problem -...


2

If I understand correctly, you're trying to map abstracts to their research papers. Here is a simple starting point: Compute a TF IDF model using the entire corpus (all abstracts + research papers). Use this model to transform your abstracts and research papers into a weighted vector representation. Under the TF IDF weighting scheme, these documents will ...


2

There are libraries that are specialized in exactly that task, for instance FAISS by Facebook AI Research: Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and ...


2

Word2vec as the name suggests will create an embedding for each word in your sentence. In order to get a sentence level embedding you would need to average (or combine in some other way) the individual embeddings together. An example of a model to generate sentence level embedding would be the Universal Sentence Encoder (USE). You may want to try it out and ...


2

Intuitively, if you normalized the vectors before using them, or if they all ended up having almost unit norm after training, then a small $l_1$ norm will imply that the angle between the vectors is small, hence the cosine similarity will be high. Conversely, almost colinear vectors will have almost equal coordinates because they all have unit length. So if ...


1

Yes, Cosine TF-IDF is quite transparent so it's usually reasonably easy to visualize the words which contribute the most to a score. Cosine is defined as the dot product divided by the product of the norms, so you can isolate the terms: dotproduct(d_1,d_2) = tfidf(w1,d1) * tfidf(w1,d2) + tfidf(w2,d1) * tfidf(w2,d2) + ... + tfidf(wN,dN) Ranking the words ...


1

According to sklearn's documentation: If linkage is “ward”, only “euclidean” is accepted. If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method. So you need to change the linkage to one of complete, average or single. If you try this it works: import numpy as np from sklearn.cluster import ...


1

I think it's rarely meaningful to consider cosine similarity on sparse data like this, not just because of sparsity (because it's only defined for dense data), but because it's not obvious the cosine similarity is meaningful. For example a user that rates 10 movies all 5s has perfect similarity with a user that rates those 10 all as 1. Magnitude doesn't ...


1

If you are using Python try the fuzzywuzzy package: FuzzyWuzzy Fuzzy string matching like a boss. It uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package. (Source)


1

You can try some approximate string matching which gives a confidence score. For example, you can try out with Levenshtein distance, but adjusted with the length of the strings using a probabilistic model; or, you can try out with Jaccard similarity on 3-grams and special treatment on word boundaries, and then calibrated into probabilities. Now you have an n ...


1

Jaccard - measures similarity of assymetric, binary attributes. For example, if you have insurance claims with binary attributes ("poor driving record", "premium paid in cash") you can compare claims with those attributes. Cosine - measures similarity between vectors, like feature vectors. Could be used in a recommender system where a user asks to see items ...


1

You can use total sum of boolean values. That will be fast and give a general notion of similarity. A more useful metric might be Hamming distance, the sum of matching booleans between two vectors.


1

For this kind of situation, spectral clustering is an intuitive solution. Basically, the idea is to perform the k-means clustering in a transformed feature space, by defining what the inner product should be in that space. The main point is to give yourself a similarity measure. In your case, this could be: $$S(v_1, v_2) = exp(-\frac{(x_0^{(1)}-x_0^{(2)})^...


1

Although cosine similarity is not a proper distance metric as it fails the triangle inequality, it can be useful in KNN. However, be wary that the cosine similarity is greatest when the angle is the same: cos(0º) = 1, cos(90º) = 0. Therefore, you may want to use sine or choose the neighbours with the greatest cosine similarity as the closest.


1

as Lejafar mentioned cosine violates triangle inequality however maybe this repo will help you


Only top voted, non community-wiki answers of a minimum length are eligible