{"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)\nfrom gensim.models import KeyedVectors\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nimport nltk\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import AdaBoostClassifier\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')\ntest = pd.read_csv('../input/test.csv')\ndata['question_text'] = data['question_text'].str.lower().str.replace('[^a-z ]', '')\ntest['question_text'] = test['question_text'].str.lower().str.replace('[^a-z ]', '')\ntarget_zero_rows = data[data['target']==0]\ntarget_one_rows = data[data['target']==1]\n\ntarget_zero_random_rows = np.random.randint(1, target_zero_rows.shape[0], target_one_rows.shape[0]*2)\ndf1 = target_zero_rows.iloc[target_zero_random_rows]\n\ntrain, validate = train_test_split(data, test_size=0.3, random_state=100)\ntrain.shape\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8836c05fde33172138181b7753337cc3d6f42338"},"cell_type":"code","source":"df2 = pd.concat([df1, target_one_rows])\ntrain, validate = train_test_split(df2, test_size=0.3, random_state=100)\ntrain.shape, validate.shape\n\ndel data\ndel target_zero_rows\ndel target_one_rows\nmodel = KeyedVectors.load_word2vec_format('../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin', binary=True)\n#print (model.most_similar('desk'))\n\nuniq_words = set()\ntrain['question_text'].str.split(' ').apply(uniq_words.update)\nuniq_words = list(uniq_words)\nlen(uniq_words)\n\nstopwords = nltk.corpus.stopwords.words('english')\nwords = set(uniq_words) - set(stopwords)\nwords = list(words)\nlen(words)\n\nlist(uniq_words)[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"38099b9cb1b564af7a6bcbe252cdd5d6a7c94840"},"cell_type":"code","source":"wordvectors = {}\nfor word in uniq_words:\n    try:\n        wordvectors[word] = model[word]\n    except:\n        pass\nlen(wordvectors)\n\ndel model\nimport gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cfa0cc29713d71d3d51fadf2373fdbc1e6e2177f"},"cell_type":"code","source":"def sent_vectorizer(sent, model):\n    sent_vec =[]\n    numw = 0\n    for w in sent:\n        try:\n            if numw == 0:\n                sent_vec = model[w]\n            else:\n                sent_vec = np.add(sent_vec, model[w])\n            numw+=1\n        except:\n            pass\n    if len(sent_vec)==300:\n        return list(np.asarray(sent_vec) / numw)\n    else:\n        return np.zeros(300)\ntrain_embeddings = []\nfor question in train['question_text']:\n    train_embeddings.append(sent_vectorizer(question.split(' '), wordvectors))\n    \ntest_embeddings = []\nfor question in test['question_text']:\n    test_embeddings.append(sent_vectorizer(question.split(' '), wordvectors))\n\nvalidate_embeddings = []\nfor question in validate['question_text']:\n    validate_embeddings.append(sent_vectorizer(question.split(' '), wordvectors))\n    \nmin_l = 0\nfor i in train_embeddings:\n    if len(i)==0:\n        min_l = min_l + 1\nmin_l","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f6e067bc0ce3c1ed5b288958fc8c6d4a93d93625"},"cell_type":"code","source":"model = AdaBoostClassifier(n_estimators=800)\nmodel.fit(np.array(train_embeddings), train['target'])\n\npred = model.predict(validate_embeddings)\nfrom sklearn.metrics import accuracy_score, f1_score\nprint(accuracy_score(validate['target'], pred))\nprint(f1_score(validate['target'], pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2d701171c560d41520da9da934064af427cfef1b"},"cell_type":"code","source":"pred_test = model.predict(test_embeddings)\npredictions = pd.DataFrame({'qid': test['qid'],\n                            'prediction': pred_test})\npredictions.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f5edf732dc168b4bee9e6b5ba9c9a8b8caded319"},"cell_type":"code","source":"predictions['prediction'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"576b8ac0faebb9c794a2bcdcdcf944b704c2cdec"},"cell_type":"code","source":"predictions.to_csv('submission.csv', index=False)","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}