{"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\"))\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":"fcda187f5532d8644bdd2783845aa76dbe9d0e3e"},"cell_type":"code","source":"data.iloc[22]['question_text'] #iloc is information in that location","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e374c49f47fa0d659b241a104683ba0bf17b1c8"},"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":"20711f48d3512248c69ec0ff11e81d245a185c6f"},"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":"f67a04b9219a1d62e61b8d4761b1acb7bea7d9b7"},"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":"9eb52b870a83ff562989b7b75f404581c363e6ff"},"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":"90759a15f922d38f0874048bd3175d8f2e1cda0b"},"cell_type":"code","source":"plt.imshow(wc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"23ccf7322fcb218569b5c43114915fe10165d906"},"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":"1b005f925c1ce50338aed4d9a5b783322174cb1c"},"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":"1cad0c70ea285ad78339404336c7d2ecba5c4020"},"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":"211c4f75ed4db53b8b92d2d892c33c20bf67b27f"},"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":"df2c56c06e8984bfe47bd9b4cf8b7013a2b531f7"},"cell_type":"code","source":"len(stopwords)# length of stopwords","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"547cb471eb5858167aeaad261a5af6cc557e19cd"},"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":"8047c83d2f6adcda6c3af2492f00ff2d4b751756"},"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":"15271350fdfb8cf4af410b80a84a35621edda14e"},"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":{"trusted":true,"_uuid":"fab255645ccd55ef8bcf40931f60bb848435409e"},"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":"ee843f090357f13614a43818dba94747dfc879c7"},"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":"5effed360586296cf7831c3b99e1f75fc61305cb"},"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":"9bcfe8218df41a07ecc6a7ad41ad65ec33cd113e"},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bcfccdcdc42cad437fcd0b0ee89057e43e703e19"},"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":"3c502fba3e0e664ebafa658f2970bba7a77a86ac"},"cell_type":"markdown","source":"here 5628198 only contains values out of 914285x143417, rest of them contains only 0s"},{"metadata":{"trusted":true,"_uuid":"28960c05c95f16ba1e66e2d0c359688fe0465bb0"},"cell_type":"code","source":"percentage_of_non_zero_values= 5628198 / (914285*143417)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3c17ddec138c77b3fa9d68fb37b72d3066626473"},"cell_type":"code","source":"percentage_of_non_zero_values #which is less than 1 percent","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e2aa953019e7413d9ee08b26a387be97d3a12037"},"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":"da92a3f8790ef287c032e1cb7d68416f82429b35"},"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":"1c04946e861731991f08028d746b6d9dae9c8a57"},"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":"9a0c6ed70fc43605ac6693b4e6b017e050cbdab1"},"cell_type":"code","source":"validate_pred_class=model_rf.predict(validate_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e87942ee865b9bd085c26b2b57779c68fe15efc2"},"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":"ffba76b9f0f3609dc56c93041239e0970da7c97c"},"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}