{"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":"# 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)\nimport plotly.express as px\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.ensemble import RandomForestClassifier\n\n\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-07-19T11:00:47.478294Z","iopub.execute_input":"2022-07-19T11:00:47.478744Z","iopub.status.idle":"2022-07-19T11:00:51.083790Z","shell.execute_reply.started":"2022-07-19T11:00:47.478650Z","shell.execute_reply":"2022-07-19T11:00:51.082531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read the CSV Files","metadata":{}},{"cell_type":"code","source":"xtrain=pd.read_csv('/kaggle/input/nlp-getting-started/train.csv')\nxtest=pd.read_csv('/kaggle/input/nlp-getting-started/test.csv')\nsample=pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.086938Z","iopub.execute_input":"2022-07-19T11:00:51.087319Z","iopub.status.idle":"2022-07-19T11:00:51.170055Z","shell.execute_reply.started":"2022-07-19T11:00:51.087284Z","shell.execute_reply":"2022-07-19T11:00:51.169131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.171969Z","iopub.execute_input":"2022-07-19T11:00:51.172863Z","iopub.status.idle":"2022-07-19T11:00:51.197175Z","shell.execute_reply.started":"2022-07-19T11:00:51.172814Z","shell.execute_reply":"2022-07-19T11:00:51.196317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create a features dataset containing 'text' 'location' and 'keyword'","metadata":{}},{"cell_type":"code","source":"y=xtrain['target']\nids=xtest['id']\nxtrain.drop(['id','target'],inplace=True,axis=1)\nxtest.drop('id',inplace=True,axis=1)\nxtrain","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.201917Z","iopub.execute_input":"2022-07-19T11:00:51.202589Z","iopub.status.idle":"2022-07-19T11:00:51.233982Z","shell.execute_reply.started":"2022-07-19T11:00:51.202548Z","shell.execute_reply":"2022-07-19T11:00:51.232793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Check for null values and perform necessary imputations","metadata":{}},{"cell_type":"code","source":"xtrain.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.235893Z","iopub.execute_input":"2022-07-19T11:00:51.236759Z","iopub.status.idle":"2022-07-19T11:00:51.250234Z","shell.execute_reply.started":"2022-07-19T11:00:51.236709Z","shell.execute_reply":"2022-07-19T11:00:51.248899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Get the top 15 values and visualize their frequency\nFor Categorical values,we generally use Mode","metadata":{}},{"cell_type":"code","source":"top_locations=xtrain['location'].value_counts().index.to_list()[:15]\ntop_loc_df=xtrain[xtrain.location.isin(top_locations)]\ntop_loc_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.252183Z","iopub.execute_input":"2022-07-19T11:00:51.252671Z","iopub.status.idle":"2022-07-19T11:00:51.283605Z","shell.execute_reply.started":"2022-07-19T11:00:51.252627Z","shell.execute_reply":"2022-07-19T11:00:51.281364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"px.histogram(top_loc_df,x='location',color='location')","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:51.285326Z","iopub.execute_input":"2022-07-19T11:00:51.286455Z","iopub.status.idle":"2022-07-19T11:00:52.885116Z","shell.execute_reply.started":"2022-07-19T11:00:51.286404Z","shell.execute_reply":"2022-07-19T11:00:52.883867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain['location'].fillna(xtrain['location'].mode()[0],inplace=True)\nxtest['location'].fillna(xtrain['location'].mode()[0],inplace=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:52.886564Z","iopub.execute_input":"2022-07-19T11:00:52.887044Z","iopub.status.idle":"2022-07-19T11:00:52.904173Z","shell.execute_reply.started":"2022-07-19T11:00:52.887008Z","shell.execute_reply":"2022-07-19T11:00:52.903108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Same for the 'Keyword' column, here the frequency is almost same so we can use multiple values to perform imputation but as the missing count is too small, we will use single mode only","metadata":{}},{"cell_type":"code","source":"top_keywords=xtrain['keyword'].value_counts().index.to_list()[:15]\ntop_keywords_df=xtrain[xtrain.keyword.isin(top_keywords)]\ntop_keywords_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:52.905600Z","iopub.execute_input":"2022-07-19T11:00:52.906880Z","iopub.status.idle":"2022-07-19T11:00:52.929533Z","shell.execute_reply.started":"2022-07-19T11:00:52.906838Z","shell.execute_reply":"2022-07-19T11:00:52.927896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"px.histogram(top_keywords_df,x='keyword',color='keyword')","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:52.935438Z","iopub.execute_input":"2022-07-19T11:00:52.936311Z","iopub.status.idle":"2022-07-19T11:00:53.073646Z","shell.execute_reply.started":"2022-07-19T11:00:52.936249Z","shell.execute_reply":"2022-07-19T11:00:53.072353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain['keyword'].fillna(xtrain['keyword'].mode()[0],inplace=True)\nxtest['keyword'].fillna(xtrain['keyword'].mode()[0],inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.075634Z","iopub.execute_input":"2022-07-19T11:00:53.076087Z","iopub.status.idle":"2022-07-19T11:00:53.089787Z","shell.execute_reply.started":"2022-07-19T11:00:53.076043Z","shell.execute_reply":"2022-07-19T11:00:53.088688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Now our dataset is free of all missing values","metadata":{}},{"cell_type":"code","source":"xtrain.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.091429Z","iopub.execute_input":"2022-07-19T11:00:53.091954Z","iopub.status.idle":"2022-07-19T11:00:53.106787Z","shell.execute_reply.started":"2022-07-19T11:00:53.091905Z","shell.execute_reply":"2022-07-19T11:00:53.105424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Replacing unnecessary characters with blank space, helps in better tokenization","metadata":{}},{"cell_type":"code","source":"\nxtrain['text']=xtrain.text.str.replace('[^a-zA-Z0-9\\s#]', '',regex=True)\nxtrain['location']=xtrain.location.str.replace('[^a-zA-Z0-9\\s]', '',regex=True)\nxtrain['keyword']=xtrain.keyword.str.replace('[^a-zA-Z0-9\\s]', '',regex=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.108082Z","iopub.execute_input":"2022-07-19T11:00:53.108499Z","iopub.status.idle":"2022-07-19T11:00:53.185447Z","shell.execute_reply.started":"2022-07-19T11:00:53.108448Z","shell.execute_reply":"2022-07-19T11:00:53.184221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nxtest['text']=xtest.text.str.replace('[^a-zA-Z0-9\\s#]', '',regex=True)\nxtest['location']=xtest.location.str.replace('[^a-zA-Z0-9\\s]', '',regex=True)\nxtest['keyword']=xtest.keyword.str.replace('[^a-zA-Z0-9\\s]', '',regex=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.186989Z","iopub.execute_input":"2022-07-19T11:00:53.187318Z","iopub.status.idle":"2022-07-19T11:00:53.225941Z","shell.execute_reply.started":"2022-07-19T11:00:53.187289Z","shell.execute_reply":"2022-07-19T11:00:53.224578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Stripping location text again as there were a few blank space tokens","metadata":{}},{"cell_type":"code","source":"\nxtrain['location']=xtrain['location'].str.strip()\nxtest['location']=xtest['location'].str.strip()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.227519Z","iopub.execute_input":"2022-07-19T11:00:53.227895Z","iopub.status.idle":"2022-07-19T11:00:53.248799Z","shell.execute_reply.started":"2022-07-19T11:00:53.227863Z","shell.execute_reply":"2022-07-19T11:00:53.247387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain.text[0]","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.249941Z","iopub.execute_input":"2022-07-19T11:00:53.250304Z","iopub.status.idle":"2022-07-19T11:00:53.258508Z","shell.execute_reply.started":"2022-07-19T11:00:53.250271Z","shell.execute_reply":"2022-07-19T11:00:53.256907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## TFIDF provides the measure of occurence of a particular word whereas word_tokenize tokenizes a given sentence to a set of tokens","metadata":{}},{"cell_type":"code","source":"tfidf = TfidfVectorizer(tokenizer=word_tokenize, token_pattern=None)\n\n#For Train Set\ntrain_texts=tfidf.fit_transform(xtrain['text'])\ntrain_texts=pd.DataFrame(train_texts.toarray(),columns=tfidf.get_feature_names_out())\n\n#For Test Set\ntest_texts=tfidf.fit_transform(xtest['text'])\ntest_texts=pd.DataFrame(test_texts.toarray(),columns=tfidf.get_feature_names_out())\n\n#Left Join\ntrain_texts,test_texts=train_texts.align(test_texts,join='left',axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:00:53.259972Z","iopub.execute_input":"2022-07-19T11:00:53.260700Z","iopub.status.idle":"2022-07-19T11:01:00.086727Z","shell.execute_reply.started":"2022-07-19T11:00:53.260649Z","shell.execute_reply":"2022-07-19T11:01:00.085653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fill useless features with zero values because similar train set features are not observed in test set","metadata":{}},{"cell_type":"code","source":"test_texts.fillna(0,inplace=True)\ntest_texts.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:00.088566Z","iopub.execute_input":"2022-07-19T11:01:00.089001Z","iopub.status.idle":"2022-07-19T11:01:00.991188Z","shell.execute_reply.started":"2022-07-19T11:01:00.088958Z","shell.execute_reply":"2022-07-19T11:01:00.989891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## One Hot Encoding the location and keyword column to generate a new set of features","metadata":{}},{"cell_type":"code","source":"ohe_train_location=pd.get_dummies(xtrain['location'])\nohe_test_location=pd.get_dummies(xtest['location'])\ntrain_locations,test_locations=ohe_train_location.align(ohe_test_location, join='left', axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:00.992959Z","iopub.execute_input":"2022-07-19T11:01:00.993299Z","iopub.status.idle":"2022-07-19T11:01:01.209463Z","shell.execute_reply.started":"2022-07-19T11:01:00.993269Z","shell.execute_reply":"2022-07-19T11:01:01.208265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_locations.fillna(0,inplace=True)\ntest_locations.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:01.211098Z","iopub.execute_input":"2022-07-19T11:01:01.211460Z","iopub.status.idle":"2022-07-19T11:01:01.272775Z","shell.execute_reply.started":"2022-07-19T11:01:01.211427Z","shell.execute_reply":"2022-07-19T11:01:01.271611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ohe_train_keywords=pd.get_dummies(xtrain['keyword'])\nohe_test_keywords=pd.get_dummies(xtest['keyword'])\ntrain_keywords,test_keywords=ohe_train_location.align(ohe_test_location, join='left', axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:01.274159Z","iopub.execute_input":"2022-07-19T11:01:01.274495Z","iopub.status.idle":"2022-07-19T11:01:01.327049Z","shell.execute_reply.started":"2022-07-19T11:01:01.274448Z","shell.execute_reply":"2022-07-19T11:01:01.326033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_keywords.fillna(0,inplace=True)\ntest_keywords.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:01.328130Z","iopub.execute_input":"2022-07-19T11:01:01.328575Z","iopub.status.idle":"2022-07-19T11:01:01.391485Z","shell.execute_reply.started":"2022-07-19T11:01:01.328535Z","shell.execute_reply":"2022-07-19T11:01:01.390295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Building the Final DataFrame with all necessary features","metadata":{}},{"cell_type":"code","source":"final_train_df=pd.concat([train_texts,train_locations,train_keywords],axis=1)\nfinal_test_df=pd.concat([test_texts,test_locations,test_keywords],axis=1)\nfinal_train_df","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:01.393611Z","iopub.execute_input":"2022-07-19T11:01:01.394148Z","iopub.status.idle":"2022-07-19T11:01:02.652944Z","shell.execute_reply.started":"2022-07-19T11:01:01.394054Z","shell.execute_reply":"2022-07-19T11:01:02.651650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fitting the Data and calculating Cross validation score","metadata":{}},{"cell_type":"code","source":"\nmodel=RandomForestClassifier(n_jobs=-1,random_state=1)\nmodel.fit(final_train_df,y)\nscores = cross_val_score(model, final_train_df, y, cv=5)\nscores.mean()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:01:02.654450Z","iopub.execute_input":"2022-07-19T11:01:02.654833Z","iopub.status.idle":"2022-07-19T11:03:42.855755Z","shell.execute_reply.started":"2022-07-19T11:01:02.654787Z","shell.execute_reply":"2022-07-19T11:03:42.854131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Calculating F1 score","metadata":{}},{"cell_type":"code","source":"train_results=model.predict(final_train_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:03:42.857817Z","iopub.execute_input":"2022-07-19T11:03:42.858218Z","iopub.status.idle":"2022-07-19T11:03:44.804865Z","shell.execute_reply.started":"2022-07-19T11:03:42.858184Z","shell.execute_reply":"2022-07-19T11:03:44.802527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f1_train=f1_score(y,train_results)\nprint(f'F1 score on train set {f1_train}')","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:03:44.806591Z","iopub.execute_input":"2022-07-19T11:03:44.807057Z","iopub.status.idle":"2022-07-19T11:03:44.820217Z","shell.execute_reply.started":"2022-07-19T11:03:44.807015Z","shell.execute_reply":"2022-07-19T11:03:44.818995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_results=model.predict(final_test_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:03:44.822095Z","iopub.execute_input":"2022-07-19T11:03:44.822569Z","iopub.status.idle":"2022-07-19T11:03:46.344083Z","shell.execute_reply.started":"2022-07-19T11:03:44.822520Z","shell.execute_reply":"2022-07-19T11:03:46.342659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"\nresult_df=pd.DataFrame({'id':ids,'target':test_results})\nresult_df.to_csv('submission.csv',index=False)\nprint('File generated successfully ! ')\n","metadata":{"execution":{"iopub.status.busy":"2022-07-19T11:03:46.349635Z","iopub.execute_input":"2022-07-19T11:03:46.350270Z","iopub.status.idle":"2022-07-19T11:03:46.371438Z","shell.execute_reply.started":"2022-07-19T11:03:46.350231Z","shell.execute_reply":"2022-07-19T11:03:46.370238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}