I'm focused on developing a Python function for TF-IDF keyword extraction. Currently, I'm defining the goal: to create a Python function for TF-IDF keyword extraction from text. Next, I am breaking down the core concepts involved, specifically TF and IDF.
Considering Algorithm Choices
I'm now weighing the implementation choices: building the TF-IDF function from scratch versus leveraging Scikit-Learn. I'm leaning toward Scikit-Learn's TfidfVectorizer for its efficiency and built-in features, and I'm figuring out how to handle single-document inputs by treating parts of it as documents for IDF calculation.
Refining Function Structure
I'm solidifying the function's structure. I've decided to use a function that requires a document and an optional corpus. If no corpus is provided, the function will either alert the user of the limitations or split the document into segments for IDF calculation. My implementation will leverage the Scikit-Learn's TfidfVectorizer to handle the calculations efficiently. I'm focusing on the input parameters and the error-handling now.
Structuring the Approaches
I'm now outlining both the Scikit-Learn and "from scratch" approaches. I'll include the former for practical use and the latter for educational clarity. I'll start with the Scikit-Learn implementation, incorporating a dummy corpus for immediate use. Next, I will design a "from scratch" version to clarify the inner workings.
Evaluating Preprocessing Steps
I'm now determining the necessary preprocessing steps for text input. I need to consider lowercasing, stop word removal, and tokenization as part of the Scikit-Learn approach. For the 'from scratch' version, I'll need a simple tokenizer and cleaning function. I'm focusing on crafting modular functions for these steps.
Focusing on Corpus Interaction
I'm now honing in on how the function will handle corpora. I've realized TF-IDF's effectiveness hinges on comparing a document against a relevant dataset. Consequently, I must structure the Scikit-Learn example to utilize a small "corpus," making it clear how the comparison enhances keyword identification. This should provide better context for the user and help explain why corpus is needed.
Here are two ways to implement keyword extraction using TF-IDF in Python.
Approach 1: Using Scikit-Learn (Recommended)
This is the most efficient and production-ready method. It handles tokenization, stop-word removal (removing words like "the", "is", "and"), and math optimization automatically.
Note: TF-IDF works by comparing a specific document against a "corpus" (a collection of other documents) to find words that are unique to the specific document.
python
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
def extract_keywords_tfidf(document, corpus, top_n=5):
"""
Extracts top keywords from a document using a corpus for context.
Args:
document (str): The specific text to analyze.
corpus (list): A list of text strings to serve as comparison context.
top_n (int): Number of keywords to return.
Returns:
list: Tuples of (keyword, score).
"""
# 1. Combine the document with the corpus to fit the vectorizer
# (We ensure our document is part of the data being analyzed)
data = [document] + corpus
# 2. Initialize TF-IDF Vectorizer
# stop_words='english' removes common words like 'the', 'and', 'is'
vectorizer = TfidfVectorizer(stop_words='english')
# 3. Fit and Transform the data
tfidf_matrix = vectorizer.fit_transform(data)
# 4. Get feature names (the words)
feature_names = vectorizer.get_feature_names_out()
# 5. Get the scores for the first document (our target document)
# tfidf_matrix[0] corresponds to the 'document' argument
first_document_vector = tfidf_matrix[0]
# 6. Convert to a readable format (pandas dataframe is easiest for sorting)
df = pd.DataFrame(first_document_vector.T.todense(),
index=feature_names,
columns=["tfidf_score"])
# 7. Sort by score descending and take top N
sorted_keywords = df.sort_values(by=["tfidf_score"], ascending=False)
# Return as a list of tuples (word, score)
return list(zip(sorted_keywords.index[:top_n], sorted_keywords["tfidf_score"][:top_n]))
# --- Example Usage ---
target_text = "Deep learning is a subset of machine learning based on neural networks."
# We need a corpus (context) so the algorithm knows that "is" and "a" are common,
# but "neural" and "networks" are rare.
context_corpus = [
"Machine learning provides systems the ability to learn automatically.",
"Python is a popular programming language for data science.",
"Neural networks are computing systems inspired by biological neural networks.",
]
keywords = extract_keywords_tfidf(target_text, context_corpus)
print(f"Analyzing text: '{target_text}'\n")
print("Top Keywords:")
for word, score in keywords:
print(f"{word}: {score:.4f}")
Approach 2: From Scratch (No external libraries)
This removes dependencies like sklearn and pandas. It is useful for understanding the mathematics behind the algorithm.
python
import math
from collections import Counter
import re
def clean_tokenize(text):
# Remove punctuation and split into words
text = re.sub(r'[^\w\s]', '', text).lower()
return text.split()
def compute_tf(text_tokens):
# Term Frequency: Times word appears in doc / Total words in doc
word_counts = Counter(text_tokens)
total_words = len(text_tokens)
return {word: count / total_words for word, count in word_counts.items()}
def compute_idf(corpus_tokens):
# Inverse Document Frequency: log(Total docs / Docs containing word)
total_docs = len(corpus_tokens)
idf = {}
# Get all unique words across all documents
all_words = set([word for doc in corpus_tokens for word in doc])
for word in all_words:
# Count how many docs contain this word
count = sum(1 for doc in corpus_tokens if word in doc)
idf[word] = math.log(total_docs / (count + 1)) # +1 avoids division by zero
return idf
def extract_keywords_manual(target_text, corpus_list, top_n=5):
# 1. Tokenize everything
target_tokens = clean_tokenize(target_text)
corpus_tokens = [clean_tokenize(doc) for doc in corpus_list]
# Add target to corpus for IDF calculation context
corpus_tokens.append(target_tokens)
# 2. Compute TF and IDF
tf_scores = compute_tf(target_tokens)
idf_scores = compute_idf(corpus_tokens)
# 3. Compute TF-IDF (TF * IDF)
tfidf_scores = {}
for word in tf_scores:
tfidf_scores[word] = tf_scores[word] * idf_scores.get(word, 0)
# 4. Sort and return
sorted_words = sorted(tfidf_scores.items(), key=lambda item: item[1], reverse=True)
return sorted_words[:top_n]
# --- Example Usage ---
my_text = "The cat sat on the mat and played with the cat toy."
my_corpus = [
"The dog ate the food.",
"The cat and the dog are friends."
]
keywords = extract_keywords_manual(my_text, my_corpus)
print("Top Keywords (Manual):")
for word, score in keywords:
print(f"{word}: {score:.4f}")
Key takeaway on TF-IDF logic:
TF (Term Frequency): Measures how often a word appears in your specific document. (Rewards frequent words).
IDF (Inverse Document Frequency): Measures how rare a word is across all documents. (Penalizes common words like "the", "is", "it").
Result: The highest scores go to words that appear frequently in your text but rarely in others.