{"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":"import pandas as pd\nimport numpy as np\nimport eli5\nimport matplotlib.pylab as plt\n#загрузка дополнительных данных для nltk\nimport nltk\n#nltk.download('punkt')\n#nltk.download('stopwords')\n#nltk.download('wordnet')\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk.corpus import stopwords\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score, classification_report, f1_score\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom nltk.stem import SnowballStemmer, WordNetLemmatizer, LancasterStemmer\nfrom functools import lru_cache\n\ndf = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/train.csv')\ntest = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vectorizer = TfidfVectorizer()\nsklearn_tokenizer = vectorizer.build_tokenizer()\n\nLEMMATIZER = WordNetLemmatizer()\n\n@lru_cache(maxsize=2048)\ndef lemmatize_word(word):\n    parts = ['a','v','n','r']\n    for part in parts:\n        temp = LEMMATIZER.lemmatize(word, part)\n        if temp != word:\n            return temp\n    return word    \n\ndef lemm_question(question):\n    return list(lemmatize_word(w.lower()) for w in sklearn_tokenizer(question))\n\nstemmer = SnowballStemmer('english')\n\ndef stem_question(question):\n    return list(stemmer.stem(w) for w in sklearn_tokenizer(question))\n\ndf['stem'] = df.apply (lambda row: \" \".join(stem_question(row.question_text)),axis=1)\ntest['stem'] = test.apply (lambda row: \" \".join(stem_question(row.question_text)),axis=1)\ndf['lemm'] = df.apply (lambda row: \" \".join(lemm_question(row.question_text)),axis=1)\ntest['lemm'] = test.apply (lambda row: \" \".join(lemm_question(row.question_text)),axis=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#EMBEDDING_FILE = '/kaggle/input/quora-insincere-questions-classification/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\n#w2v = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)\n#w2v = KeyedVectors.load_word2vec_format(imgdata, binary=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stops=stopwords.words('english')\nvec = TfidfVectorizer(stop_words = stops)\nclf = SGDClassifier(loss='modified_huber',class_weight={0:1,1:11})\nmodel1 = Pipeline([('vec', vec),('clf', clf)])\nmodel1.fit(df.stem.values, df.target.values)\npreds1 = model1.predict_proba(test.stem.values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stops=stopwords.words('english')\nvec = TfidfVectorizer(stop_words = stops)\nclf = SGDClassifier(loss='modified_huber',class_weight={0:1,1:9})\nmodel2 = Pipeline([('vec', vec),('clf', clf)])\nmodel2.fit(df.question_text.values, df.target.values)\npreds2 = model2.predict_proba(test.question_text.values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#stops=stopwords.words('english')\nvec = TfidfVectorizer()\nclf = SGDClassifier(loss='log',class_weight={0:1,1:11})\nmodel3 = Pipeline([('vec', vec),('clf', clf)])\nmodel3.fit(df.lemm.values, df.target.values)\npreds3 = model3.predict_proba(test.lemm.values)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = (preds1[:,1]+preds2[:,1]+preds3[:,1])/3\n\n# можно поискать идеальную границу, но она тут всегда около 0.7, так что..\nmysub=pd.DataFrame({'qid':test.qid,'prediction':preds>=0.7})\nmysub['prediction']=mysub['prediction'].astype(np.int64)\nmysub.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}