{"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":{},"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/deepnlp-hse-course/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/deepnlp-hse-course/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/deepnlp-hse-course/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":"# Посмотрим на answers.jsonl\n\n## answers.jsonl\nФайл, где каждая строка - это json такого вида:\n```json\n{\n    'вопрос': [\n        'ответ_1',\n        'ответ_2',\n        ...,\n        'ответ_n'\n    ]\n}\n```   "},{"metadata":{},"cell_type":"markdown","source":"## Читаем файл"},{"metadata":{"trusted":true},"cell_type":"code","source":"input_file = open('/kaggle/input/deepnlp-hse-course/answers.jsonl')\n\nprogress_bar = tqdm()\n\nadditional_data = {\n    'question': [],\n    'answer': []\n}\n\ntry:\n    while True:\n\n        line = input_file.readline().strip()\n\n        if not line:\n            break\n            \n        line = json.loads(line)\n        \n        question = list(line.keys())[0]\n        \n        for answer in line[question]:\n            additional_data['question'].append(question)\n            additional_data['answer'].append(answer)\n            \n        progress_bar.update()\n            \nexcept KeyboardInterrupt:\n    pass\n\nprogress_bar.close()\ninput_file.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"additional_data = pd.DataFrame(data=additional_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"additional_data.sample(frac=1).head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f'Количество строк в таблице: {additional_data.shape[0]}'","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_test, y_train, y_test = train_test_split(train.question, train.target, test_size=0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vectorizer = TfidfVectorizer(max_features=75000, ngram_range=(1, 2))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train_vectorized = vectorizer.fit_transform(x_train)\nx_test_vectorized = vectorizer.transform(x_test)","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_test = log_reg.predict(x_test_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_test, y_pred=predicted_test, 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_test, predicted_test, 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":{"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}