{"cells":[{"metadata":{},"cell_type":"markdown","source":"# About the Problem Statement:\n\n**An insincere question is defined as a question intended to make a statement rather than look for helpful answers. Some characteristics that can signify that a question is insincere:**\n\n* Has a non-neutral tone\nHas an exaggerated tone to underscore a point about a group of people\nIs rhetorical and meant to imply a statement about a group of people\n* Is disparaging or inflammatory\nSuggests a discriminatory idea against a protected class of people, or seeks confirmation of a stereotype\nMakes disparaging attacks/insults against a specific person or group of people\nBased on an outlandish premise about a group of people\nDisparages against a characteristic that is not fixable and not measurable\n* Isn't grounded in reality\nBased on false information, or contains absurd assumptions\n* Uses sexual content (incest, bestiality, pedophilia) for shock value, and not to seek genuine answers\nThe training data includes the question that was asked, and whether it was identified as insincere (target = 1). The ground-truth labels contain some amount of noise: they are not guaranteed to be perfect.","execution_count":null},{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**The F1-Score I got from traditional classification models was very low(0.25). So tried implementing in tensorflow.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install texthero","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport texthero as hero\n\nimport matplotlib.pyplot as plt\nimport re\nimport matplotlib as mpl\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nmpl.rcParams['figure.dpi'] = 300","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/train.csv')\ntest= pd.read_csv('/kaggle/input/quora-insincere-questions-classification/test.csv')\n\ndisplay(train.sample(5))\ndisplay(train.info())\ndisplay(test.info())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"combined_df = pd.concat([train.drop('target',axis=1),test])\ncombined_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hero.visualization.wordcloud(combined_df['question_text'], max_words=1000,background_color='BLACK')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"combined_df['cleaned_text']=(combined_df['question_text'].pipe(hero.remove_angle_brackets)\n                    .pipe(hero.remove_brackets)\n                    .pipe(hero.remove_curly_brackets)\n                    .pipe(hero.remove_diacritics)\n                    .pipe(hero.remove_digits)\n                    .pipe(hero.remove_html_tags)\n                    .pipe(hero.remove_punctuation)\n                    .pipe(hero.remove_round_brackets)\n                    .pipe(hero.remove_square_brackets)\n                    .pipe(hero.remove_stopwords)\n                    .pipe(hero.remove_urls)\n                    .pipe(hero.remove_whitespace)\n                    .pipe(hero.lowercase))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lemm = WordNetLemmatizer()\n\ndef word_lemma(text):\n    words = nltk.word_tokenize(text)\n    lemma = [lemm.lemmatize(word) for word in words]\n    joined_text = \" \".join(lemma)\n    return joined_text","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"combined_df['lemmatized_text'] = combined_df.cleaned_text.apply(lambda x: word_lemma(x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,accuracy_score,classification_report,f1_score,plot_confusion_matrix\n\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.preprocessing.text import one_hot\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Bidirectional\nfrom tensorflow.keras.layers import Dropout","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"text = []\nfor i in range(len(combined_df)):\n    review = nltk.word_tokenize(combined_df['lemmatized_text'].iloc[i])\n    review = ' '.join(review)\n    text.append(review)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"voc_size = 5000\nonehot_repr=[one_hot(words,voc_size)for words in text] \n\nsent_length=50\nembedded_docs=pad_sequences(onehot_repr,padding='pre',maxlen=sent_length)\ndisplay(embedded_docs)\ndisplay(embedded_docs.shape)\n\nembedded_docs_train = embedded_docs[:1306122,:]\nembedded_docs_test = embedded_docs[1306122:,:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Creating model\nembedding_vector_features=150\nmodel1=Sequential()\nmodel1.add(Embedding(voc_size,embedding_vector_features,input_length=sent_length))\nmodel1.add(Bidirectional(LSTM(100)))\nmodel1.add(Dropout(0.3))\nmodel1.add(Dense(1,activation='sigmoid'))\nmodel1.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\nprint(model1.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_final=np.array(embedded_docs_train)\ny_final=np.array(train.target)\n\nX_train, X_test, y_train, y_test = train_test_split(X_final, y_final, test_size=0.2, random_state=42)\n\nmodel1.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=10,batch_size=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Prediction on test data\ny_pred1=model1.predict_classes(X_test)\nprint(classification_report(y_test,y_pred1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred2=model1.predict_classes(embedded_docs_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Final predictions and submission\nqid = test.qid\n\nsubmissions = pd.DataFrame({'qid':qid,'target':y_pred2.reshape(-1)})\nsubmissions.to_csv('./submission1.csv',index=False,header=True)","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":4}