53. Sentiment Analysis Project in Python
53.2 Copy-Run TF-IDF + LogisticRegression
Why. You need a copy-run spine you can paste into Jupyter and extend.
What. One script: data → split → vectorise → fit classifier → predict → score.
How.
Copy-run the mini project
- Create docs and y.
- Stratified train_test_split.
- TfidfVectorizer fit on train.
- LogisticRegression fit; print accuracy on test.
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
docs = [
"fresh pedha on time delivery",
"sour dahi and torn packing",
"sweet pedha excellent taste",
"late delivery cold chain fail",
"good packing fresh dahi",
"bad smell sour tray returned",
"on time from nashik hub",
"not good packing damaged box",
"loved the pedha box",
"refund please spoiled dahi",
"fresh and neat packing",
"worst delivery experience",
]
y = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
X_train, X_test, y_train, y_test = train_test_split(
docs, y, test_size=0.33, random_state=42, stratify=y
)
vec = TfidfVectorizer(ngram_range=(1, 2), stop_words="english")
Xtr = vec.fit_transform(X_train)
Xte = vec.transform(X_test)
clf = LogisticRegression(max_iter=200)
clf.fit(Xtr, y_train)
pred = clf.predict(Xte)
print("accuracy:", round(accuracy_score(y_test, pred), 3))
print(classification_report(y_test, pred, zero_division=0))
What you should see. An accuracy print and a small classification report. With tiny data, scores bounce — the goal is the pipeline, not a leaderboard.