{"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\ndata=pd.read_csv('../input/train.csv')\ndata.head()\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"data.shape\nfrom matplotlib import *\nimport matplotlib.pyplot as plt\n\nimport nltk\nimport wordcloud","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"afc66511ee2a926c6e041caf43d9684396c3bac6"},"cell_type":"code","source":"class_0=data[data['target']==0]\nclass_1=data[data['target']==1]\nwc=wordcloud.WordCloud().generate(' '.join(class_0['question_text']))\nplt.imshow(wc)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8fb3bac1b1aaed734fa3f1dd3c8178002a158d2f"},"cell_type":"code","source":"wc=wordcloud.WordCloud().generate(' '.join(class_1['question_text']))\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"703bdc3028544d0298c634e809ed095bef4d64c6"},"cell_type":"code","source":"nltk.corpus.stopwords.words('english')\nstop_words=nltk.corpus.stopwords.words('english')\njunk_words=[\"amp\",'rt','https','will']\nlen(stop_words)\nstop_words.extend(junk_words)\nlen(stop_words)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"70e72b17108659f4b42b403b2b63d46be57e2815"},"cell_type":"code","source":"## cleaning the data\ndocs=data['question_text'].str.lower()\ndocs.head()\ndocs=docs.str.replace('[^a-z #@]','') # retain all alphabets with #@\ndocs.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1fd301e7737a30413274d7fb9bfcbf02a2dd48ac"},"cell_type":"code","source":"stemmer=nltk.PorterStemmer()\ndef clean_text(row_text):\n    #print(type(row_text))\n    row_words=row_text.split(' ')\n    #print(row_words)\n    row_words= [stemmer.stem(word) for word in row_words if word not in stop_words]\n    #print(row_words)\n    #print('----')\n    return ' '.join(row_words)\n\ndocs_clean=docs.apply(lambda v: clean_text(v))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e0d27885d3619863e446ebbcbb4124013e1a1c17"},"cell_type":"code","source":"data[\"clean_one\"]=docs_clean\n\ndf=data[[\"clean_one\",\"target\"]]\n\nfeatures=df.clean_one\nlabel=df.target\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1e8c815f4aa623edabb3368d8e282f03c308a4c9"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(features, label, test_size=0.3, random_state=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f974c6e32cbd490c1eae3c65509c3cf2525b34c5"},"cell_type":"code","source":"docs = data['question_text'].fillna('').str.lower().str.replace('[^a-z ]','')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9ee85481443ce5a364cb03d863fa95c52bceb905"},"cell_type":"code","source":"stop_words=nltk.corpus.stopwords.words('english')\njunk_words=['will']\n\nstop_words.extend(junk_words)\nlen(stop_words)\nstemmer = nltk.PorterStemmer()\ndocs_clean = docs.apply(lambda x:' '.join([stemmer.stem(word) for word in x.split(' ') \\\n                        if word not in stop_words]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1aeb55a4455a1bdb00b9faa5fae49e554f2730d5"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain, validate = train_test_split(docs_clean,test_size=0.3, random_state=100)\ntrain_y= data.loc[train.index]['target']\nvalidate_y = data.loc[validate.index]['target']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b15ec0d0ea7ab0ccc906e5bbc32b1eb5639ece91"},"cell_type":"code","source":"train.shape, validate.shape, train_y.shape, validate_y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fc0dbcc70472d79956f626f17e2e3ba9f53a426b"},"cell_type":"code","source":"from sklearn.feature_extraction.text import CountVectorizer\ncv=CountVectorizer()\ncv.fit(train)\ntrain_x_sparse=cv.transform(train)\nvalidate_x_sparse=cv.transform(validate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"00bde499c63a91193ccf495310af66f06a8f9e6f"},"cell_type":"code","source":"from  sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\ndt_model = DecisionTreeClassifier(max_depth=20, random_state=100)\ndt_model.fit(train_x_sparse, train_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aead14d843acbf1604f48444ef338a57889c3e59"},"cell_type":"code","source":"pred_class = dt_model.predict(validate_x_sparse)\npred_probs = pd.DataFrame(dt_model.predict_proba(validate_x_sparse),\n                         columns=['Sincere','Insincere'])\nfrom sklearn.metrics import accuracy_score, f1_score, roc_curve, auc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"80d52be6b8cc6201cdb4f2e06c8f9ad7c9abe04d"},"cell_type":"code","source":"print(accuracy_score(validate_y, pred_class))\nprint(f1_score(validate_y, pred_class))\nfpr, tpr, thresholds = roc_curve(validate_y, pred_probs['Insincere'])\nauc_dt = auc(fpr, tpr)\nplt.plot(fpr, tpr)\nplt.legend(['Decision Tree - AUC: %.2f' % auc_dt])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"12451cdd521a41405b90c46bb7baa9428b81308b"},"cell_type":"code","source":"test=pd.read_csv('../input/test.csv')\ntest_docs=test['question_text'].fillna('').str.lower()\ntest_docs=test_docs.str.replace('[^a-z ]','')\n\ntest_docs_clean=test_docs.apply(lambda x: ' '.join([stemmer.stem(word) for word in x.split(' ') if word not in stop_words]))\ntest_docs_clean.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9f147e42395771566f629722df31bb3221216457"},"cell_type":"code","source":"test_x = cv.transform(test_docs_clean)\ntest_pred_class = dt_model.predict(test_x)\ntest_pred_class.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"83f9b5804c775bafafb20c56c8e2eb4d830bc857"},"cell_type":"code","source":"submission = pd.DataFrame({'qid': test['qid'],\n                          'prediction': test_pred_class})\nsubmission.to_csv('submission.csv', index = False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"37db3fb860019e05e91961b27efc5fa05e8972dc"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9d270972cb1c93b3e1d88b3cba6f3c1f64b576c8"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}