{"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":"markdown","source":"# Author\nAdvisor: **Dr. Nguyen Thanh Binh**, University of Science, Vietnam National University Ho Chi Minh City, Vietnam.\n\n**Tran Quang Linh**, University of Information Technology, Vietnam National University Ho Chi Minh City, Vietnam.\n\n**Duong Van Binh**, University of Information Technology, Vietnam National University Ho Chi Minh City, Vietnam.\n\n","metadata":{}},{"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-06-30T03:58:26.618807Z","iopub.execute_input":"2022-06-30T03:58:26.619233Z","iopub.status.idle":"2022-06-30T03:58:26.628576Z","shell.execute_reply.started":"2022-06-30T03:58:26.619178Z","shell.execute_reply":"2022-06-30T03:58:26.627409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocessing the data","metadata":{}},{"cell_type":"code","source":"!pip install nltk","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:58:26.630516Z","iopub.execute_input":"2022-06-30T03:58:26.630993Z","iopub.status.idle":"2022-06-30T03:58:59.731757Z","shell.execute_reply.started":"2022-06-30T03:58:26.630947Z","shell.execute_reply":"2022-06-30T03:58:59.730767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport re\nimport numpy as np\nimport tensorflow as tf\nimport json\nimport pickle\nimport nltk\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:58:59.734324Z","iopub.execute_input":"2022-06-30T03:58:59.734994Z","iopub.status.idle":"2022-06-30T03:59:07.613542Z","shell.execute_reply.started":"2022-06-30T03:58:59.734953Z","shell.execute_reply":"2022-06-30T03:59:07.612793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/fashion-and-beauty-reviews/review_train.tsv\", sep = '\\t')","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:07.615058Z","iopub.execute_input":"2022-06-30T03:59:07.616398Z","iopub.status.idle":"2022-06-30T03:59:13.94247Z","shell.execute_reply.started":"2022-06-30T03:59:07.616352Z","shell.execute_reply":"2022-06-30T03:59:13.941359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = pd.read_csv(\"/kaggle/input/fashion-and-beauty-reviews/review_test_post.tsv\", sep = '\\t')","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:13.944709Z","iopub.execute_input":"2022-06-30T03:59:13.945106Z","iopub.status.idle":"2022-06-30T03:59:15.434636Z","shell.execute_reply.started":"2022-06-30T03:59:13.945072Z","shell.execute_reply":"2022-06-30T03:59:15.433584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.fillna(\"N/A\", inplace = True)\ndf_test.fillna(\"N/A\", inplace = True)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:15.435983Z","iopub.execute_input":"2022-06-30T03:59:15.436349Z","iopub.status.idle":"2022-06-30T03:59:16.0174Z","shell.execute_reply.started":"2022-06-30T03:59:15.436318Z","shell.execute_reply":"2022-06-30T03:59:16.016351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocessing the comment and summary. Including lowercase the text, remove html tag, remove unnecessary punctuation.\ndef preprocessing(text):\n    text = text.lower()\n    html = re.compile(\"<.*?>\")\n    text = html.sub(r\"\", text)\n    text = re.sub(\"[^\\w\\s]\", \"\", text)\n    return text","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:16.018817Z","iopub.execute_input":"2022-06-30T03:59:16.019327Z","iopub.status.idle":"2022-06-30T03:59:16.025869Z","shell.execute_reply.started":"2022-06-30T03:59:16.019281Z","shell.execute_reply":"2022-06-30T03:59:16.025008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"processed_review_train = []\nfor i in df.review.values:\n  if i == 'N/A':\n    processed_review_train.append(\"N/A\")\n  else:\n    processed_review_train.append(preprocessing(i))","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:16.026988Z","iopub.execute_input":"2022-06-30T03:59:16.027455Z","iopub.status.idle":"2022-06-30T03:59:26.099911Z","shell.execute_reply.started":"2022-06-30T03:59:16.027422Z","shell.execute_reply":"2022-06-30T03:59:26.098873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"processed_review_test = []\nfor i in df_test.review.values:\n  if i == 'N/A':\n    processed_review_test.append(\"N/A\")\n  else:\n    processed_review_test.append(preprocessing(i))","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:26.101058Z","iopub.execute_input":"2022-06-30T03:59:26.10144Z","iopub.status.idle":"2022-06-30T03:59:28.639409Z","shell.execute_reply.started":"2022-06-30T03:59:26.101398Z","shell.execute_reply":"2022-06-30T03:59:28.638246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"processed_sum_test = []\nfor i in df_test.summary.values:\n  if i == 'N/A':\n    processed_sum_test.append(\"N/A\")\n  else:\n    processed_sum_test.append(preprocessing(i))","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:28.640818Z","iopub.execute_input":"2022-06-30T03:59:28.641187Z","iopub.status.idle":"2022-06-30T03:59:29.658273Z","shell.execute_reply.started":"2022-06-30T03:59:28.641155Z","shell.execute_reply":"2022-06-30T03:59:29.656976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"processed_sum_train = []\nfor i in df.summary.values:\n  if i == 'N/A':\n    processed_sum_train.append(\"N/A\")\n  else:\n    processed_sum_train.append(preprocessing(i))","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:29.661248Z","iopub.execute_input":"2022-06-30T03:59:29.661644Z","iopub.status.idle":"2022-06-30T03:59:33.684078Z","shell.execute_reply.started":"2022-06-30T03:59:29.661609Z","shell.execute_reply":"2022-06-30T03:59:33.682997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['processed_review']  = processed_review_train\ndf_test['processed_review']  = processed_review_test\ndf['processed_summary']  = processed_sum_train\ndf_test['processed_summary']  = processed_sum_test","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:33.68553Z","iopub.execute_input":"2022-06-30T03:59:33.685883Z","iopub.status.idle":"2022-06-30T03:59:33.941733Z","shell.execute_reply.started":"2022-06-30T03:59:33.685852Z","shell.execute_reply":"2022-06-30T03:59:33.940749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Concat review and summary to have a comprehensive text\ndf['summary_review'] = df['processed_summary']+' '+df['processed_review']\ndf_test['summary_review'] = df_test['processed_summary']+' '+df_test['processed_review']","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:33.943325Z","iopub.execute_input":"2022-06-30T03:59:33.944281Z","iopub.status.idle":"2022-06-30T03:59:34.645988Z","shell.execute_reply.started":"2022-06-30T03:59:33.944233Z","shell.execute_reply":"2022-06-30T03:59:34.644537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:34.647282Z","iopub.execute_input":"2022-06-30T03:59:34.647677Z","iopub.status.idle":"2022-06-30T03:59:34.70968Z","shell.execute_reply.started":"2022-06-30T03:59:34.647644Z","shell.execute_reply":"2022-06-30T03:59:34.708846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"./processed_train.csv\", index = False, sep = '\\t')\ndf_test.to_csv(\"./processed_test.csv\", index = False, sep = '\\t')","metadata":{"execution":{"iopub.status.busy":"2022-06-30T03:59:34.710848Z","iopub.execute_input":"2022-06-30T03:59:34.711365Z","iopub.status.idle":"2022-06-30T04:00:09.1817Z","shell.execute_reply.started":"2022-06-30T03:59:34.71133Z","shell.execute_reply":"2022-06-30T04:00:09.180594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using keyword to predict rating _ Rule-based approach\nThe idea is based on summary to predict the rating of review.\n\nAfter reviewing the dataset, we see that many summaries have the same rating star. For example: summary: \"Five Stars\" has the rating 5.\n\nWe choose top 300 frequently summaries and examing the rating distribution of these summaries. If a summary has the rating star dominating over 70% then we assign that rating to that summary.\nFor example: The summary \"Five Stars\" have the rating distribution as follow {1:0.01, 2:0.05, 3:0.1, 4:0.1, 5:0.74} -> 5 stars is the dominant rating (0.74 > 0.7) so we assign all reviews with summary \"Five Stars\" to 5 in the test set. \n\nThe result shows that 40% of the training and testing datasets belong to the above summaries. The rmse of this approach in training set is 0.20, a great number.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:00:09.182971Z","iopub.execute_input":"2022-06-30T04:00:09.18334Z","iopub.status.idle":"2022-06-30T04:00:09.188398Z","shell.execute_reply.started":"2022-06-30T04:00:09.183308Z","shell.execute_reply":"2022-06-30T04:00:09.187328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"./processed_train.csv\", sep = '\\t')\ndf","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:00:09.190128Z","iopub.execute_input":"2022-06-30T04:00:09.190637Z","iopub.status.idle":"2022-06-30T04:00:19.701085Z","shell.execute_reply.started":"2022-06-30T04:00:09.190591Z","shell.execute_reply":"2022-06-30T04:00:19.700147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"list_key = df['processed_summary'].value_counts()[:300].index\nhigh_key = []\nhigh_rate = []\nfor key in list_key:\n    if (df[df['processed_summary']==key].rating.value_counts()/(df[df['processed_summary']==key].rating.value_counts().sum())).values[0] > 0.7:\n        high_key.append(key)\n        high_rate.append(df[df['processed_summary']==key].rating.value_counts().index[0])","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:00:19.702511Z","iopub.execute_input":"2022-06-30T04:00:19.703462Z","iopub.status.idle":"2022-06-30T04:02:20.647015Z","shell.execute_reply.started":"2022-06-30T04:00:19.703396Z","shell.execute_reply":"2022-06-30T04:02:20.646045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(high_key))\nlen(high_rate)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:20.648306Z","iopub.execute_input":"2022-06-30T04:02:20.648624Z","iopub.status.idle":"2022-06-30T04:02:20.655835Z","shell.execute_reply.started":"2022-06-30T04:02:20.648596Z","shell.execute_reply":"2022-06-30T04:02:20.654716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_high = df[df['processed_summary'].isin(high_key)]\ndef predicted_rate(row):\n    for i in range(len(high_key)):\n        if row==high_key[i]:\n            return high_rate[i]\ndf_high['predicted_rating'] = df_high['processed_summary'].apply(predicted_rate)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:20.657442Z","iopub.execute_input":"2022-06-30T04:02:20.657878Z","iopub.status.idle":"2022-06-30T04:02:21.629261Z","shell.execute_reply.started":"2022-06-30T04:02:20.657833Z","shell.execute_reply":"2022-06-30T04:02:21.628232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_high.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:21.630567Z","iopub.execute_input":"2022-06-30T04:02:21.63092Z","iopub.status.idle":"2022-06-30T04:02:21.637683Z","shell.execute_reply.started":"2022-06-30T04:02:21.630885Z","shell.execute_reply":"2022-06-30T04:02:21.636599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(np.sqrt(mean_squared_error(df_high['rating'], df_high['predicted_rating'])))","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:21.639128Z","iopub.execute_input":"2022-06-30T04:02:21.639783Z","iopub.status.idle":"2022-06-30T04:02:21.653707Z","shell.execute_reply.started":"2022-06-30T04:02:21.639735Z","shell.execute_reply":"2022-06-30T04:02:21.652949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_remain = df[~df.index.isin(df_high.index)]","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:21.654967Z","iopub.execute_input":"2022-06-30T04:02:21.655317Z","iopub.status.idle":"2022-06-30T04:02:21.811679Z","shell.execute_reply.started":"2022-06-30T04:02:21.655285Z","shell.execute_reply":"2022-06-30T04:02:21.810596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_remain.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:21.812881Z","iopub.execute_input":"2022-06-30T04:02:21.813591Z","iopub.status.idle":"2022-06-30T04:02:21.819914Z","shell.execute_reply.started":"2022-06-30T04:02:21.813554Z","shell.execute_reply":"2022-06-30T04:02:21.818961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, df_val = train_test_split(df_remain, train_size=0.9, random_state =42)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:21.821583Z","iopub.execute_input":"2022-06-30T04:02:21.822233Z","iopub.status.idle":"2022-06-30T04:02:22.513754Z","shell.execute_reply.started":"2022-06-30T04:02:21.822187Z","shell.execute_reply":"2022-06-30T04:02:22.512695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_val.rating.value_counts()/df_val.shape[0]","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:22.51526Z","iopub.execute_input":"2022-06-30T04:02:22.515732Z","iopub.status.idle":"2022-06-30T04:02:22.526016Z","shell.execute_reply.started":"2022-06-30T04:02:22.515698Z","shell.execute_reply":"2022-06-30T04:02:22.525062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.to_csv(\"./splited_train.csv\", index = False)\ndf_val.to_csv(\"./splited_val.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:22.527388Z","iopub.execute_input":"2022-06-30T04:02:22.527728Z","iopub.status.idle":"2022-06-30T04:02:48.277814Z","shell.execute_reply.started":"2022-06-30T04:02:22.527698Z","shell.execute_reply":"2022-06-30T04:02:48.276063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Apply to test set","metadata":{}},{"cell_type":"code","source":"df_test = pd.read_csv(\"./processed_test.csv\", sep = '\\t')","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:48.280397Z","iopub.execute_input":"2022-06-30T04:02:48.2808Z","iopub.status.idle":"2022-06-30T04:02:51.396738Z","shell.execute_reply.started":"2022-06-30T04:02:48.280762Z","shell.execute_reply":"2022-06-30T04:02:51.395272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_pred = df_test[df_test['processed_summary'].isin(high_key)]","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:51.403515Z","iopub.execute_input":"2022-06-30T04:02:51.40391Z","iopub.status.idle":"2022-06-30T04:02:51.469672Z","shell.execute_reply.started":"2022-06-30T04:02:51.403879Z","shell.execute_reply":"2022-06-30T04:02:51.468518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_pred['predicted_rating'] = df_test_pred['processed_summary'].apply(predicted_rate)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:51.471252Z","iopub.execute_input":"2022-06-30T04:02:51.471597Z","iopub.status.idle":"2022-06-30T04:02:51.672291Z","shell.execute_reply.started":"2022-06-30T04:02:51.471568Z","shell.execute_reply":"2022-06-30T04:02:51.671334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_pred['id'] = df_test_pred.index+1","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:51.673682Z","iopub.execute_input":"2022-06-30T04:02:51.674021Z","iopub.status.idle":"2022-06-30T04:02:51.680474Z","shell.execute_reply.started":"2022-06-30T04:02:51.673991Z","shell.execute_reply":"2022-06-30T04:02:51.679609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_pred.to_csv(\"./predicted_data_with_keywords_.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:51.681677Z","iopub.execute_input":"2022-06-30T04:02:51.681996Z","iopub.status.idle":"2022-06-30T04:02:53.223616Z","shell.execute_reply.started":"2022-06-30T04:02:51.681966Z","shell.execute_reply":"2022-06-30T04:02:53.222611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_remain = df_test[~df_test.index.isin(df_test_pred.index)]\ndf_test_remain['id']  = df_test_remain.index+1","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:53.22502Z","iopub.execute_input":"2022-06-30T04:02:53.225515Z","iopub.status.idle":"2022-06-30T04:02:53.270252Z","shell.execute_reply.started":"2022-06-30T04:02:53.225476Z","shell.execute_reply":"2022-06-30T04:02:53.26923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_remain.to_csv(\"./processed_test.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:53.271675Z","iopub.execute_input":"2022-06-30T04:02:53.272771Z","iopub.status.idle":"2022-06-30T04:02:58.969701Z","shell.execute_reply.started":"2022-06-30T04:02:53.272719Z","shell.execute_reply":"2022-06-30T04:02:58.968632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model\nUsing BiLSTM+BiGRU+Conv1D as the main architecture of the model. Because the limitation of resources so we can't use transformer model, the training time will be so long since the big number of reviews.\n\nThe model has two parts, a model for learning from summaries and a model for learning from summaries concatinating with reviews. We concat the output of the two models and go through some Fullyconnected and dropout layers before the output layer.\n\nWe don't use any pre-trained language model because the list of words in this dataset and the list of words in language model is not matched much. In addition, the overfitting problem in this dataset is really high so reducing the embedding size helps the model become simpler and less to be overfitting.\n\nThe model using 60% reviews left in training set to train the model and evaluate in validation set (10% in training data) before predict on 60% reviews left in the testing set.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport re\nimport numpy as np\nfrom keras.models import Input\nfrom keras.layers import Dense, Dropout, Concatenate, BatchNormalization\nfrom keras.layers import LSTM, Embedding, Bidirectional, GRU\nfrom keras.layers import SpatialDropout1D, Conv1D, GlobalAveragePooling1D, GlobalMaxPooling1D\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.initializers import Constant\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.losses import BinaryCrossentropy, CategoricalCrossentropy\nimport pickle\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn.metrics import classification_report\nimport collections\nfrom sklearn.utils.class_weight import compute_class_weight\n\nimport seaborn as sns\nfrom tensorflow.keras import regularizers","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:02:58.971357Z","iopub.execute_input":"2022-06-30T04:02:58.971866Z","iopub.status.idle":"2022-06-30T04:03:00.651974Z","shell.execute_reply.started":"2022-06-30T04:02:58.971817Z","shell.execute_reply":"2022-06-30T04:03:00.650757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"./splited_train.csv\")\ndf_val = pd.read_csv(\"./splited_val.csv\")\ndf_test = pd.read_csv(\"./processed_test.csv\")\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:03:00.653455Z","iopub.execute_input":"2022-06-30T04:03:00.653874Z","iopub.status.idle":"2022-06-30T04:03:11.596223Z","shell.execute_reply.started":"2022-06-30T04:03:00.653833Z","shell.execute_reply":"2022-06-30T04:03:11.594653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cmt_train = df_train['summary_review'].astype('str').values\ncmt_val = df_val['summary_review'].astype('str').values\ncmt_test = df_test['summary_review'].astype('str').values","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:03:11.597832Z","iopub.execute_input":"2022-06-30T04:03:11.598992Z","iopub.status.idle":"2022-06-30T04:03:11.661266Z","shell.execute_reply.started":"2022-06-30T04:03:11.598937Z","shell.execute_reply":"2022-06-30T04:03:11.660159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sum_train = df_train['processed_summary'].astype('str').values\nsum_val = df_val['processed_summary'].astype('str').values\nsum_test = df_test['processed_summary'].astype('str').values","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:03:11.66326Z","iopub.execute_input":"2022-06-30T04:03:11.663709Z","iopub.status.idle":"2022-06-30T04:03:11.698314Z","shell.execute_reply.started":"2022-06-30T04:03:11.663671Z","shell.execute_reply":"2022-06-30T04:03:11.697219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntok = Tokenizer(filters='')\ntok.fit_on_texts(cmt_train)\nprint(len(tok.word_index)+1)\ntok.fit_on_texts(cmt_val)\nprint(len(tok.word_index)+1)\ntok.fit_on_texts(cmt_test)\nprint(len(tok.word_index)+1)\nvocab_size = len(tok.word_index)+1\n\ntokenized_train = tok.texts_to_sequences(cmt_train)\ntokenized_val = tok.texts_to_sequences(cmt_val)\ntokenized_test = tok.texts_to_sequences(cmt_test)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:03:11.700592Z","iopub.execute_input":"2022-06-30T04:03:11.701435Z","iopub.status.idle":"2022-06-30T04:04:14.81432Z","shell.execute_reply.started":"2022-06-30T04:03:11.701301Z","shell.execute_reply":"2022-06-30T04:04:14.813316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_len = 200\n\npadded_train = pad_sequences(tokenized_train, padding = 'post', maxlen = max_len)\npadded_val = pad_sequences(tokenized_val, padding = 'post', maxlen = max_len)\npadded_test = pad_sequences(tokenized_test, padding = 'post', maxlen = max_len)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:14.816001Z","iopub.execute_input":"2022-06-30T04:04:14.816597Z","iopub.status.idle":"2022-06-30T04:04:21.224696Z","shell.execute_reply.started":"2022-06-30T04:04:14.816561Z","shell.execute_reply":"2022-06-30T04:04:21.22374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntok_sum = Tokenizer(filters='')\ntok_sum.fit_on_texts(sum_train)\ntok_sum.fit_on_texts(sum_val)\ntok_sum.fit_on_texts(sum_test)\nvocab_size_sum = len(tok_sum.word_index)+1\n\ntokenized_train_sum = tok_sum.texts_to_sequences(sum_train)\ntokenized_val_sum = tok_sum.texts_to_sequences(sum_val)\ntokenized_test_sum = tok_sum.texts_to_sequences(sum_test)\n\nmax_len_sum = 50\n\n\npadded_train_sum = pad_sequences(tokenized_train_sum, padding = 'post', maxlen = max_len_sum)\npadded_val_sum = pad_sequences(tokenized_val_sum, padding = 'post', maxlen = max_len_sum)\npadded_test_sum = pad_sequences(tokenized_test_sum, padding = 'post', maxlen = max_len_sum)\npadded_train","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:21.226231Z","iopub.execute_input":"2022-06-30T04:04:21.226797Z","iopub.status.idle":"2022-06-30T04:04:38.910441Z","shell.execute_reply.started":"2022-06-30T04:04:21.226763Z","shell.execute_reply":"2022-06-30T04:04:38.909471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nvocab_size = len(tok.word_index)+1\nembedding_dim = 100\n\nmax_len=padded_train.shape[1]\n\n\n# Summary model\ninput_sum = Input(shape=(max_len_sum,))\nembed_sum = Embedding(input_dim=vocab_size_sum,\n                output_dim=embedding_dim,\n                input_length=max_len_sum,\n                trainable=True)(input_sum)\nlstm_sum = Bidirectional(LSTM(units = 64, activation = 'tanh',\n                return_sequences = True))(embed_sum)\nconv_sum = Conv1D( 64, kernel_size = 4, padding = \"valid\", kernel_initializer = \"he_uniform\")(lstm_sum)\n\navg_pool1 = GlobalAveragePooling1D()(conv_sum)\nmax_pool1 = GlobalMaxPooling1D()(conv_sum)\nconcat = Concatenate(axis=-1)([ avg_pool1, max_pool1])\ndense_sum = Dense(units = 32, activation = 'tanh')(concat)\ndroupout_sum = Dropout(rate = 0.5)(dense_sum)\n\n\n# Comment model\ninput = Input(shape=(max_len,))\nembed = Embedding(input_dim=vocab_size,\n                output_dim=embedding_dim,\n                input_length=max_len,\n                trainable=True)(input)\n\n\nlstm = Bidirectional(LSTM(units = 128, activation = 'tanh',\n                          return_sequences = True))(embed)\nlstm = Bidirectional(GRU(units = 64, activation = 'tanh',\n                          return_sequences = True))(lstm)\nconv_lstm = Conv1D( 128, kernel_size = 4, padding = \"valid\", kernel_initializer = \"he_uniform\")(lstm)\n\n\navg_pool1 = GlobalAveragePooling1D()(conv_lstm)\nmax_pool1 = GlobalMaxPooling1D()(conv_lstm)\n   \n    \nconcat = Concatenate(axis=-1)([ avg_pool1, max_pool1])\ndense4 = Dense(units = 64, activation = 'relu')(concat)\n\nconcat = Concatenate(axis=-1)([dense4, droupout_sum])\n\n\nout_put = Dense(units = 1, activation = 'linear', name = 'out_sentiment')(concat)\n\nmodel = tf.keras.Model(inputs = [input, input_sum], outputs = out_put)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:38.911828Z","iopub.execute_input":"2022-06-30T04:04:38.912195Z","iopub.status.idle":"2022-06-30T04:04:41.093153Z","shell.execute_reply.started":"2022-06-30T04:04:38.912163Z","shell.execute_reply":"2022-06-30T04:04:41.091978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"losses = 'mse'\nmodel.compile(optimizer=Adam(learning_rate = 0.001), loss=losses, metrics=['mae'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.094476Z","iopub.execute_input":"2022-06-30T04:04:41.094821Z","iopub.status.idle":"2022-06-30T04:04:41.120801Z","shell.execute_reply.started":"2022-06-30T04:04:41.09479Z","shell.execute_reply":"2022-06-30T04:04:41.119913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.122279Z","iopub.execute_input":"2022-06-30T04:04:41.122831Z","iopub.status.idle":"2022-06-30T04:04:41.127345Z","shell.execute_reply.started":"2022-06-30T04:04:41.122797Z","shell.execute_reply":"2022-06-30T04:04:41.126412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit model\n# We train the model in Colab and it costs a lot of time so we dont want to train it in Kaggle here, so we skip this stage and load the predicted result from previous training to submit.\n# history = model.fit(x=[padded_train, padded_train_sum],\n#                     y=df_train.rating.values,\n#                     validation_data=([padded_val, padded_val_sum],df_val.rating.values),\n#                     batch_size = 128,\n#                     callbacks = [callback],\n#                     epochs=10,\n#                     verbose=1)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.128629Z","iopub.execute_input":"2022-06-30T04:04:41.12937Z","iopub.status.idle":"2022-06-30T04:04:41.139259Z","shell.execute_reply.started":"2022-06-30T04:04:41.129332Z","shell.execute_reply":"2022-06-30T04:04:41.138349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_test = pd.read_csv(\"../input/predicted-sentiment-from-model-competion/predicted_sentiment_from_model.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.141479Z","iopub.execute_input":"2022-06-30T04:04:41.141994Z","iopub.status.idle":"2022-06-30T04:04:41.243899Z","shell.execute_reply.started":"2022-06-30T04:04:41.141948Z","shell.execute_reply":"2022-06-30T04:04:41.243075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_predicted = pd.read_csv(\"./predicted_data_with_keywords_.csv\")\ndf_predicted.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.245368Z","iopub.execute_input":"2022-06-30T04:04:41.246252Z","iopub.status.idle":"2022-06-30T04:04:41.907836Z","shell.execute_reply.started":"2022-06-30T04:04:41.246215Z","shell.execute_reply":"2022-06-30T04:04:41.907109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_predicted = df_predicted[['id', 'predicted_rating']]\ndf_predicted.columns = ['id', 'rating']","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.909563Z","iopub.execute_input":"2022-06-30T04:04:41.910322Z","iopub.status.idle":"2022-06-30T04:04:41.93767Z","shell.execute_reply.started":"2022-06-30T04:04:41.910274Z","shell.execute_reply":"2022-06-30T04:04:41.936892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submit = pd.concat([df_predicted, pred_test])\ndf_submit.sort_values(['id'])","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.93919Z","iopub.execute_input":"2022-06-30T04:04:41.940376Z","iopub.status.idle":"2022-06-30T04:04:41.983593Z","shell.execute_reply.started":"2022-06-30T04:04:41.940333Z","shell.execute_reply":"2022-06-30T04:04:41.982452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submit.sort_values(['id']).to_csv(\"./submission.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-06-30T04:04:41.984821Z","iopub.execute_input":"2022-06-30T04:04:41.985181Z","iopub.status.idle":"2022-06-30T04:04:42.710895Z","shell.execute_reply.started":"2022-06-30T04:04:41.985149Z","shell.execute_reply":"2022-06-30T04:04:42.709815Z"},"trusted":true},"execution_count":null,"outputs":[]}]}