{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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 20GB 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":"## Performing Stopwords removal and other operations on the data available."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from spacy.lang.en.stop_words import STOP_WORDS\ndf = pd.read_csv('../input/quora-insincere-questions-classification/train.csv')\ndf[\"question_text\"] = df['question_text'].str.replace('[^\\w\\s]','')\ndf[\"question_text\"] = df['question_text'].str.replace('\\d+', '')\ndf[\"question_text\"] = df['question_text'].str.lower()\ndf['question_text'] = df['question_text'].apply(lambda x: ' '.join([item for item in x.split() if item not in STOP_WORDS]))\n\n\ndf_test = pd.read_csv(\"../input/quora-insincere-questions-classification/test.csv\")\ndf_test['question_text']=df_test['question_text'].str.replace('[^\\w\\s]','')\ndf_test[\"question_text\"] = df_test['question_text'].str.replace('\\d+', '')\ndf_test[\"question_text\"] = df_test['question_text'].str.lower()\ndf_test['question_text'] = df_test['question_text'].apply(lambda x: ' '.join([item for item in x.split() if item not in STOP_WORDS]))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Tried upsampling and downsampling. Both provided same result."},{"metadata":{"trusted":true},"cell_type":"code","source":"df_majority = df[df.target==0]\ndf_minority = df[df.target==1]\n\n# # Downsample majority class\n# df_majority_downsampled = resample(df_majority, \n#                                  replace=False,    # sample without replacement\n#                                  n_samples=80810,     # to match minority class\n#                                  random_state=173) # reproducible results\n# df_majority_downsampled.info()\n# df = pd.concat([df_majority_downsampled,df_minority])\n\n# Downsample majority class\ndf_majority_updampled = resample(df_minority, \n                                 replace=True,    # sample without replacement\n                                 n_samples=1225312,     # to match minority class\n                                 random_state=173) # reproducible results\ndf = pd.concat([df_majority_updampled,df_majority])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['target'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Used gensim to do stopwords removal again. \nThis is done because of the fact that the number of stopwords are less in nltk."},{"metadata":{"trusted":true},"cell_type":"code","source":"from gensim.parsing.preprocessing import remove_stopwords\n\ndf[\"question_text\"] = df[\"question_text\"].str.lower()\ndf_test['question_text'] = df_test['question_text'].str.lower()\n\ndf['question_text'] = df['question_text'].apply(remove_stopwords)\ndf_test['question_text'] = df_test['question_text'].apply(remove_stopwords)\n\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Tokenization"},{"metadata":{"trusted":true},"cell_type":"code","source":"from gensim.utils import simple_preprocess\n\n# Tokenize the text column to get the new column 'tokenized_text'\ndf['tokenized_text'] = [simple_preprocess(line, deacc=True) for line in df['question_text']] \ndf_test['tokenized_text'] = [simple_preprocess(line, deacc=True) for line in df_test['question_text']] \n\nprint(df['tokenized_text'].head(10))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Stemming the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from gensim.parsing.porter import PorterStemmer\nporter_stemmer = PorterStemmer()\n# Get the stemmed_tokens\n# df['stemmed_tokens'] = [porter_stemmer.stem(word) for word in df['question_text']]\n# df['stemmed_tokens'].head(10)\n\ndf['stemmed_tokens'] = [[porter_stemmer.stem(word) for word in tokens] for tokens in df['tokenized_text'] ]\ndf_test['stemmed_tokens'] = [[porter_stemmer.stem(word) for word in tokens] for tokens in df_test['tokenized_text'] ]\n\ndf['stemmed_tokens'].head(10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## TF-IDF Vectorizer"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nX = df['stemmed_tokens']\nX_TEST = df_test['stemmed_tokens']\ny = df['target']\n\nX_TFIDF = X.apply(lambda x : \" \".join(x))\nX_TEST_TFIDF = X_TEST.apply(lambda x : \" \".join(x))\n\nvectorizer = TfidfVectorizer()\nX_train_tfidf = vectorizer.fit_transform(X_TFIDF)\nX_test_tfidf = vectorizer.transform(X_TEST_TFIDF)\n\n\nX_train, X_test, y_train, y_test = train_test_split(X_train_tfidf,y, test_size=0.33,random_state=42)\nprint(X_train_tfidf.shape)\nprint(X_test_tfidf.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Implementing LinearSVC"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.svm import LinearSVC","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"clf = LinearSVC()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"clf.fit(X_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = clf.predict(X_test)\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(confusion_matrix(y_test,predictions))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(classification_report(y_test,predictions))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn import metrics\nmetrics.accuracy_score(y_test,predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_prediction = clf.predict(X_test_tfidf)\ntest_prediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_result = pd.DataFrame({'qid':df_test['qid'].to_numpy(), 'prediction':test_prediction})\ndf_result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_result.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":4}