{"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":{"trusted":true},"cell_type":"code","source":"df=pd.read_csv('../input/predict-closed-questions-on-stack-overflow/train-sample.csv')\ndf.head()","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,test_size=0.2)","execution_count":null,"outputs":[]},{"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['Tag1']=train_df['Tag1'].replace(np.nan,' ')\ntrain_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,' ')\ntest_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['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']\n","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":"train_df['Tags']=train_df['Tags'].apply(lambda x:x.lstrip())\ntrain_df['Tags']=train_df['Tags'].apply(lambda x:x.rstrip())","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":"# Dropping excess columns \ntrain_df.drop(['PostId','OwnerCreationDate','Tag1','Tag2','Tag3','Tag4','Tag5'],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":"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})\ny_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['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)\ntrain_df.drop(['index'],inplace=True,axis=1)\ntest_df.drop(['index'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"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'])\nword_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","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)\ny_pred_final=np.argmax(y_pred,axis=1)\ny_pred_final","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,classification_report\nimport seaborn as sns\ncm=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":{"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}