Creating a text summarizer using Machine Learning (ML) and Deep Learning (DL) involves training or using pre-trained models to generate concise summaries from longer documents. Below is an example of how you can build a text summarizer in Python using both ML (e.g., TF-IDF + SVM) and DL (e.g., Transformers like BERT or T5).
We'll use:
scikit-learn for the ML approach
transformers and torch for the DL approach
✅ 1. Install Required Libraries
pip install scikit-learn transformers torch nltk
Also, download NLTK data:
import nltk
nltk.download('punkt')
🧠 Option A: Text Summarizer Using ML (TF-IDF + SVM)
This is more of an extractive method using classical ML techniques.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk import sent_tokenize
def ml_summarize(text, summary_size=3):
sentences = sent_tokenize(text)
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(sentences)
# Compute sentence importance using sum of TF-IDF scores
sentence_scores = tfidf_matrix.sum(axis=1).flatten().tolist()[0]
ranked_sentences = [sentences[i] for i in sentence_scores.argsort()[::-1]]
return ' '.join(ranked_sentences[:summary_size])
# Example usage
text = """
Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence
concerned with the interactions between computers and human language. Much of NLP involves teaching computers
to gather information from unstructured text. Some of the earliest work in NLP dates back to the 1950s.
"""
print("ML Summary:\n", ml_summarize(text))
🤖 Option B: Text Summarizer Using Deep Learning (Transformer-based model - Hugging Face)
Using a pre-trained transformer model like t5-small or facebook/bart-large-cnn.
from transformers import pipeline
# Load a pre-trained summarization pipeline
summarizer = pipeline("summarization", model="t5-small", framework="pt")
def dl_summarize(text, max_length=150, min_length=30):
summary = summarizer(text, max_length=max_length, min_length=min_length, do_sample=False)
return summary[0]['summary_text']
# Example usage
dl_summary = dl_summarize(text, max_length=60)
print("DL Summary:\n", dl_summary)
🔁 Optional: Use BART or PEGASUS for Better Results
You can switch to better models like:
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
Or:
summarizer = pipeline("summarization", model="google/pegasus-xsum")
Note: These models may require GPU support for faster inference.
📌 Summary
| Method | Type | Pros | Cons |
|---|
| TF-IDF + ML | Extractive | Fast, simple | Less contextual |
| Transformer (T5/BART) | Abstractive | High-quality output | Slower, needs more resources |
Would you like a version that trains your own summarizer model using a dataset like CNN/DM?