{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","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":{},"cell_type":"markdown","source":"![alt text](https://i.redd.it/icok5mempnd21.jpg \"Logo Title Text 1\")"},{"metadata":{"trusted":true},"cell_type":"code","source":"import json\nimport plotly.express as px\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom nltk.tokenize import wordpunct_tokenize\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Посмотрим на train"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/dmia-dl-nlp-2019/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Главная и дополнительная категория представлены id\nУ нас есть файлы main_category_mapper.json и sub_category_mapper.json  \n### main_category_mapper.json\nСловарь, в котором ключ - это строковое представление главной категории, а значение - id главной категории\n### sub_category_mapper.json\nСловарь, в котором ключ - это строковое представление дополнительной категории, а значение - id дополнительной категории"},{"metadata":{"trusted":true},"cell_type":"code","source":"# читаем \nwith open('/kaggle/input/dmia-dl-nlp-2019/main_category_mapper.json') as f:\n    main_cat2id = json.load(f)\n    \n# инвертируем\nid2main_cat = {value: key for key, value in main_cat2id.items()}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id2main_cat","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# тоже самое с доп категориями\nwith open('/kaggle/input/dmia-dl-nlp-2019/sub_category_mapper.json') as f:\n    sub_cat2id = json.load(f)\n    \nid2sub_cat = {value: key for key, value in sub_cat2id.items()}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# переводим id в строку\ntrain.main_category = train.main_category.map(id2main_cat)\ntrain.sub_category = train.sub_category.map(id2sub_cat)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Теперь классы представлены строками"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Посмотрим на распределение классов"},{"metadata":{"trusted":true},"cell_type":"code","source":"val_counts_main = pd.DataFrame(train.main_category.value_counts())\nval_counts_main.reset_index(inplace=True)\nval_counts_main.columns = ['category', 'n_entries']\nfig = px.bar(val_counts_main, x='category', y='n_entries')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_counts_sub = pd.DataFrame(train.sub_category.value_counts())\nval_counts_sub.reset_index(inplace=True)\nval_counts_sub.columns = ['category', 'n_entries']\nfig = px.bar(val_counts_sub, x='category', y='n_entries')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Посмотрим на распределение длин в токенах и символах"},{"metadata":{"trusted":true},"cell_type":"code","source":"train['char_len'] = train.question.map(len)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['token_len'] = train.question.map(lambda x: len(wordpunct_tokenize(x)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16, 12))\nplt.title('Distplot question char len')\nsns.distplot(train.char_len)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16, 12))\nplt.title('Distplot question token len')\nsns.distplot(train.token_len)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Неразмеченные данные"},{"metadata":{"trusted":true},"cell_type":"code","source":"unsupervised = pd.read_csv('/kaggle/input/dmia-dl-nlp-2019/unsupervised.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unsupervised","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Попробуем построить простую модель"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import f1_score, confusion_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# переводим класс в индекс\ntrain['target'] = train.main_category.map(main_cat2id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_validation, y_train, y_validation = train_test_split(train.question, train.target, test_size=0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_validation.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"markdown","source":"# Векторизуем наши тексты\n\ntf-idf часто встречающийся в NLP метод векторизации предложений. Подробнее можно почитать здесь: https://ru.wikipedia.org/wiki/TF-IDF  \nМы берем его как бейзлайн, приятно будет знать про него, но не является критичным для этого задания. В нем много минусов, но безусловный плюс - простота."},{"metadata":{"trusted":true},"cell_type":"code","source":"# оставим только 75000 самых частых слов\n# каждое слово - фича\nvectorizer = TfidfVectorizer(max_features=75000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train_vectorized = vectorizer.fit_transform(x_train)\nx_validation_vectorized = vectorizer.transform(x_validation)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# у нас получилась разреженная матрица, потому что все 75 000 слов почти точно не встречаются в одном тексте\nx_train_vectorized","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = x_train_vectorized[0].toarray()[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# на каждый пример у нас вектор из 75000\nsample.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# и только на столько заполнен наш вектор\n(sample > 0).sum() * 100 / sample.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_reg = LogisticRegression(solver='lbfgs', multi_class='auto')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_reg.fit(x_train_vectorized, y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_train = log_reg.predict(x_train_vectorized)\npredicted_validation = log_reg.predict(x_validation_vectorized)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f1_train = f1_score(y_true=y_train, y_pred=predicted_train, average='micro')\nf1_test = f1_score(y_true=y_validation, y_pred=predicted_validation, average='micro')\n\nf'F1 train: {f1_train:.3f} | test: {f1_test:.3f}'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = [id2main_cat[n] for n in range(len(id2main_cat))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_confusion_matrix(y_true, y_pred, classes,\n                          normalize=True,\n                          title=None,\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if not title:\n        if normalize:\n            title = 'Normalized confusion matrix'\n        else:\n            title = 'Confusion matrix, without normalization'\n\n    # Compute confusion matrix\n    cm = confusion_matrix(y_true, y_pred)\n    # Only use the labels that appear in the data\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    fig, ax = plt.subplots(figsize=(18, 18))\n    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n    ax.figure.colorbar(im, ax=ax)\n    # We want to show all ticks...\n    ax.set(xticks=np.arange(cm.shape[1]),\n           yticks=np.arange(cm.shape[0]),\n           # ... and label them with the respective list entries\n           xticklabels=classes, yticklabels=classes,\n           title=title,\n           ylabel='True label',\n           xlabel='Predicted label')\n\n    # Rotate the tick labels and set their alignment.\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n             rotation_mode=\"anchor\")\n\n    # Loop over data dimensions and create text annotations.\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i in range(cm.shape[0]):\n        for j in range(cm.shape[1]):\n            ax.text(j, i, format(cm[i, j], fmt),\n                    ha=\"center\", va=\"center\",\n                    color=\"white\" if cm[i, j] > thresh else \"black\")\n    fig.tight_layout()\n    return ax","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_confusion_matrix(y_validation, predicted_validation, classes)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"![alt text](https://i.kym-cdn.com/entries/icons/mobile/000/002/456/tearingmeapartlisa.jpg \"Logo Title Text 1\")"},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/dmia-dl-nlp-2019/test.csv')\nsample_submission = pd.read_csv('/kaggle/input/dmia-dl-nlp-2019/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"text_vectorized = vectorizer.transform(test.question)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_prediction = log_reg.predict(text_vectorized)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.main_category = test_prediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}