{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Dense, SimpleRNN, BatchNormalization\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\nfrom mlxtend.plotting import plot_confusion_matrix\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport nltk\nimport re\nfrom nltk.tokenize import word_tokenize\nimport string\nimport re\nimport nltk\nnltk.download('stopwords')\nnltk.download('wordnet')\nnltk.download('omw-1.4')\nnltk.download('punkt')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:58:42.130475Z","iopub.execute_input":"2022-10-30T01:58:42.130866Z","iopub.status.idle":"2022-10-30T01:58:50.376622Z","shell.execute_reply.started":"2022-10-30T01:58:42.130837Z","shell.execute_reply":"2022-10-30T01:58:50.375454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-10-30T01:48:27.051598Z","iopub.execute_input":"2022-10-30T01:48:27.052023Z","iopub.status.idle":"2022-10-30T01:48:27.059356Z","shell.execute_reply.started":"2022-10-30T01:48:27.051994Z","shell.execute_reply":"2022-10-30T01:48:27.058196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Reading and checking dataset","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv('../input/goodreads-books-reviews-290312/goodreads_train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:49:11.518418Z","iopub.execute_input":"2022-10-30T01:49:11.519364Z","iopub.status.idle":"2022-10-30T01:49:37.768239Z","shell.execute_reply.started":"2022-10-30T01:49:11.519320Z","shell.execute_reply":"2022-10-30T01:49:37.767152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:49:47.061914Z","iopub.execute_input":"2022-10-30T01:49:47.063078Z","iopub.status.idle":"2022-10-30T01:49:47.425934Z","shell.execute_reply.started":"2022-10-30T01:49:47.063036Z","shell.execute_reply":"2022-10-30T01:49:47.424820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Taking only the columns that interest us. The review and ratings.\ndf = df[[\"rating\", \"review_text\"]]\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:50:27.602409Z","iopub.execute_input":"2022-10-30T01:50:27.603345Z","iopub.status.idle":"2022-10-30T01:50:27.643109Z","shell.execute_reply.started":"2022-10-30T01:50:27.603304Z","shell.execute_reply":"2022-10-30T01:50:27.642157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['rating'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:50:49.150139Z","iopub.execute_input":"2022-10-30T01:50:49.150562Z","iopub.status.idle":"2022-10-30T01:50:49.170014Z","shell.execute_reply.started":"2022-10-30T01:50:49.150527Z","shell.execute_reply":"2022-10-30T01:50:49.169091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Balancing our dataset","metadata":{}},{"cell_type":"markdown","source":"I took the amount from the review with less quantity, then I made all the other have the same amount, that is udersampling methode for balancing data .","metadata":{}},{"cell_type":"code","source":"df = df.groupby('rating').head(28718)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:54:44.822371Z","iopub.execute_input":"2022-10-30T01:54:44.822823Z","iopub.status.idle":"2022-10-30T01:54:44.910781Z","shell.execute_reply.started":"2022-10-30T01:54:44.822788Z","shell.execute_reply":"2022-10-30T01:54:44.909598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['rating'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:55:06.533590Z","iopub.execute_input":"2022-10-30T01:55:06.534006Z","iopub.status.idle":"2022-10-30T01:55:06.546056Z","shell.execute_reply.started":"2022-10-30T01:55:06.533974Z","shell.execute_reply":"2022-10-30T01:55:06.544738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Processing","metadata":{}},{"cell_type":"markdown","source":"\nNow we cleaned the reviews from symbols, HTML, URL, punctuation, numbers, emojis and capital letter.  All things that do not influence our interpretation of the data for sentiment analysis","metadata":{}},{"cell_type":"code","source":"def clean_data(data):\n    #Remove HTML\n    data = re.sub(r'<.*?>', '',  data)\n    #Remove URL\n    data = re.sub(r'http\\S+', '', data)\n    #Remove punctuation\n    data = re.sub(r'[^\\w\\s]', '', data)\n    #Remove numbers\n    data = re.sub(r'\\b\\d+\\b', '', data)\n    #Create a list os emojis\n    emoji_pattern = re.compile(\"[\"\n        u\"\\U0001F600-\\U0001F64F\"\n        u\"\\U0001F300-\\U0001F5FF\"\n        u\"\\U0001F680-\\U0001F6FF\"\n        u\"\\U0001F1E0-\\U0001F1FF\"\n        \"]+\", flags=re.UNICODE)\n    #Remove emojis\n    data = emoji_pattern.sub(r'', data)\n    #Make all letters lower case\n    data = data.lower()\n    return data","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:57:55.562432Z","iopub.execute_input":"2022-10-30T01:57:55.562879Z","iopub.status.idle":"2022-10-30T01:57:55.570308Z","shell.execute_reply.started":"2022-10-30T01:57:55.562844Z","shell.execute_reply":"2022-10-30T01:57:55.569118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['review_text'] = df['review_text'].apply(lambda z: clean_data(z))\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:58:59.169251Z","iopub.execute_input":"2022-10-30T01:58:59.169952Z","iopub.status.idle":"2022-10-30T01:59:11.984205Z","shell.execute_reply.started":"2022-10-30T01:58:59.169916Z","shell.execute_reply":"2022-10-30T01:59:11.983018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now i split each review from a big string to a vector of strings for each word.\ndf['review_text'] = df.apply(lambda row: nltk.word_tokenize(row['review_text']), axis=1)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T01:59:58.249125Z","iopub.execute_input":"2022-10-30T01:59:58.249534Z","iopub.status.idle":"2022-10-30T02:01:46.179442Z","shell.execute_reply.started":"2022-10-30T01:59:58.249503Z","shell.execute_reply":"2022-10-30T02:01:46.178153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now i removed all the stopwords from the english language\n\nstop = stopwords.words('english')\n\ndf['review_text'] = df['review_text'].apply(lambda x: [word for word in x if word not in (stop)])\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-30T02:02:48.949600Z","iopub.execute_input":"2022-10-30T02:02:48.950508Z","iopub.status.idle":"2022-10-30T02:03:35.710859Z","shell.execute_reply.started":"2022-10-30T02:02:48.950462Z","shell.execute_reply":"2022-10-30T02:03:35.709686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Lemmatization","metadata":{}},{"cell_type":"markdown","source":"\nLemmatization is basically replacing different forms of the same word for a single one. \nEx:\n    words = [\"connects\", \"connected\", \"strange\", \"am\", \"is\"]\n    lemmatized = [\"connect\", \"connect\", \"strange\", \"be\", \"be\"]\n\n","metadata":{}},{"cell_type":"code","source":"nltk.download('averaged_perceptron_tagger')","metadata":{"execution":{"iopub.status.busy":"2022-10-30T02:03:35.712996Z","iopub.execute_input":"2022-10-30T02:03:35.713418Z","iopub.status.idle":"2022-10-30T02:03:35.739047Z","shell.execute_reply.started":"2022-10-30T02:03:35.713388Z","shell.execute_reply":"2022-10-30T02:03:35.737708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from nltk.corpus import wordnet\n\ndef get_wordnet_pos(word):\n    tag = nltk.pos_tag([word])[0][1][0].upper()\n    tag_dict = {\"J\": wordnet.ADJ,\n                \"N\": wordnet.NOUN,\n                \"V\": wordnet.VERB,\n                \"R\": wordnet.ADV}\n\n    return tag_dict.get(tag, wordnet.NOUN)\n\nfrom nltk.corpus import wordnet\n\ndef lemma_traincorpus(data):\n    lemmatizer=WordNetLemmatizer()\n    out_data= []\n    for words in data:\n        out_data.append(lemmatizer.lemmatize(words, get_wordnet_pos(words)))\n    return out_data","metadata":{"execution":{"iopub.status.busy":"2022-10-30T02:03:35.740418Z","iopub.execute_input":"2022-10-30T02:03:35.741055Z","iopub.status.idle":"2022-10-30T02:03:35.748415Z","shell.execute_reply.started":"2022-10-30T02:03:35.741016Z","shell.execute_reply":"2022-10-30T02:03:35.747049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['review_text']=df['review_text'].apply(lambda z: lemma_traincorpus(z))\ndf.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### TF IDF:","metadata":{}}]}