51. What Is Natural Language Processing (NLP)
51.4 Bag-of-Words Intuition
Why. Text is not one float column. You must turn documents into a matrix before sklearn fit.
What. Classic idea: bag of words — count how often each word appears, ignore grammar order at first. Next chapter upgrades counts to TF-IDF (smarter weights). Labels (y) stay 0/1 for sentiment.
How.
See documents as rows
- Each review = one document (one row).
- Vocabulary = unique tokens across the training set.
- Cell value = count (or later TF-IDF weight) of that token in that review.
- y = sentiment label known from humans.
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"fresh pedha on time",
"sour dahi late delivery",
"fresh dahi good packing",
]
y = [1, 0, 1] # 1=positive, 0=negative (fictional)
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray())
print("y:", y)
Ravindra Bagale's Tip
Bag-of-words only counts words, like items in a basket, and it ignores their order. So a phrase like "not good" is a hard case for it. Even so, it gives a strong baseline for many tasks such as tagging tickets, and TF-IDF in the next chapter makes it smarter.
Ravindra Bagale's Tip – मराठी
Bag-of-words फक्त words मोजतं, जसं basket मधल्या वस्तू मोजतो, आणि त्यांचा क्रम (order) लक्षात घेत नाही. त्यामुळे "not good" सारखा phrase त्याच्यासाठी अवघड case आहे. तरीही tickets ला tag लावण्यासारख्या अनेक कामांसाठी तो एक मजबूत baseline देतो, आणि पुढच्या chapter मधलं TF-IDF त्याला अजून smart बनवतं.
Ravindra Bagale's Tip – हिंदी
Bag-of-words सिर्फ words गिनता है, जैसे basket में रखी चीज़ें गिनते हैं, और उनका क्रम (order) नहीं देखता. इसलिए "not good" जैसा phrase उसके लिए मुश्किल case है. फिर भी tickets को tag करने जैसे कई कामों के लिए यह एक मज़बूत baseline देता है, और अगले chapter का TF-IDF इसे और smart बनाता है.