210 lines
6.2 KiB
Plaintext
210 lines
6.2 KiB
Plaintext
{
|
|
"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 zgodnie z poradą Pana Jakuba\n",
|
|
"# https://radimrehurek.com/gensim/auto_examples/howtos/run_downloader_api.html\n",
|
|
"# https://www.kaggle.com/kstathou/word-embeddings-logistic-regression\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": 59,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"y_dev = []\n",
|
|
"y_test = []\n",
|
|
"\n",
|
|
"#model.eval() will notify all your layers that you are in eval mode\n",
|
|
"model.eval()\n",
|
|
"\n",
|
|
"#torch.no_grad() impacts the autograd engine and deactivate it. It will reduce memory usage and speed up\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",
|
|
" y = (outputs > 0.5)\n",
|
|
" y_dev.extend(y)\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",
|
|
" y = (outputs > 0.5)\n",
|
|
" y_test.extend(y)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 60,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"y_dev = np.asarray(y_dev, dtype=np.int32)\n",
|
|
"y_test = np.asarray(y_test, dtype=np.int32)\n",
|
|
"\n",
|
|
"y_dev_df = pd.DataFrame({'label':y_dev})\n",
|
|
"y_test_df = pd.DataFrame({'label':y_test})\n",
|
|
"\n",
|
|
"y_dev_df.to_csv(r'dev-0/out.tsv', sep='\\t', index=False, header=False)\n",
|
|
"y_test_df.to_csv(r'test-A/out.tsv', sep='\\t', index=False, header=False)"
|
|
]
|
|
},
|
|
{
|
|
"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
|
|
}
|