{"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 all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"########### Library Imports #################\nimport pandas as pd\nimport os\nimport numpy as np\nimport nltk\nfrom nltk.tokenize\timport\tword_tokenize  \nfrom nltk.corpus\timport\tstopwords\nfrom nltk import ngrams\nfrom collections import defaultdict\nimport time\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split,cross_val_score,cross_val_predict\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\n######################################################\n\n########## Inputs ###############################\n\npath = \"../input/quora-insincere-questions-classification/\"\nnum_of_max_values_to_per_ngram = 20 ## Display these many ngrams \nstopwords_list = stopwords.words('english')\nthresholds = [0.1,0.2,0.5,0.6,0.7,0.8] ####### These are thresholds at which predictions need to be generated\n####################################################\n\n\n################ Function Definitions ##########################\ndef generate_tokenized_sentence_without_stopwords(sentence):\n    \"\"\" Generates Tokenized Sentence removing stopwords \"\"\"\n    tokens = [w\tfor\tw in\tword_tokenize(sentence.lower()) if\tw.isalpha()]            \n    tokenized_sen =  [t for t in tokens if t not in stopwords_list]\n    return tokenized_sen\n\ndef ngram(sentence,ngram_len):\n    \"\"\" Return Ngram if ngram doesn't exist return empty list  \"\"\"\n    try:\n        return(list(ngrams(sentence,ngram_len)))\n    except RuntimeError:\n        return([])\n##################################################################\n\n\n\n\n\ntrain_df = pd.read_csv(os.path.join(path,'train.csv'))##,nrows=250) ## currently load only 25 que for development\ntest_df = pd.read_csv(os.path.join(path,'test.csv'))##,nrows=250) ## currently load only 25 que for development\n\n\n\ntrain_df['One_gram'] = train_df['question_text'].apply(lambda que: generate_tokenized_sentence_without_stopwords(que)) ### Get tokenized que\n#train_df = train_df[['qid','target','One_gram']]\n\n\ntrain_df['Two_gram'] = train_df['One_gram'].apply(lambda x: ngram(x,2))\ntrain_df['Three_gram'] = train_df['One_gram'].apply(lambda x: ngram(x,3))\n\n\nfreq_count_df = []\nfor target_val in [0,1] :\n    for ngram_val in ['One_gram','Two_gram','Three_gram']:\n        freq_dict = defaultdict(int)\n        for sentence in train_df[train_df['target']==target_val][ngram_val]:\n            for token in sentence:\n                freq_dict[token] += 1\n        freq_df = pd.DataFrame.from_dict(freq_dict, orient='index',columns=['Count']).reset_index()\n        freq_df= freq_df[['index','Count']].sort_values(by ='Count' ,ascending = False).head(num_of_max_values_to_per_ngram).reset_index(drop = True)\n        freq_df['target'] = target_val \n        freq_df['Ngram'] = ngram_val\n        freq_count_df.append(freq_df)\n\nfreq_count_df = pd.concat(freq_count_df)   \n\n\n\nsns.set(style=\"whitegrid\")\nf, axes = plt.subplots(3,2,figsize=(20,30))\n\nfor target_val in [0,1] :\n    row = 0\n    for ngram_val in ['One_gram','Two_gram','Three_gram']:\n        filtered_data = freq_count_df[(freq_count_df['target'] == target_val) & (freq_count_df['Ngram'] == ngram_val) ]\n        g = sns.barplot(x=\"Count\", y=\"index\", data=filtered_data,ax = axes[row,target_val])\n        axes[row,target_val].set_title(\"Target: %s   Ngram: %s\"%(target_val,ngram_val))\n        row +=1\n\nplt.savefig('Ngram.png')\n\n\n\n\n######################### Model Development ###############\n\nX_train = train_df['question_text']\nX_test  = test_df['question_text']\ny_train = train_df['target']\n\n\n\n############## Vectorize Input text ###############\ncount_vectorizer\t=\tCountVectorizer(stop_words='english')\ncount_train = count_vectorizer.fit_transform(X_train.values)\ncount_test = count_vectorizer.transform(X_test.values)\n\n############# Use Naive Bayes Classifier on Vectorized Input ###############\nnb_classifier = MultinomialNB()\nnb_classifier.fit(count_train,y_train)\ny_pred_prob = nb_classifier.predict_proba(count_test)[:,1]\nthresh  = 0.4 ## This value was obtained by running Cross validation offline\ny_pred = (y_pred_prob >= thresh).astype(int) ###### convert probabilities to 1 or 0 using thresholds\n\nout_df = pd.DataFrame(data={'qid':test_df['qid'].values,'prediction': y_pred})\nout_df.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}