{"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\")\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.head() #top 5 rows are displayed","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e08c1533bb3a6a355b31b40085ad52d1cf202e23"},"cell_type":"code","source":"data.iloc[22]['question_text'] ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f60dfa80b1389fda5f0da2bf18b2cc10e8dea29a"},"cell_type":"code","source":"#bag of words\n#to find the frequency of each word\n#prepositions like the,for,i,we,etc..will be ignored","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c1326604fc8690a797f3d5453fa19bb85fcd77d9"},"cell_type":"code","source":"from wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\nwc=WordCloud().generate('i love india.i love its culture')\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cabe4f61aee0c749557ae3c746e778a0c7bdd741"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"04d76e69a0dfe8548fdf133bc409c2f13576476a"},"cell_type":"code","source":"question_str=''.join(data['question_text'])\nwc=WordCloud().generate(question_str)\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"34885913f2ccbb3fe592a53cd986a5c81bd973d1"},"cell_type":"code","source":"insincere_data=data[data['target']==1]\nwc=WordCloud().generate(''.join(insincere_data['question_text']))\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"71f2e3bf558443004d65e841b74dc08c79da913d"},"cell_type":"markdown","source":"text Cleaning/ text tranformations\n\n * convert all characters to lower case\n * Apply regular expressions to retain only alphabete or numbers etc\n * Remove commonly used words\n * Apply stemming"},{"metadata":{"trusted":true,"_uuid":"976c2fae843db495a6247e189e73f51576f51dee"},"cell_type":"code","source":"#convert all the characters to lower case\n\ndocs=data['question_text'].str.lower()\n\n#Apply regular expressions to retain only alphabets\ndocs=docs.str.replace('[^a-z ]','')\ndocs.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9b3e938a953133d0e56322215dd7148b36c37164"},"cell_type":"code","source":"#Remove commonly used words\nimport nltk\nstopwords=nltk.corpus.stopwords.words('english')\nstopwords\nlen(stopwords)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e779a713413aba85f0072101a89ef147d61a0f89"},"cell_type":"code","source":"\ndef remove_stopwords(text):\n    words=nltk.word_tokenize(text)\n    stemmer=nltk.stem.PorterStemmer()\n    words=[stemmer.stem(word) for word in words if word not in stopwords]\n    return ' '.join(words)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ad11045a9535ef453de0796effbd92d6f96a4958"},"cell_type":"code","source":"docs_clean=docs.apply(remove_stopwords)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"59a877d53328abb25b4d5b1f03b456d35900444e"},"cell_type":"markdown","source":"# stemming is process of identifying the root word for example: if we have play,played,playind,plays everything must be identified as only play "},{"metadata":{"trusted":true,"_uuid":"f8ecf2de5eaed314f4432d2f03c08e11cb2ce0bf"},"cell_type":"code","source":"stemmer=nltk.stem.PorterStemmer()\nstemmer.stem('adopted')# but this can change a specific meaning by getting the root word \n# for example: if u put organization the root word will be organ ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"85ec1b64c09b03446937f482fd55be6b15467810"},"cell_type":"markdown","source":"##  now we have an unstructured data...hence we must convert it to a structured one "},{"metadata":{"trusted":true,"_uuid":"eaf21305523748dd094fea66e0e48ffaff377dec"},"cell_type":"markdown","source":"document term matrix\nwhere you will have documents in the rows place and terms in the cols place\n    *                        T1 T2 T3 T4......\n     *                   D1  0   1    3   4....\n      *                  D2  1   5    7   0\n       *                 D3  3 \n        *                D4  0\n* so here we can say thatin the Document1 we have 0 number of term T1"},{"metadata":{"trusted":true,"_uuid":"c7ecbad1eecfff8f52c547f6866729651e6b523a"},"cell_type":"code","source":"len(docs_clean)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d5f09dc0d6ddbe22fd6e7178aaeb7bf4d42e9c18"},"cell_type":"code","source":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\n\ntrain,validate=train_test_split(docs_clean,test_size=0.3,random_state=100)\n\nvector=CountVectorizer()\nvector.fit(train)\ntrain_dtm=vector.transform(train)#dtm(document term matrix)\nvalidate_dtm=vector.transform(validate)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a84632007ca54449cf21284c97e36aa68c22146"},"cell_type":"code","source":"train_dtm## here we will have 914285 rows and 143417 cols as terms","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8f35edbb107cafb9c2b8488c5586e5c11eeb6d79"},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e99a1b35267ea4dac45d015dd757993cd126e043"},"cell_type":"code","source":"perc_non_zero_values=5628198/(914285*143417)*100\n# we will use 5628198 as the no of words without zeros and dividing it by the whole rows and cols where the percent is also not equal to 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fab8cd5541ab0ea880f74bd6c9a8ec6ab758bd31"},"cell_type":"code","source":"a=pd.DataFrame(train_dtm[:5].toarray(),\n            columns=vector.get_feature_names())\n#a.columns.values[1623]#col name for adopt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c5fcd083839cc8a9da99b27ab3ca127bbd5d6871"},"cell_type":"code","source":"train_x=train_dtm\ntrain_y=data.loc[train.index]['target']\n\nvalidate_x=validate_dtm\nvalidate_y=data.loc[validate.index]['target']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8594a2f1db868a6949361581702e7b8aa0c5c21d"},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\n\nmodel_rf=RandomForestClassifier(n_estimators=300, random_state=100)\n\nmodel_rf.fit(train_x,train_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8950817578c1b9404375f5287cfc6f8dcebb4158"},"cell_type":"code","source":"validate_pred_rf=model_rf.predict(validate_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"49a4934e44ee09aa9ddfae7b471bb01f81a50062"},"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}