# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/towardsai/tutorials/blob/master/sentiment_analysis_tutorial/sentiment_analysis_tutorial.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="WF4Qh5xVqM4D"
# # Sentiment Analysis on Women's Dress Review
#
# * Tutorial: https://towardsai.net/p/nlp/sentiment-analysis-opinion-mining-with-python-nlp-tutorial-d1f173ca4e3c
#
# * Github: https://github.com/towardsai/tutorials/tree/master/sentyment_analysis_tutorial

# + [markdown] id="cCdKoergjmDw"
# **Download Dataset**

# + colab={"base_uri": "https://localhost:8080/"} id="VLl8z7VEjpMw" outputId="f9c9a841-ef4d-4658-9445-30b7acf02068"
# !wget https://raw.githubusercontent.com/towardsai/tutorials/master/sentiment_analysis_tutorial/women_clothing_review.csv

# + [markdown] id="-hBtFjjoqV2_"
# **Import All Required Packages**

# + colab={"base_uri": "https://localhost:8080/"} id="-sSRIdY1HZCS" outputId="ab15e23e-0924-42bb-c694-f4ddb58df4ef"
import pandas as pd
import numpy as np
import seaborn as sns
import re
import string
from string import punctuation
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')


import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.callbacks import EarlyStopping

# + [markdown] id="YUH7jv5KrgG-"
# **Read data from csv**

# + colab={"base_uri": "https://localhost:8080/", "height": 306} id="aBdnYpaqqEfs" outputId="c4a417df-8a1e-42b2-de17-ed4e672cbbf3"
df = pd.read_csv('women_clothing_review.csv')
df.head()

# + [markdown] id="N1DXfvBurnSO"
# **Drop unnecessary columns**

# + id="Gn_vu_gprlK1"
df = df.drop(['Title', 'Positive Feedback Count', 'Unnamed: 0', ], axis=1)
df.dropna(inplace=True)

# + [markdown] id="VqT2elfcs4tj"
# **Calculation of Polarity**

# + id="GY08-o4YzR1i"
df['Polarity_Rating'] = df['Rating'].apply(lambda x: 'Positive' if x > 3 else('Neutral' if x == 3  else 'Negative'))

# + colab={"base_uri": "https://localhost:8080/", "height": 202} id="6b0k-DA-0IYJ" outputId="623e6ff7-6699-4a3d-b08f-8f79bf2ce8d3"
df.head()

# + [markdown] id="lMD-lue81NME"
# **Plot the Rating visualization graph**

# + colab={"base_uri": "https://localhost:8080/", "height": 297} id="EwQ5_FWh1R-p" outputId="1db2e56f-a522-400a-8edf-235f14cd73dd"
sns.set_style('whitegrid')
sns.countplot(x='Rating',data=df, palette='YlGnBu_r')

# + [markdown] id="cObGcj-R1_Uf"
# **Plot the Polarity Rating count**

# + colab={"base_uri": "https://localhost:8080/", "height": 297} id="TglKEwxS2DcK" outputId="32a9bc27-7a55-450e-c1fd-e3380a0af5d1"
sns.set_style('whitegrid')
sns.countplot(x='Polarity_Rating',data=df, palette='summer')

# + [markdown] id="l2ppN_Gj3MXZ"
# **Data Preprocessing**

# + id="KMryD2Ok3PbF"
df_Positive = df[df['Polarity_Rating'] == 'Positive'][0:8000]
df_Neutral = df[df['Polarity_Rating'] == 'Neutral']
df_Negative = df[df['Polarity_Rating'] == 'Negative']

# + [markdown] id="mUZim1eA3qDF"
# **Sample negative and neutral polarity dataset and create final dataframe**

# + id="9PqqFadV4Qaf"
df_Neutral_over = df_Neutral.sample(8000, replace=True)
df_Negative_over = df_Negative.sample(8000, replace=True)
df = pd.concat([df_Positive, df_Neutral_over, df_Negative_over], axis=0)


# + [markdown] id="B3so3XNt5PXg"
# **Text Preprocessing**

# + id="mvi7pt-d5R6E"
def get_text_processing(text):
    stpword = stopwords.words('english')
    no_punctuation = [char for char in text if char not in string.punctuation]
    no_punctuation = ''.join(no_punctuation)
    return ' '.join([word for word in no_punctuation.split() if word.lower() not in stpword])


# + [markdown] id="1F75BGMk5zbT"
# **Apply the method "get_text_processing" into column review text**

# + colab={"base_uri": "https://localhost:8080/", "height": 306} id="52_Rbc3p5953" outputId="5e231d9d-8ea7-4821-d0a6-e8f956efb97f"
df['review'] = df['Review Text'].apply(get_text_processing)
df.head()

# + [markdown] id="Fhxnn-pj7R6P"
# **Visualize Text Review with Polarity Rating**

# + colab={"base_uri": "https://localhost:8080/", "height": 202} id="yFeqv9LG7N5N" outputId="a06a4655-55ed-4748-e2c4-90d8820c70b1"
df = df[['review', 'Polarity_Rating']]
df.head()

# + [markdown] id="rwpsuZPk8HCS"
# **Apply One hot encoding on negative, neutral, and positive**

# + colab={"base_uri": "https://localhost:8080/", "height": 202} id="lHrXiYDQ8Pj6" outputId="a80ce8f8-e4f3-4a6a-9f39-0f95d17d0007"
one_hot = pd.get_dummies(df["Polarity_Rating"])
df.drop(['Polarity_Rating'],axis=1,inplace=True)
df = pd.concat([df,one_hot],axis=1)
df.head()

# + [markdown] id="O63qBfKuE2nu"
# **Apply Train Test Split**

# + id="6PNWLYhME7Pf"
X = df['review'].values
y = df.drop('review', axis=1).values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)

# + [markdown] id="AuADdT8UFgOy"
# **Apply vectorization**

# + id="r20vXgZ6Fvqw"
vect = CountVectorizer()
X_train = vect.fit_transform(X_train)
X_test = vect.transform(X_test)

# + [markdown] id="akiDMHsvGNxD"
# **Apply frequency, inverse document frequency:**

# + id="_q3-ppruGRz7"
tfidf = TfidfTransformer()
X_train = tfidf.fit_transform(X_train)
X_test = tfidf.transform(X_test)
X_train = X_train.toarray()
X_test = X_test.toarray()

# + [markdown] id="rXV_Xf5kHB73"
# **Add different layers**

# + id="-Su4eu41HAUT"
model = Sequential()

model.add(Dense(units=12673,activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(units=4000,activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(units=500,activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(units=3, activation='softmax'))

opt=tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

early_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=2)

# + [markdown] id="NYGn2m1lIFvo"
# **Fit the Model**

# + colab={"base_uri": "https://localhost:8080/"} id="NtKRqIcYIEev" outputId="0de54d2f-bc01-4606-e290-1f0b216baab5"
model.fit(x=X_train, y=y_train, batch_size=256, epochs=100, validation_data=(X_test, y_test), verbose=1, callbacks=early_stop)

# + [markdown] id="mOSbaNrqJBeP"
# **Evaluation of Model**

# + id="ZTsIgolQJD2M"
model_score = model.evaluate(X_test, y_test, batch_size=64, verbose=1)
print('Test accuracy:', model_score[1])

# + [markdown] id="s6c7yRFKJUK4"
# **Prediction**

# + id="Q34Yb_0pJW3r"
preds = model.predict(X_test)
preds

StarcoderdataJupyterScriptsDedupFiltered