{"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)\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport re\nfrom nltk.corpus import stopwords\nfrom tqdm import tqdm\nfrom wordcloud import WordCloud, STOPWORDS\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import roc_auc_score \nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\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\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":"train=pd.read_csv('../input/train.csv')\ntest=pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"da50649e5d3ccaa03bbf781a282785aed67aae35"},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ff3de6f7ee7b5beaaa95f61cf0bd7c131442e8cb"},"cell_type":"code","source":"train.question_text[9]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2c58f33a9bdb4a0bf95092d358e07e9b2c72d488"},"cell_type":"code","source":"train.target.value_counts().plot(kind='bar')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"88cc3036a10ce2e94d50abc20f2adc900d32a2e5"},"cell_type":"code","source":"def clean_text(text, remove_stopwords = False):\n    text = text.lower()\n    text = text.strip().replace(\"\\n\", \" \").replace(\"\\r\", \" \") ## remove new line chars\n    text = re.sub(r'[_\"\\-;%()|+&=*%.,!?:#$@\\[\\]/]', ' ', text)  ## remove unwanted chars\n    text = re.sub(r'\\'', ' ', text)\n    text = re.sub('[\\d+]', '', text) ## remove numerics\n    text=  re.sub(\"\\s\\s+\", \" \", text)  ## remove white spaces\n    \n    # Optionally, remove stop words\n    if remove_stopwords:\n        text = text.split()\n        stops = set(stopwords.words(\"english\"))\n        text = [w for w in text if not w in stops]\n        text = \" \".join(text)\n\n    return text","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1848780f697e79767ac0bb6e12d77ff7f7d23d7e"},"cell_type":"code","source":"clean_question=[]\nfor text in tqdm(train.question_text):\n    textt=clean_text(text,remove_stopwords = True)\n    clean_question.append(textt)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6161c9dd5708c601322eb8f97635e79f5811415d"},"cell_type":"code","source":"train['clean_question']=clean_question","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ac4c298a3a5951221f40205c1e7cbfb0ff6348d8"},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c055aaa3cda216b7ff3db0fca944fba7a0b2f17"},"cell_type":"code","source":"sincere = train[train.target==0][\"clean_question\"]\ninsincere = train[train.target==1][\"clean_question\"]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"acf8261ac6f3e4b88fb316937c337a7c497a8c3a"},"cell_type":"code","source":"wordcloud = WordCloud(\n                          background_color='white',\n                          stopwords=STOPWORDS,\n                          max_words=50000,\n                          max_font_size=30, \n                          random_state=42\n                         ).generate(str(sincere))\n\nprint(wordcloud)\nplt.figure(figsize=(16,13))\n\nfig = plt.figure(1)\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\n#fig.savefig(\"word1.png\", dpi=900)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f96605122e3e30d1466e2e9cd0418c9dff4fa3cc"},"cell_type":"code","source":"wordcloud = WordCloud(\n                          background_color='white',\n                          stopwords=STOPWORDS,\n                          max_words=50000,\n                          max_font_size=30, \n                          random_state=42\n                         ).generate(str(insincere))\n\nprint(wordcloud)\nplt.figure(figsize=(16,13))\n\nfig = plt.figure(1)\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\n#fig.savefig(\"word1.png\", dpi=900)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"840b827b15711ec67fa2126d201ef4b1791a94e9"},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(train['clean_question'], \n                                                    train['target'], \n                                                    random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dc4d95bdc5ae458bf68793a71f68117488455a1d"},"cell_type":"code","source":"tfvect=TfidfVectorizer(stop_words='english',min_df=3).fit(X_train)\nx_train_tfvect=tfvect.transform(X_train)\nx_test_tfvect=tfvect.transform(X_test)\nname=tfvect.get_feature_names()\nfeature_names = np.array(tfvect.get_feature_names())\nsorted_tfidf_index = x_train_tfvect.max(0).toarray()[0].argsort()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3cac414cdbaccda5bcd314b78aa971de58121345"},"cell_type":"code","source":"print('Smallest tfidf:\\n{}\\n'.format(feature_names[sorted_tfidf_index[:10]]))\nprint('Largest tfidf: \\n{}'.format(feature_names[sorted_tfidf_index[:-100:-1]]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ca1a031776311474143a38649c0a754543f024c4"},"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dbc3bd9a60f65fda6745a5b4bb0b6e0f928f893e"},"cell_type":"code","source":"model=LogisticRegression(solver='sag')\nmodel.fit(x_train_tfvect,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fa65a8f082691cfd8abb012096369a2a42876229"},"cell_type":"code","source":"predicted= model.predict(x_test_tfvect)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b70918e1ac782049b198d6c7b3ea4f3d85f50ad6"},"cell_type":"code","source":"accuracy=accuracy_score(y_test, predicted)\n\nreport=classification_report(y_test, predicted)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aa71d95ecf010c3d347db04e87ee270e923d6561"},"cell_type":"code","source":"accuracy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9af81d0cc5b3a156bb11181c1f6dd231902e6753"},"cell_type":"code","source":"print(report)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5ce365c04d78d6cfecec7636f583e4decc2a4131"},"cell_type":"markdown","source":"# to be continued...."},{"metadata":{"trusted":true,"_uuid":"c73670c807670a8565fb8e2bf7fef75b0aebcb71"},"cell_type":"code","source":"clean_question_test=[]\nfor text in tqdm(test.question_text):\n    textt=clean_text(text,remove_stopwords = True)\n    clean_question_test.append(textt)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6da53f5b7f68add67de09a0ee11266643396972a"},"cell_type":"code","source":"x_testt_tfvect=tfvect.transform(clean_question_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c850bf5cef3ddffef0e5695c68338e105d01daa0"},"cell_type":"code","source":"test_pred=model.predict(x_testt_tfvect)\ntest_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"381f1c49124abb4ef41ad278f82afacd62f5eb12"},"cell_type":"code","source":"out_df = pd.DataFrame({\"qid\":test[\"qid\"].values})\nout_df['prediction'] = test_pred\nout_df.to_csv(\"submission.csv\", index=False)","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}