Loading…
DS · Text mining · Program 32 · Bonus
Information retrieval using TF-IDF.
1from sklearn.feature_extraction.text import TfidfVectorizer2from sklearn.metrics.pairwise import cosine_similarity3 4docs = [5 "Python is a popular programming language for data science and machine learning",6 "Machine learning algorithms learn patterns from data to make predictions",7 "Deep learning uses neural networks with many layers",8 "Pandas and NumPy are Python libraries for data analysis",9 "Football is the most popular sport in the world",10 "The World Cup is a famous football tournament held every four years",11 "Healthy food and regular exercise keep the body fit",12 "Neural networks are inspired by the human brain"]13 14vectorizer = TfidfVectorizer(stop_words='english')15tfidf = vectorizer.fit_transform(docs)16print("Vocabulary:", vectorizer.get_feature_names_out())17 18query = "python data analysis"19scores = cosine_similarity(vectorizer.transform([query]), tfidf)[0]20print(f"\nTop results for '{query}':")21for i in scores.argsort()[::-1][:3]:22 print(f"D{i} (Score: {scores[i]:.4f}): {docs[i]}")Vocabulary: ['algorithms' 'analysis' 'body' 'brain' 'cup' 'data' 'deep' 'exercise' 'famous' 'fit' 'food' 'football' 'healthy' 'held' 'human' 'inspired' 'language' 'layers' 'learn' 'learning' 'libraries' 'machine' 'make' 'networks' 'neural' 'numpy' 'pandas' 'patterns' 'popular' 'predictions' 'programming' 'python' 'regular' 'science' 'sport' 'tournament' 'uses' 'world' 'years'] Top results for 'python data analysis': D3 (Score: 0.6526): Pandas and NumPy are Python libraries for data analysis D0 (Score: 0.3311): Python is a popular programming language for data science and machine learning D1 (Score: 0.1350): Machine learning algorithms learn patterns from data to make predictions
Run program 32 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.