Loading…
DS · Text mining · Program 33 · Bonus
Document similarity using cosine similarity.
1from sklearn.feature_extraction.text import TfidfVectorizer2from sklearn.metrics.pairwise import cosine_similarity3 4docs = ["The cat sat on the mat",5 "The dog sat on the log",6 "The cat and the dog are popular pets",7 "Machine learning finds patterns in data",8 "Deep learning is a part of machine learning",9 "Data science uses machine learning and statistics"]10 11sim = cosine_similarity(TfidfVectorizer().fit_transform(docs))12print("Cosine Similarity Matrix:\n", sim.round(3))13print(f"\nSimilarity (Doc 0 & Doc 1): {sim[0][1]:.4f}")14print(f"Similarity (Doc 0 & Doc 3): {sim[0][3]:.4f}")Cosine Similarity Matrix: [[1. 0.661 0.443 0. 0. 0. ] [0.661 1. 0.443 0. 0. 0. ] [0.443 0.443 1. 0. 0. 0.111] [0. 0. 0. 1. 0.264 0.329] [0. 0. 0. 0.264 1. 0.247] [0. 0. 0.111 0.329 0.247 1. ]] Similarity (Doc 0 & Doc 1): 0.6611 Similarity (Doc 0 & Doc 3): 0.0000
Run program 33 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.