{"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\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":"import pandas as pd\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"858913aa2628c44c0ca68e9fcf31792df68f48d0"},"cell_type":"code","source":"train = pd.read_csv('../input/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b71c84c98fa5233c2f8ab3a2dcb582a9ada1dd53"},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a89376fb0f57f19fd01d4abf3c53361d772372cc"},"cell_type":"code","source":"train['target'].value_counts() / train.shape[0] * 100  # imbalanced data","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7fcb8f47e456a4787da593e9f49dfed00141de73"},"cell_type":"markdown","source":"# bag of word analysis "},{"metadata":{"trusted":true,"_uuid":"427df252ecabe72ca35cba46daa55c8c0b5fe0cb"},"cell_type":"code","source":"from wordcloud import WordCloud\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"808b6949a3998e7454ec7881ac3ac38c3f8eec60"},"cell_type":"code","source":"wc = WordCloud().generate('i love india; i love bikes; i love apples')\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f2d84b015b9c78b71126952f945310404421a6aa"},"cell_type":"code","source":"wc = WordCloud().generate(' '.join(train['question_text']))\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d029dd725e1eee2268d2e66bc8b2ba6aa00a573f"},"cell_type":"code","source":"insincere_rows = train[train['target'] == 1 ]\n\nwc = WordCloud().generate(' '.join(insincere_rows['question_text']))\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9d090fd05eb91a342c1a0ceab3de99049bc7969a"},"cell_type":"markdown","source":"****text cleaning / text transformations "},{"metadata":{"trusted":true,"_uuid":"cb0970174a34f425aad153e847ffa49ab52369e8"},"cell_type":"code","source":"# convert all characters to lower case\n\ndocs = train['question_text'].str.lower()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"56c25593fcc2aa311a91bb9a16913eeaaa09fee4"},"cell_type":"code","source":"# apply regular expression to retain only alphabets and spaces\n\ndocs = docs.str.replace('[^a-z ]', '')\ndocs.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1d2b0d9b2c26c590ba09de8dbc94cda49cbb9fd8"},"cell_type":"code","source":"# remove commonly used words and apply stemming\n\nimport nltk\nstopwords = nltk.corpus.stopwords.words('english')\ncustom_stopwords = ['will']\nstopwords.extend(custom_stopwords)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2b1ed5d06860e29da57c9148c47ce39228f46c13"},"cell_type":"code","source":"len(stopwords)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"238751ec0aeb71d5cc1ed99582ab7fe09b9c46ff"},"cell_type":"code","source":"# stemming\n\nstemmer = nltk.stem.PorterStemmer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ee711735d43a933c290bfdcf31e37159b06a3590"},"cell_type":"code","source":"def clean_sentences(text):\n    words = text.split(' ')\n    clean_words = [stemmer.stem(word) for word in words if word not in stopwords]\n    return ' '.join(clean_words)\n\ndocs_clean = docs.apply(clean_sentences)\ndocs_clean.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"06be4aa8721c063776d44694d27dde5e5089c12f"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"408de173879e0d485030195df74724906a017df1"},"cell_type":"markdown","source":"# DOCUMENT TERM MATRIX"},{"metadata":{"trusted":true,"_uuid":"da1137e9d99a4753a0066b7b9fa78c21ed9c3824"},"cell_type":"code","source":"from sklearn.feature_extraction.text import CountVectorizer","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fb9095a47623f30c0386fb365e2d586d587fc21f"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_model , validate_model = train_test_split(docs_clean , test_size = 0.3 , random_state = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8f8d31159568403738f1760779eeffb29866d355"},"cell_type":"code","source":"vectorizer = CountVectorizer(min_df=50)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cdccf7fe015b7d25be013863684724530fd74a3b"},"cell_type":"code","source":"vectorizer.fit(train_model)\n\ntrain_dtm = vectorizer.transform(train_model)\nvalidate_dtm = vectorizer.transform(validate_model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f7cb7f4b40638f0f552790bba883faf70eeb9bb5"},"cell_type":"code","source":"train_dtm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a54140294042f145bdb9502116eaf98eb06a28cc"},"cell_type":"code","source":"train_model.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ffd6054406947f6f0d53d3e4067ef1621c55663f"},"cell_type":"code","source":"unique_terms = vectorizer.get_feature_names()\nlen(unique_terms)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"283aeab48a6dd091ef5cab1bc04dc2c2d4390da6"},"cell_type":"code","source":"unique_terms[:100]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2bbd32c443841f2c8a411e93bb2c20ca1f724af8"},"cell_type":"code","source":"df_dtm = pd.DataFrame(train_dtm[:10].toarray(),\n                     columns = vectorizer.get_feature_names())\ndf_dtm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b3ebe7e7167247a0d3a7af0d022c294a09ccc4af"},"cell_type":"code","source":"train_x = train_dtm\nvalidate_x = validate_dtm\n\ntrain_y = train.loc[train_model.index]['target']\nvalidate_y = train.loc[validate_model.index]['target']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1db3ffb91dd88258cc6ef8f65104cdd04bbb64e2"},"cell_type":"code","source":"from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score , f1_score , classification_report","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1d1493104b511f68519cec643f75a561379cdcc1"},"cell_type":"code","source":"model_dt = DecisionTreeClassifier(max_depth = 20)\nmodel_dt.fit(train_x , train_y)\nvalidate_pred = model_dt.predict(validate_x)\nprint(accuracy_score(validate_y,validate_pred))\nprint(f1_score(validate_y,validate_pred))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b483a2bc9ab2bce842228b996ba6b25d888eb7b3"},"cell_type":"markdown","source":"# perform same operations on test data "},{"metadata":{"trusted":true,"_uuid":"26bf17801dcf5d25f650c03885ef1a97e77ed628"},"cell_type":"code","source":"test = pd.read_csv('../input/test.csv')\ndocs_test = test['question_text'].str.lower()\ndocs_test = docs_test.str.replace('[^a-z ]','')\ndocs_test_clean = docs_test.apply(clean_sentences)\n\ntest_dtm = vectorizer.transform(docs_test_clean)\ntest_pred = model_dt.predict(test_dtm)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7a6493cbcbe8aa40699edeac1c07c5b71ddfc3d3"},"cell_type":"code","source":"submission = pd.DataFrame({ \n    'qid' : test['qid'],\n    'prediction' : test_pred})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5e7f5d5a25e5120fc52a8133ee278d844d3916fd"},"cell_type":"code","source":"submission.to_csv('submission.csv',index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a3b9218104a874fb69ab2a695f2392531c32c254"},"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.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}