Bag of Words
Text কে numbers এ convert করার প্রথম formula।
Computer অংক জানে, ভাষা না। তাহলে আমরা যদি ভাষাকে অংকে রূপান্তর করতে পারি — computer ভাষা বুঝবে। সবচেয়ে সহজ recipe: প্রতিটা document কে গুনে দেখুন কোন word কতবার আছে — এটাই Bag of Words। নাম শুনে মনে হবে ছেলেমানুষি, কিন্তু এটা ছিল NLP এর প্রথম বিপ্লব।
Bag of Words (BoW) হলো text কে numeric vector এ রূপান্তর করার সবচেয়ে সহজ technique। প্রথমে পুরো corpus থেকে unique words এর একটা vocabulary বানানো হয়। তারপর প্রতিটা document কে একটা vector হিসেবে represent করা হয় — যেখানে প্রতিটা position এ সেই vocabulary-word টা ওই document এ কতবার এসেছে তার count।
ভাবুন আপনার কাছে অনেকগুলো ব্যাগ আছে, প্রতিটায় বিভিন্ন রঙের মার্বেল। প্রতিটা ব্যাগের 'identity' হলো — কোন রঙের মার্বেল কতটা আছে। Word order, grammar, context — কিছুই matter করে না, শুধু count। সেজন্যই 'bag' — order ভুলে যান, শুধু গণনা গোনেন। 'I love NLP' আর 'NLP love I' — BoW এর কাছে identical!
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
corpus = [
"I love NLP and machine learning",
"Machine learning is fun",
"NLP is a part of machine learning",
"I love Bangla NLP",
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
# Vocabulary
vocab = vectorizer.get_feature_names_out()
print("Vocabulary:", vocab)
# Document-Term Matrix
df = pd.DataFrame(X.toarray(), columns=vocab)
print("\nDocument-Term Matrix:")
print(df)
# Single document encoding
new_text = ["I love machine learning"]
encoded = vectorizer.transform(new_text).toarray()
print("\nEncoded:", encoded)
# With stop word removal + lowercase + bigrams
v2 = CountVectorizer(stop_words="english", ngram_range=(1, 2))
X2 = v2.fit_transform(corpus)
print("\nWith bigrams vocab:", v2.get_feature_names_out())sklearn এর CountVectorizer automatic ভাবে lowercase, tokenize এবং vocabulary build করে দেয়। `fit_transform()` প্রথমে vocabulary শেখে, তারপর count matrix বানায়। `transform()` নতুন text কে existing vocab অনুযায়ী encode করে। `ngram_range=(1,2)` দিলে শুধু single word না, পাশাপাশি 2-word phrase (bigram) ও vocab এ আসে — যা context কিছুটা ধরতে পারে।
১০টা spam SMS এবং ১০টা ham (normal) SMS এর list বানান। CountVectorizer দিয়ে BoW feature বের করুন। sklearn এর MultinomialNB (Naive Bayes) model train করুন। তারপর একটা নতুন SMS দিয়ে predict করুন — spam নাকি ham। এটা world এর সবচেয়ে classic NLP application এর mini version।