{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import torch\n", "import csv\n", "from nltk.tokenize import word_tokenize\n", "from gensim.models import Word2Vec\n", "import gensim.downloader" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class NeuralNetwork(torch.nn.Module):\n", " def __init__(self, input_size, hidden_size, num_classes):\n", " super(NeuralNetwork, self).__init__()\n", " self.l1 = torch.nn.Linear(input_size, hidden_size)\n", " self.l2 = torch.nn.Linear(hidden_size, num_classes)\n", "\n", " def forward(self, x):\n", " x = self.l1(x)\n", " x = torch.relu(x)\n", " x = self.l2(x)\n", " x = torch.sigmoid(x)\n", " return x" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "col_names = ['content', 'id', 'label']\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wczytanie danych...\n" ] } ], "source": [ "print('Wczytanie danych...')\n", "# loading dataset\n", "train_set_features = pd.read_table('train/in.tsv.xz', error_bad_lines=False, quoting=csv.QUOTE_NONE, header=None, names=col_names[:2])\n", "train_set_labels = pd.read_table('train/expected.tsv', error_bad_lines=False, quoting=csv.QUOTE_NONE, header=None, names=col_names[2:])\n", "dev_set = pd.read_table('dev-0/in.tsv.xz', error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE, names=col_names[:2])\n", "test_set = pd.read_table('test-A/in.tsv.xz', error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE, names=col_names[:2])" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preprocessing danych...\n" ] } ], "source": [ "print('Preprocessing danych...')\n", "# lowercase\n", "X_train = train_set_features['content'].str.lower()\n", "y_train = train_set_labels['label']" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "X_dev = dev_set['content'].str.lower()\n", "X_test = test_set['content'].str.lower()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# tokenize\n", "X_train = [word_tokenize(content) for content in X_train]\n", "X_dev = [word_tokenize(content) for content in X_dev]\n", "X_test = [word_tokenize(content) for content in X_test]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[==================================================] 100.0% 1662.8/1662.8MB downloaded\n" ] } ], "source": [ "# word2vec\n", "word2vec = gensim.downloader.load('word2vec-google-news-300')\n", "X_train = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_train]\n", "X_dev = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_dev]\n", "X_test = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_test]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "model = NeuralNetwork(300, 600, 1)\n", "\n", "criterion = torch.nn.BCELoss()\n", "optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)\n", "\n", "batch_size = 10" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Trenowanie modelu...\n" ] } ], "source": [ "print('Trenowanie modelu...')\n", "for epoch in range(6):\n", " model.train()\n", " for i in range(0, y_train.shape[0], batch_size):\n", " X = X_train[i:i+batch_size]\n", " X = torch.tensor(X)\n", " y = y_train[i:i+batch_size]\n", " y = torch.tensor(y.astype(np.float32).to_numpy()).reshape(-1,1)\n", "\n", " outputs = model(X.float())\n", " loss = criterion(outputs, y)\n", "\n", " optimizer.zero_grad()\n", " loss.backward()\n", " optimizer.step()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Predykcje...\n" ] } ], "source": [ "print('Predykcje...')\n", "dev_prediction = []\n", "test_prediction = []\n", "\n", "model.eval()\n", "with torch.no_grad():\n", " for i in range(0, len(X_dev), batch_size):\n", " X = X_dev[i:i+batch_size]\n", " X = torch.tensor(X)\n", "\n", " outputs = model(X.float())\n", "\n", " prediction = (outputs > 0.5)\n", " dev_prediction = dev_prediction + prediction.tolist()\n", "\n", " for i in range(0, len(X_test), batch_size):\n", " X = X_test[i:i+batch_size]\n", " X = torch.tensor(X)\n", "\n", " outputs = model(X.float())\n", "\n", " prediction = (outputs > 0.5)\n", " test_prediction = test_prediction + prediction.tolist()\n", "\n", "dev_prediction = np.asarray(dev_prediction, dtype=np.int32)\n", "test_prediction = np.asarray(test_prediction, dtype=np.int32)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "dev_prediction.tofile('./dev-0/out.tsv', sep='\\n')\n", "test_prediction.tofile('./test-A/out.tsv', sep='\\n')" ] } ], "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.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }