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

# + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5"
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session

# + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a"
import warnings
warnings.filterwarnings("ignore")
data = pd.read_csv("/kaggle/input/amazon-fine-food-reviews/Reviews.csv")
print(data.shape)
# -

data.columns

data = data[data['Score']!=3]

data['target'] = data['Score'].apply(lambda x : 1 if x>3 else 0)

#Sorting data according to ProductId in ascending order
data=data.sort_values('ProductId', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
#Deduplication of entries
data=data.drop_duplicates(subset={"UserId","ProfileName","Time","Text"}, keep='first', inplace=False)
print(data.shape)

data.head()

# +
# https://stackoverflow.com/a/47091490/4084039
# https://stackoverflow.com/questions/16206380/python-beautifulsoup-how-to-remove-all-tags-from-an-element
import re
from bs4 import BeautifulSoup

def decontracted(phrase):
    # specific
    phrase = re.sub(r"won't", "will not", phrase)
    phrase = re.sub(r"can\'t", "can not", phrase)

    # general
    phrase = re.sub(r"n\'t", " not", phrase)
    phrase = re.sub(r"\'re", " are", phrase)
    phrase = re.sub(r"\'s", " is", phrase)
    phrase = re.sub(r"\'d", " would", phrase)
    phrase = re.sub(r"\'ll", " will", phrase)
    phrase = re.sub(r"\'t", " not", phrase)
    phrase = re.sub(r"\'ve", " have", phrase)
    phrase = re.sub(r"\'m", " am", phrase)
    return phrase

stopwords= ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've",\
            "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \
            'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their',\
            'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', \
            'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \
            'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \
            'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\
            'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\
            'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\
            'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \
            's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', \
            've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn',\
            "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn',\
            "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", \
            'won', "won't", 'wouldn', "wouldn't"]


from tqdm import tqdm
def preprocess_text(text_data):
    preprocessed_text = []
    for sentance in tqdm(text_data):
        sentance = re.sub(r"http\S+", "", sentance)
        sentance = BeautifulSoup(sentance, 'lxml').get_text()
        sentance = decontracted(sentance)
        sentance = re.sub("\S*\d\S*", "", sentance).strip()
        sentance = re.sub('[^A-Za-z]+', ' ', sentance)
        #sent = ' '.join(e for e in sent.split() if e.lower() not in stopwords)
        preprocessed_text.append(sentance.lower().strip())
    return preprocessed_text


# -

from wordcloud import WordCloud
from tqdm import tqdm_notebook as tqdm
import matplotlib.pyplot as plt
def plot_word_cloud(data):
    text = " ".join(review.lower() for review in data)
    wordcloud = WordCloud(width = 800, height = 800, 
                        background_color ='white', 
                        stopwords = stopwords, 
                        min_font_size = 10).generate(text)
    plt.figure(figsize = (8, 8), facecolor = None) 
    plt.imshow(wordcloud) 
    plt.axis("off")
    plt.tight_layout(pad = 0) 
    plt.show()


preprocessed_reviews = preprocess_text(data['Text'].values)
labels = data['target'].values

data['Text'] = preprocessed_reviews

# %%time
plot_word_cloud(data['Text'].values)

# %%time
plot_word_cloud(data.loc[data['target'] == 0]['Text'].values)

# %%time
plot_word_cloud(data.loc[data['target'] == 1]['Text'].values)

pd.Series(labels).value_counts()

# +
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import one_hot
from keras.preprocessing.text import Tokenizer
from sklearn.model_selection import train_test_split
from scipy import sparse
x_train,x_cv, y_train, y_cv = train_test_split(preprocessed_reviews, labels, test_size=0.2, random_state=42, stratify=labels)

MAX_SEQUENCE_LENGTH = 4000
MAX_NUM_WORDS = 20000
tokenizer = Tokenizer(num_words=MAX_NUM_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\\]^`{|}~\t\n')

tokenizer.fit_on_texts(x_train)

encoded_docs_train = tokenizer.texts_to_sequences(x_train)
padded_text_train=pad_sequences(encoded_docs_train,maxlen=MAX_SEQUENCE_LENGTH, padding="post", truncating="post").astype('int16')
encoded_docs_cv = tokenizer.texts_to_sequences(x_cv)
padded_text_cv=pad_sequences(encoded_docs_cv,maxlen=MAX_SEQUENCE_LENGTH, padding="post", truncating="post").astype('int16')
word_index = tokenizer.word_index
# -

import pickle
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

print(padded_text_train[0])

print(padded_text_cv.shape)

from sklearn.preprocessing import Normalizer
transformer = Normalizer()
transformer.fit(padded_text_train)
padded_text_train_norm = transformer.transform(padded_text_train)
padded_text_cv_norm =transformer.transform(padded_text_cv)

# ### Training a simple model

# +
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, confusion_matrix
from scipy.stats import uniform
from sklearn.linear_model import LogisticRegression as lr
import seaborn as sns

clf = lr()
clf.fit(padded_text_train_norm, y_train)
y_pred = clf.predict(padded_text_cv_norm)
print("Acccuracy is",accuracy_score(y_cv,y_pred))
print("F1 score is", f1_score(y_cv, y_pred))
confusion_matrix_test = confusion_matrix(y_cv, y_pred)
sns.heatmap(confusion_matrix_test,xticklabels=["1","0"], yticklabels=["1","0"],annot=True).set_title("Confusion Matrix")
plt.show()
# -

# ### Comaparing and Fine tuning ML classification models

from xgboost import XGBClassifier
models = {
    'lr': lr(),
    'svc': SVC(),
    'dtc':DecisionTreeClassifier(),
    'rfc': RandomForestClassifier(),
    'xgbc':XGBClassifier(objective = 'binary:logistic', verbosity = 0)
}


def train_and_test_model(model_key, distributions, model_name):
    print("Model training", model_name)
    model = models[model_key]
    clf = RandomizedSearchCV(model, distributions, random_state=0, n_iter = 10, verbose=0)
    clf.fit(padded_text_train_norm, y_train)
    print(clf.best_estimator_)
    final_model = clf.best_estimator_
    final_model.fit(padded_text_train_norm, y_train)
    y_pred = final_model.predict(padded_text_cv)
    print("Acccuracy is",accuracy_score(y_cv,y_pred))
    print("F1 score is", f1_score(y_cv, y_pred))
    confusion_matrix_test = confusion_matrix(y_cv, y_pred)
    sns.heatmap(confusion_matrix_test,xticklabels=["1","0"], yticklabels=["1","0"],annot=True).set_title("Confusion Matrix")
    plt.show()


distributions = dict(C=uniform(loc=0.00001, scale=10000), penalty=['l2', 'l1'], class_weight=['balanced', None])
train_and_test_model('lr', distributions, "logistic regression")

distributions = dict(C=uniform(loc=0.00001, scale=10000),kernel=['linear', 'poly', 'rbf', 'sigmoid'] ,coef0=uniform(loc=0, scale=10), class_weight=['balanced', None], gamma=['scale', 'auto'])
train_and_test_model('svc', distributions, "SVM")

from scipy.stats import randint
distributions = dict(criterion=['gini', 'entropy'], splitter=['best', 'random'], max_depth = randint(1, 100), min_samples_split= uniform(loc=0, scale=1), max_features=['auto', 'sqrt', 'log2'], class_weight=['balanced', None])
train_and_test_model('dtc', distributions, "Decisoin Tree Classifier")

distributions = dict(criterion=['gini', 'entropy'], n_estimators = randint(10, 500) , max_depth = randint(1, 100), min_samples_split= uniform(loc=0, scale=1), max_features=['auto', 'sqrt', 'log2'], class_weight=['balanced', 'balanced_subsample', None])
train_and_test_model('rfc', distributions, "Random forest classifier")

StarcoderdataJupyterScriptsDedupFiltered