{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# 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\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"imdb = pd.read_csv('https://raw.githubusercontent.com/skathirmani/datasets/master/imdb_sentiment.csv')\nimdb.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Sentiment Analysis - Text Classification","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from gensim.parsing.preprocessing import remove_stopwords\nfrom gensim.parsing.porter import PorterStemmer\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\nstemmer = PorterStemmer()\n\ndef clean_documents(docs):\n    stemmer = PorterStemmer()\n    docs_clean = docs.str.lower()\n    docs_clean = docs_clean.str.replace('[^a-z\\s]', '')\n    docs_clean = docs_clean.apply(lambda doc: remove_stopwords(doc))\n    #docs_clean = pd.Series(stemmer.stem_documents(docs_clean), index=docs.index)\n    docs_clean = pd.Series(docs_clean, index=docs.index)\n    return docs_clean","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"docs_cleaned = clean_documents(imdb['review'])\ntrain_x, validate_x, train_y, validate_y = train_test_split(docs_cleaned,\n                                                           imdb['sentiment'],\n                                                           test_size=0.2,\n                                                           random_state=1)\ntrain_x.shape, validate_x.shape, train_y.shape, validate_y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vectorizer = CountVectorizer(min_df=2,stop_words='english',).fit(train_x)\nvocab = vectorizer.get_feature_names()\ntrain_dtm = vectorizer.transform(train_x)\nvalidate_dtm = vectorizer.transform(validate_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_model = MultinomialNB().fit(train_dtm, train_y)\npred_validate_y = pd.Series(nb_model.predict(validate_dtm), index=validate_y.index)\nprint(accuracy_score(validate_y, pred_validate_y))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### TF-IDF Transformation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\ntfidf_vectorizer = TfidfVectorizer(stop_words='english',).fit(train_x)\nvocab = tfidf_vectorizer.get_feature_names()\ntrain_dtm_tfidf = tfidf_vectorizer.transform(train_x)\nvalidate_dtm_tfidf = tfidf_vectorizer.transform(validate_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_model_tfidf = MultinomialNB().fit(train_dtm_tfidf, train_y)\npred_validate_y = pd.Series(nb_model_tfidf.predict(validate_dtm_tfidf), index=validate_y.index)\nprint(accuracy_score(validate_y, pred_validate_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"### Word Embeddings\nimport zipfile\nimport gensim","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"archive = zipfile.ZipFile('/kaggle/input/quora-insincere-questions-classification/embeddings.zip', 'r')\narchive.namelist()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = 'GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nembeddings = gensim.models.KeyedVectors.load_word2vec_format(archive.open(path), binary=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#embeddings.most_similar('mercedes', topn=10)\n#embeddings['india']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_docs_vectors = pd.DataFrame()\ntokens_missing = []\nfor doc in docs_cleaned:\n    temp = pd.DataFrame()\n    for token in doc.split(' '):\n        try:\n            word_vector = embeddings[token]\n            temp = temp.append(pd.Series(word_vector), ignore_index=True)\n        except:\n            tokens_missing.append(token)\n    \n    doc_vector = temp.mean()\n    all_docs_vectors = all_docs_vectors.append(doc_vector, ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_docs_vectors.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_x, validate_x, train_y, validate_y = train_test_split(all_docs_vectors.fillna(0),\n                                                           imdb['sentiment'],\n                                                           test_size=0.2,\n                                                           random_state=1)\ntrain_x.shape, validate_x.shape, train_y.shape, validate_y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=100).fit(train_x, train_y)\nvalidate_y_pred = rf.predict(validate_x)\nprint(accuracy_score(validate_y, validate_y_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"docs_tokens = docs_cleaned.str.split(' ').tolist()\ntrain_x, validate_x, train_y, validate_y = train_test_split(docs_cleaned,\n                                                           imdb['sentiment'],\n                                                           test_size=0.2,\n                                                           random_state=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten\nfrom keras.layers.embeddings import Embedding\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vocab = set(x for l in docs_tokens for x in l)\nvocab_size = len(vocab)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_y_labels = np.array(train_y)\nvocab_size = len(vocab)\nmax_length = max([len(x) for x in docs_tokens])\nencoded_docs = [one_hot(d, vocab_size) for d in train_x]\npadded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, 300, input_length=max_length))\nmodel.add(Flatten())\nmodel.add(Dense(8, activation='sigmoid'))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='adam', loss='binary_crossentropy')\nmodel.fit(padded_docs, train_y_labels,\n          epochs=3, batch_size=1000,\n          validation_split=0.2,\n          callbacks=[callback],\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoded_docs = [one_hot(d, vocab_size) for d in validate_x]\npadded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')\nvalidate_y_pred = model.predict_classes(padded_docs).flatten()\naccuracy_score(validate_y.values, validate_y_pred)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Polarity based sentiment analysis","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"imdb['review'].iloc[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nsentiment_analyzer = SentimentIntensityAnalyzer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sentiment_analyzer.polarity_scores('they love coffee')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = 0.5\ncs = score / np.sqrt(np.square(score) + 15)\ncs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Case is important\n## Punct is important\n## very, not are important\n## Stemming is not used","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(sentiment_analyzer.polarity_scores('they love coffee')['compound'])\nprint(sentiment_analyzer.polarity_scores('they LOVE coffee')['compound'])\nprint(sentiment_analyzer.polarity_scores('they LOVE!!! coffee')['compound'])\nprint(sentiment_analyzer.polarity_scores('they very LOVE!!! coffee')['compound'])\nprint(sentiment_analyzer.polarity_scores('they very LOVE :) coffee')['compound'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"docs = imdb.loc[validate_x.index]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"docs['compound'] = docs['review'].apply(lambda v: sentiment_analyzer.polarity_scores(v)['compound'])\ndocs['sentiment_vader'] = docs['compound'].apply(lambda v: 1 if v >0 else 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy_score(docs['sentiment'], docs['sentiment_vader'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sentiment_analyzer.polarity_scores(\"there are better movies in youtube\")","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}