{ "cells": [ { "cell_type": "code", "execution_count": 38, "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 as api" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "#Sieć neuronowa z ćwiczeń 8\n", "class NeuralNetwork(torch.nn.Module): \n", " def __init__(self, hidden_size):\n", " super(NeuralNetwork, self).__init__()\n", " self.l1 = torch.nn.Linear(300, hidden_size) #Korzystamy z Googlowego word2vec-google-news-300 który ma zawsze na wejściu wymiar 300\n", " self.l2 = torch.nn.Linear(hidden_size, 1)\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": 40, "metadata": {}, "outputs": [], "source": [ "# Wczytanie X i Y do Train oraz X do Dev i Test\n", "X_train = pd.read_table('train/in.tsv', sep='\\t', error_bad_lines=False, quoting=3, header=None, names=['content', 'id'], usecols=['content'])\n", "y_train = pd.read_table('train/expected.tsv', sep='\\t', error_bad_lines=False, quoting=3, header=None, names=['label'])\n", "X_dev = pd.read_table('dev-0/in.tsv', sep='\\t', error_bad_lines=False, header=None, quoting=3, names=['content', 'id'], usecols=['content'])\n", "X_test = pd.read_table('test-A/in.tsv', sep='\\t', error_bad_lines=False, header=None, quoting=3, names=['content', 'id'], usecols=['content'])" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "# Preprocessing danych\n", "# lowercase\n", "# https://www.datacamp.com/community/tutorials/case-conversion-python\n", "X_train = X_train.content.str.lower()\n", "y_train = y_train['label']\n", "X_dev = X_dev.content.str.lower()\n", "X_test = X_test.content.str.lower()" ] }, { "cell_type": "code", "execution_count": 42, "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": 44, "metadata": {}, "outputs": [], "source": [ "# word2vec\n", "# https://radimrehurek.com/gensim/auto_examples/howtos/run_downloader_api.html\n", "w2v = api.load('word2vec-google-news-300')\n", "X_train = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_train]\n", "X_dev = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_dev]\n", "X_test = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_test]" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "model = NeuralNetwork(600)\n", "\n", "criterion = torch.nn.BCELoss()\n", "optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)\n", "\n", "batch_size = 15" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "# Trening modelu z ćwiczeń 8\n", "for epoch in range(5):\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": 47, "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": 49, "metadata": {}, "outputs": [], "source": [ "dev_prediction.tofile('./dev-0/out.tsv', sep='\\n')\n", "test_prediction.tofile('./test-A/out.tsv', sep='\\n')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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 }