{"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 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_train=pd.read_csv('../input/predict-closed-questions-on-stack-overflow/train-sample.csv')\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_df,test_df=train_test_split(df_train,test_size=0.2)\nprint('Training data shape: {}'.format(train_df.shape))\nprint('Testing data shape: {}'.format(test_df.shape))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Exploratory Data Analysis"},{"metadata":{},"cell_type":"markdown","source":"## PostID"},{"metadata":{},"cell_type":"markdown","source":"This feature is the id of the query posted by the user. This feauture does not have any importance in making the prediction but it will be used later for submission we will save it."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_post_id=train_df.PostId\ntest_post_id=test_df.PostId","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## PostCreationDate\n\nThe post creation date is the date and time on which the query was posted by the user let us see if we could make something out of this."},{"metadata":{},"cell_type":"markdown","source":"As we have observed that it doesn't matter on the time the question is posted on its label thus we can just remove this column both from our train and test."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['PostCreationDate'],axis=1,inplace=True)\ntest_df.drop(['PostCreationDate'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head(2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## OwnerUserId"},{"metadata":{},"cell_type":"markdown","source":"This is the user id who posted the query. Let us check it"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['PostCount']=[1]*len(train_df['PostId'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.pivot_table(train_df,index='OwnerUserId',columns='OpenStatus',values='PostCount',aggfunc='sum')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.loc[train_df['OpenStatus']=='open','OwnerUserId'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We see that it does not matter on the OwnerUserId whether his question is going to be open or not as there are many user whose only one question remain open \nSo, we would be dropping this column"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['OwnerUserId'],axis=1,inplace=True)\ntest_df.drop(['OwnerUserId'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reputation at Post Created\n\nThis can be a important factor. Let's take a look at it"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['ReputationAtPostCreation'].min()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['ReputationAtPostCreation'].max()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Since the data range is such high let us scale it using MinMaxScaler"},{"metadata":{"trusted":true},"cell_type":"code","source":"minimum=df_train['ReputationAtPostCreation'].min()\nmaximum=df_train['ReputationAtPostCreation'].max()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['ReputationAtPostCreation']=(train_df['ReputationAtPostCreation']-minimum)/(maximum-minimum)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['ReputationAtPostCreation']=(test_df['ReputationAtPostCreation']-minimum)/(maximum-minimum)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## OwnerUndeletedAnswerCountAtPostTime "},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.OwnerUndeletedAnswerCountAtPostTime.value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This feature doesnot seem to be doing anything, we will be dropping it for now."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['OwnerUndeletedAnswerCountAtPostTime'],axis=1,inplace=True)\ntest_df.drop(['OwnerUndeletedAnswerCountAtPostTime'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## PostClosedDate"},{"metadata":{},"cell_type":"markdown","source":"Dropping this column as post closed date does not seem to be doing anything, so we would be dropping it "},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['PostClosedDate'],axis=1,inplace=True)\ntest_df.drop(['PostClosedDate'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Tag1"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tag1'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tag1'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can combine all the tags column into one this would help us in comparing the words which are used as tags and the words used in Title and Body."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tag1']=train_df['Tag1'].replace(np.nan,' ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tag2']=train_df['Tag2'].replace(np.nan,' ')\ntrain_df['Tag3']=train_df['Tag3'].replace(np.nan,' ')\ntrain_df['Tag4']=train_df['Tag4'].replace(np.nan,' ')\ntrain_df['Tag5']=train_df['Tag5'].replace(np.nan,' ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tag1']=test_df['Tag1'].replace(np.nan,' ')\ntest_df['Tag2']=test_df['Tag2'].replace(np.nan,' ')\ntest_df['Tag3']=test_df['Tag3'].replace(np.nan,' ')\ntest_df['Tag4']=test_df['Tag4'].replace(np.nan,' ')\ntest_df['Tag5']=test_df['Tag5'].replace(np.nan,' ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tag1']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tags']=train_df['Tag1']+' '+train_df['Tag2']+' '+train_df['Tag3']+' '+train_df['Tag4']+' '+train_df['Tag5']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tags']=test_df['Tag1']+' '+test_df['Tag2']+' '+test_df['Tag3']+' '+test_df['Tag4']+' '+test_df['Tag5']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tags']=train_df['Tags'].str.lower()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tags']=test_df['Tags'].str.lower()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tags']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tags']=train_df['Tags'].apply(lambda x:x.lstrip())\ntrain_df['Tags']=train_df['Tags'].apply(lambda x:x.rstrip())\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tags']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Tags']=test_df['Tags'].apply(lambda x:x.lstrip())\ntest_df['Tags']=test_df['Tags'].apply(lambda x:x.rstrip())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Dropping excess columns \ntrain_df.drop(['PostId','OwnerCreationDate','Tag1','Tag2','Tag3','Tag4','Tag5','PostCount'],axis=1,inplace=True)\ntest_df.drop(['PostId','OwnerCreationDate','Tag1','Tag2','Tag3','Tag4','Tag5'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train=train_df['OpenStatus']\ny_test=test_df['OpenStatus']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['ReputationAtPostCreation','OpenStatus'],axis=1,inplace=True)\ntest_df.drop(['ReputationAtPostCreation','OpenStatus'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train=y_train.map({'not a real question':0,\n  'not constructive':1,\n  'off topic':2,\n  'open':3,\n  'too localized':4})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test=y_test.map({'not a real question':0,\n  'not constructive':1,\n  'off topic':2,\n  'open':3,\n  'too localized':4})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Text']=train_df['Title']+' '+train_df['BodyMarkdown']+' '+train_df['Tags']\ntest_df['Text']=test_df['Title']+' '+test_df['BodyMarkdown']+' '+test_df['Tags']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['Title','BodyMarkdown','Tags'],axis=1,inplace=True)\ntest_df.drop(['Title','BodyMarkdown','Tags'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.reset_index(inplace=True)\ntest_df.reset_index(inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop(['index'],inplace=True,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.drop(['index'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Building the tensorflow model\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.text import Tokenizer\nmax_words=10000\ntokenizer=Tokenizer(max_words)\ntokenizer.fit_on_texts(train_df['Text'])\nsequence_train=tokenizer.texts_to_sequences(train_df['Text'])\nsequence_test=tokenizer.texts_to_sequences(test_df['Text'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"word_2_vec=tokenizer.word_index\nV=len(word_2_vec)\nprint('Dataset has {} number of independent tokens'.format(V))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.sequence import pad_sequences\ndata_train=pad_sequences(sequence_train)\ndata_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"T=data_train.shape[1]\ndata_test=pad_sequences(sequence_test,maxlen=T)\ndata_test.shape\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Input,Conv1D,MaxPooling1D,Dense,GlobalMaxPooling1D,Embedding\nfrom tensorflow.keras.models import Model\nD=20\ni=Input((T,))\nx=Embedding(V+1,D)(i)\nx=Conv1D(32,3,activation='relu')(x)\nx=MaxPooling1D(3)(x)\nx=Conv1D(64,3,activation='relu')(x)\nx=MaxPooling1D(3)(x)\nx=Conv1D(128,3,activation='relu')(x)\nx=GlobalMaxPooling1D()(x)\nx=Dense(5,activation='softmax')(x)\nmodel=Model(i,x)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\ncnn_senti=model.fit(data_train,y_train,validation_data=(data_test,y_test),batch_size=100,epochs=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.predict(data_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred=model.predict(data_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_final=np.argmax(y_pred,axis=1)\ny_pred_final","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Scoring"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,classification_report\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cm=confusion_matrix(y_test,y_pred_final)\nax=sns.heatmap(cm,cmap='Blues',annot=True,fmt=' ')\nax.set_title('Confusion Matrix')\nax.set_xlabel('Y Test')\nax.set_ylabel('Y Pred')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(classification_report(y_test,y_pred_final))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission=pd.DataFrame(test_post_id,columns=['PostId'])\ndf_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_post_id.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1=pd.DataFrame(y_pred,columns=[0,1,2,3,4])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1['PostId']=list(test_post_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"columns=['PostId',0,1,2,3,4]\ndf_submission_1=df_submission_1[columns]\ndf_submission_1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1['Sum']=df_submission_1[0]+df_submission_1[1]+df_submission_1[2]+df_submission_1[3]+df_submission_1[4]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission_1","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}