{"cells":[{"metadata":{"trusted":true,"_uuid":"c597d73f8e760cae19d4359d3138f418063e3444"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"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\"))\ndata=pd.read_csv(\"../input/train.csv\")\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":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d0d225aeecf6484758855bb5f9b0ff4b4a63dd7e"},"cell_type":"code","source":"data.iloc[22]['question_text'] #iloc is information in that location","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"588139cbc09a3e52451e2289d193a1b06d2289b5"},"cell_type":"code","source":"##Bag of words\n#to find frequency of each word\n#prepositions like its, i and all will be ignored in wordcloud\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"08ccc51a4f737695221bb1e97539ed6c3069bfb3"},"cell_type":"code","source":"from wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\nwc= WordCloud().generate('i love india, i have its culture')\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6a2a9c2d8c7a4f0782562e4d1806ee0f08ad9e35"},"cell_type":"code","source":"#when we have multiple lines, we join and make it into one string \nx=['a','c','d','c','e']\n' '.join(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6827bf7c59acaf7bd2300310e3403db8d6c2374c"},"cell_type":"code","source":"questions_string=' '.join(data['question_text'])#here we are combining all the lines into a single string\n\nwc=WordCloud().generate(questions_string) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ded560202739ddac58289febf4303ca5b023e56a"},"cell_type":"code","source":"plt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7693da4b1de994b40f60f23b0d684a9e5ca65964"},"cell_type":"code","source":"insincere_questions=data[data['target']==1]\nwc=WordCloud().generate(' '.join(insincere_questions['question_text']))\nplt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"fb2315812eca254e6c38c6ca5b2ba27592472ba1"},"cell_type":"markdown","source":"**Text Cleaning/ Text Transformation**\n* 1.Convert all characters to lower case\n* 2.Apply regular expressions to retain only alphabets or numbers etc\n* 3.Remove commonly used words\n* 4.Apply stemming"},{"metadata":{"trusted":true,"_uuid":"992197642d6cabec041e2dc3a028f8516a663322"},"cell_type":"code","source":"#1.Convert all characters to lower case\ndocs=data['question_text'].str.lower()\n\n#2.Apply regular expressions to retain only alphabets\ndocs= docs.str.replace('[^a-z ]','') #except alphabets everything is replaced with space\ndocs.head()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c65a8b46b17cebdd9393dacba0d764a47cca6eb2"},"cell_type":"code","source":"#3. Remove commonly used words\n#which we will find through nltk library where 250 words are listed as commonly used words\n#for which we will import nltk library\n\nimport nltk\nstopwords=nltk.corpus.stopwords.words('english')\nstopwords","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"772b5ac558be9ff34d330e5e04915f07550953f0"},"cell_type":"code","source":"len(stopwords)# length of stopwords","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f39b841eb717c2a2ebd53e9827683ab6da95ad06"},"cell_type":"code","source":"#creating a user defined function\n#def remove_stopwords(text):\n#    words=nltk.word_tokenize(text)\n#    print(words)\n#    print('-------')\n\n# split sentence into words\n#go word by word using loop to check if it exist in stopwords, remove it else keep it\n#def remove_stopwords(text):\n#    words=nltk.word_tokenize(text)\n#    words=[word for word in words if word not in stopwords]\n#    print(words)\n#    print('-------')\n\ndef remove_stopwords(text):\n    words=nltk.word_tokenize(text)\n    words=[stemmer.stem(word) for word in words if word not in stopwords]\n    #print(words)\n    #print('-------')\n    return' '.join(words)\n#docs.head(2).apply(remove_stopwords)\ndocs_clean=docs.apply(remove_stopwords)\ndocs_clean.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1b0ed4a7b250337ce29213bb5a3eb6110e524f8a"},"cell_type":"markdown","source":"stemming is a process of identifying root words\nlike plays, playing, player-> root word will be play, suffixes like s, ing, er must be removed"},{"metadata":{"trusted":true,"_uuid":"b3272df262bca8bdf81ee50fb150323c4af6cda5"},"cell_type":"code","source":"#cresting stemmer\n#nltk has lot of stemmer in which porterstemmer is widely used\nstemmer= nltk.stem.PorterStemmer()\nstemmer.stem('plays')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"35abe2f0ce2e9f472a095c7ab2dcf1a974773eb2","trusted":true},"cell_type":"code","source":"#but sometimes it change the meaning as well for example organisation to orgaN, we have to use it samrtly\nstemmer.stem('organisation')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"510b2db4459bb8b99ba23849c10a9f3318b300dd"},"cell_type":"code","source":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"da9c7d44954e18b00a8ae397cae65ad6ba2565d9"},"cell_type":"code","source":"vectorizer= CountVectorizer()\ntrain, validate= train_test_split(docs_clean, test_size=0.3,random_state=100)\nvectorizer=CountVectorizer()\nvectorizer.fit(train)\ntrain_dtm=vectorizer.transform(train)\nvalidate_dtm=vectorizer.transform(validate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a3b02d2c3cf396d64954f16021fd0d9d4fdddd91"},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"62b134696aa7a15d21ef5a6376a01c825cd17034"},"cell_type":"code","source":"train_dtm #here we get Compressed Sparse Row format,914285 is number of rows in training dataset,\n          #143417 is number of distinct words\n          #which is created as column","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b6abe20acc4c4cb80a388ab5ddb00a6f9e66dfd4"},"cell_type":"markdown","source":"here 5628198 only contains values out of 914285x143417, rest of them contains only 0s"},{"metadata":{"trusted":true,"_uuid":"5f5f6fe4eb9b086a481a60ee26d4bf2a9e44fa02"},"cell_type":"code","source":"percentage_of_non_zero_values= 5628198 / (914285*143417)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a168db9f06505a79ad80acc574bbd9de1043722"},"cell_type":"code","source":"percentage_of_non_zero_values #which is less than 1 percent","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4d147fa43442cb1cf1ff28c720d55abb9ffea720"},"cell_type":"code","source":"#pd.DataFrame(train_dtm[:5].toarray()) #here we took only 1st 5 row\npd.DataFrame(train_dtm[:5].toarray(), columns=vectorizer.get_feature_names())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"02ffd7ce8c5fe852aa133e2538722d89679b5633"},"cell_type":"code","source":"train_x=train_dtm\nvalidate_x=validate_dtm\ntrain_y=data.loc[train.index]['target']\nvalidate_y=data.loc[validate.index]['target']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1d5e674b34863c36df0cb19766d768727d042b48"},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nmodel_rf= RandomForestClassifier(n_estimators=300, random_state=100)\nmodel_rf.fit(train_x,train_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"62156198da0e4e764c7c5a69aa2eaa70575f8ea0"},"cell_type":"code","source":"validate_pred_class=model_rf.predict(validate_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"057dc50bd2d4d38679898409bd080c139b9c035c"},"cell_type":"code","source":"from sklearn.metrics import accuracy_score, f1_score\nprint(accuracy_score, validate_pred_class)\nprint(fi_score(validate_y,validate_pred_class))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1fdc7f90520a9e2512281fc697003d5ad8c5cdfb"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4e638181a336a5353048ed964e074c6fc8525ba5"},"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}