Docsity

NLP Lab Experiment/Assignment 8 Group B 6 Program Code SPPU TE AIDS 2024 Pattern, Papers of Natural Language Processing (NLP)

Toggle sidebar
bg1
import pandas as pd
import requests
import re
import spacy
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, precision_score, recall_score, f1_score, confusion_matrix,
classification_report
# Load spaCy
nlp = spacy.load("en_core_web_sm")
# Dataset URLs
imdb_url = "https://raw.githubusercontent.com/SK7here/Movie-Review-Sentiment-Analysis/refs/heads/master/IMDB-
Dataset.csv"
twitter_url = "https://raw.githubusercontent.com/tmun5718/Twitter-Sentiment-
Analysis/refs/heads/master/DataSet/FinalizedFull.csv"
# Load IMDB Dataset
imdb = pd.read_csv(imdb_url)
imdb = imdb.rename(columns={"review":"text","sentiment":"label"})
imdb = pd.concat([
imdb[imdb["label"]=="positive"].head(100),
imdb[imdb["label"]=="negative"].head(100)
], ignore_index=True)
imdb["label"] = imdb["label"].map({"positive":1,"negative":0})
# Load Twitter Dataset
twitter = pd.read_csv(twitter_url)
text_col = [c for c in twitter.columns if "text" in c.lower() or "tweet" in c.lower()][0]
label_col = [c for c in twitter.columns if "sent" in c.lower() or "label" in c.lower()][0]
twitter = twitter[[text_col,label_col]]
twitter.columns = ["text","label"]
twitter["label"] = twitter["label"].astype(str).str.lower()
twitter = twitter[twitter["label"].isin(["positive","negative"])]
twitter = pd.concat([
twitter[twitter["label"]=="positive"].head(100),
twitter[twitter["label"]=="negative"].head(100)
], ignore_index=True)
twitter["label"] = twitter["label"].map({"positive":1,"negative":0})
# Combine datasets
data = pd.concat([imdb[["text","label"]],twitter],ignore_index=True)
# Preprocessing
def clean(text):
text = str(text).lower()
text = re.sub(r"http\S+|www\S+", " ", text)
text = re.sub(r"[^a-z\s]", " ", text)
return text
data["clean_text"] = data["text"].apply(clean)
# TF-IDF
tfidf = TfidfVectorizer(max_features=5000)
X = tfidf.fit_transform(data["clean_text"])
y = data["label"]
# Split Dataset
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
# Train Model
model = LogisticRegression(max_iter=1000)
model.fit(X_train,y_train)
pf2

Partial preview of the text

Download NLP Lab Experiment/Assignment 8 Group B 6 Program Code SPPU TE AIDS 2024 Pattern and more Papers Natural Language Processing (NLP) in PDF only on Docsity!

import pandas as pd import requests import re import spacy 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, precision_score, recall_score, f1_score, confusion_matrix, classification_report

Load spaCy

nlp = spacy.load("en_core_web_sm")

Dataset URLs

imdb_url = "https://raw.githubusercontent.com/SK7here/Movie-Review-Sentiment-Analysis/refs/heads/master/IMDB- Dataset.csv" twitter_url = "https://raw.githubusercontent.com/tmun5718/Twitter-Sentiment- Analysis/refs/heads/master/DataSet/FinalizedFull.csv"

Load IMDB Dataset

imdb = pd.read_csv(imdb_url) imdb = imdb.rename(columns={"review":"text","sentiment":"label"}) imdb = pd.concat([ imdb[imdb["label"]=="positive"].head(100), imdb[imdb["label"]=="negative"].head(100) ], ignore_index=True) imdb["label"] = imdb["label"].map({"positive":1,"negative":0})

Load Twitter Dataset

twitter = pd.read_csv(twitter_url) text_col = [c for c in twitter.columns if "text" in c.lower() or "tweet" in c.lower()][0] label_col = [c for c in twitter.columns if "sent" in c.lower() or "label" in c.lower()][0] twitter = twitter[[text_col,label_col]] twitter.columns = ["text","label"] twitter["label"] = twitter["label"].astype(str).str.lower() twitter = twitter[twitter["label"].isin(["positive","negative"])] twitter = pd.concat([ twitter[twitter["label"]=="positive"].head(100), twitter[twitter["label"]=="negative"].head(100) ], ignore_index=True) twitter["label"] = twitter["label"].map({"positive":1,"negative":0})

Combine datasets

data = pd.concat([imdb[["text","label"]],twitter],ignore_index=True)

Preprocessing

def clean(text): text = str(text).lower() text = re.sub(r"http\S+|www\S+", " ", text) text = re.sub(r"[^a-z\s]", " ", text) return text data["clean_text"] = data["text"].apply(clean)

TF-IDF

tfidf = TfidfVectorizer(max_features=5000) X = tfidf.fit_transform(data["clean_text"]) y = data["label"]

Split Dataset

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y )

Train Model

model = LogisticRegression(max_iter=1000) model.fit(X_train,y_train)

Prediction

y_pred = model.predict(X_test)

Evaluation

print("\nAccuracy :",round(accuracy_score(y_test,y_pred),4)) print("Precision:",round(precision_score(y_test,y_pred),4)) print("Recall :",round(recall_score(y_test,y_pred),4)) print("F1 Score :",round(f1_score(y_test,y_pred),4)) print("\nConfusion Matrix") print(confusion_matrix(y_test,y_pred)) print("\nClassification Report") print(classification_report(y_test,y_pred))

Test Examples

samples = [ "This movie is fantastic and wonderful.", "I hated this film. Waste of time.", "Amazing acting and great story.", "Worst experience ever." ] print("\nSample Predictions") for s in samples: c = clean(s) p = model.predict(tfidf.transform([c]))[0] print(s,"->","Positive" if p==1 else "Negative")

Analysis

print("\nModel Performance Analysis") print("1. TF-IDF converts text into numerical features.") print("2. Logistic Regression performs well for sentiment classification.") print("3. Misclassification may occur because of sarcasm or ambiguous words.") print("4. Using larger datasets and transformer models like BERT can improve accuracy.")

OUTPUT: