{"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.\ndata=pd.read_csv(\"../input/train.csv\")\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"data.iloc[22]['question_text'] #iloc is information in that location","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d2fcf52b807e0f5116539fce3657fc6d3f012a30"},"cell_type":"markdown","source":"   Bag of words\n- to find frequency of each word\n- prepositions like its, i and all will be ignored in wordcloud\n"},{"metadata":{"trusted":true,"_uuid":"d7fd28c959d33bd39bc0df48f0825e0d13a09e0a"},"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":"667e29825e23188e5163de0ea1ab23313593310f"},"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":"50ca469f9290f4dc7c66ced6e77bfb7636c7d067"},"cell_type":"code","source":"questions_string=' '.join(data['question_text'])#here we are combining all the lines into a single string\nwc=WordCloud().generate(questions_string) \nplt.imshow(wc)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b0f76746733f0943a7de31c83b50ec37ba60d055"},"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":"d9c98fe1f3ae365e455142d2b2172abbbe39360f"},"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":"11f510f443b48461e2a6fb3699416732699af271"},"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#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\n\n\nlen(stopwords)# length of stopwords\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"45f36249ca1fd3fd3b845700bc74a76fe5b691ee"},"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":"f300a143ab1b46fbaac0d4fa83c3096f6e727d6e"},"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":"9cb64807632dea0cf06f360ef9f41f0d249dfc29"},"cell_type":"code","source":"\n#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":{"trusted":true,"_uuid":"8fda2cb4e3534435affe03eaff03b31ddb305607"},"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":"e8b27a680c1f1b7c97f37ad2ad2fb3674f7e11b7"},"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":"61d90a5b170bb0a3f96e1f248eb054f8d737a7f1"},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c00cf82604f66af59fbb9a730d9e93b87e96b92"},"cell_type":"code","source":"train_dtm=vectorizer.transform(train)\nvalidate_dtm=vectorizer.transform(validate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d5e3cef485b12260be53cf742563406096f70596"},"cell_type":"code","source":"train.shape\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"42749084e20cdb24f99dc97922c2a2ec4ee2a8f9"},"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\n\n#here 5628198 only contains values out of 914285x143417, rest of them contains only 0s","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c09f1e9508b9303ebe57e03d7a9582d54c367bd6"},"cell_type":"code","source":"percentage_of_non_zero_values= 5628198 / (914285*143417)*100\n\npercentage_of_non_zero_values #which is less than 1 percent","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7eea06a39d70c7f44b54caf53fbfa511498b11f7"},"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())\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"852e1c235018e0dad74d28506928406c7a51bc30"},"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']\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"df42e1d3acf9f1f1420683c9de31f7f60ee7f170"},"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)\n\nvalidate_pred_class=model_rf.predict(validate_x)","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}