4-A: CBOW for Document Classification

# Install once if needed:
# pip install pandas numpy gensim scikit-learn tensorflow

# 1. Import libraries
import re
import numpy as np
import pandas as pd

from gensim.models import Word2Vec
from sklearn.model_selection import train_test_split

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# 2. Load dataset
df = pd.read_csv("IMDB Dataset.csv")

# 3. Preprocess reviews
def clean_text(text):
    text = re.sub(r"<.*?>", " ", text)
    text = re.sub(r"[^a-zA-Z\s]", " ", text)
    return text.lower().split()

sentences = df["review"].apply(clean_text).tolist()
labels = df["sentiment"].map({"positive": 1, "negative": 0}).values

# 4. Split into training and testing data
X_train_text, X_test_text, y_train, y_test = train_test_split(
    sentences, labels, test_size=0.2, random_state=42
)

# 5. Train CBOW model (sg=0 means CBOW)
cbow_model = Word2Vec(
    sentences=X_train_text,
    vector_size=100,
    window=5,
    min_count=2,
    sg=0,
    workers=4,
    epochs=5
)

# 6. Represent each review by averaging word embeddings
def document_vector(words):
    vectors = [
        cbow_model.wv[word]
        for word in words
        if word in cbow_model.wv
    ]

    if len(vectors) == 0:
        return np.zeros(100)

    return np.mean(vectors, axis=0)

X_train = np.array([document_vector(s) for s in X_train_text])
X_test = np.array([document_vector(s) for s in X_test_text])

# 7. Build classification model
model = Sequential([
    Dense(64, activation="relu", input_shape=(100,)),
    Dense(1, activation="sigmoid")
])

model.compile(
    optimizer="adam",
    loss="binary_crossentropy",
    metrics=["accuracy"]
)

# 8. Train model
model.fit(
    X_train, y_train,
    epochs=5,
    batch_size=32,
    validation_split=0.2
)

# 9. Evaluate model
loss, accuracy = model.evaluate(X_test, y_test)

print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
