my brilliant

This commit is contained in:
Druminska 2022-05-28 15:40:45 +02:00
parent 77aa85972a
commit 279693e9e8
3 changed files with 8728 additions and 8180 deletions

File diff suppressed because it is too large Load Diff

548
pytorch.ipynb Normal file
View File

@ -0,0 +1,548 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"import lzma\n",
"import torch\n",
"import numpy as np\n",
"from gensim import downloader\n",
"from gensim.models import Word2Vec\n",
"import gensim.downloader\n",
"import pandas as pd\n",
"import csv"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"\n",
"from sklearn.datasets import fetch_20newsgroups\n",
"# https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html\n",
"\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sklearn.metrics import accuracy_score"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\10118794\\AppData\\Local\\Temp\\ipykernel_32100\\3675615398.py:1: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.\n",
"\n",
"\n",
" train_x = pd.read_csv('train/in.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"C:\\Users\\10118794\\AppData\\Local\\Temp\\ipykernel_32100\\3675615398.py:2: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.\n",
"\n",
"\n",
" train_y = pd.read_csv('train/expected.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"C:\\Users\\10118794\\AppData\\Local\\Temp\\ipykernel_32100\\3675615398.py:3: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.\n",
"\n",
"\n",
" dev_x = pd.read_csv('dev-0/in.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"C:\\Users\\10118794\\AppData\\Local\\Temp\\ipykernel_32100\\3675615398.py:4: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.\n",
"\n",
"\n",
" dev_y = pd.read_csv('dev-0/expected.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"C:\\Users\\10118794\\AppData\\Local\\Temp\\ipykernel_32100\\3675615398.py:5: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.\n",
"\n",
"\n",
" test_x = pd.read_csv('test-A/in.tsv', header=None, sep='\\t',quoting=csv.QUOTE_NONE, error_bad_lines=False)\n"
]
}
],
"source": [
"train_x = pd.read_csv('train/in.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"train_y = pd.read_csv('train/expected.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"dev_x = pd.read_csv('dev-0/in.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"dev_y = pd.read_csv('dev-0/expected.tsv', header=None, sep='\\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)\n",
"test_x = pd.read_csv('test-A/in.tsv', header=None, sep='\\t',quoting=csv.QUOTE_NONE, error_bad_lines=False)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"train_x = train_x[0]\n",
"dev_x = dev_x[0]\n",
"test_x = test_x[0]\n",
"train_y = train_y[0]\n",
"dev_y = dev_y[0]\n",
"train_y = train_y.to_numpy()\n",
"dev_y = dev_y.to_numpy()"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[==================================================] 100.0% 387.1/387.1MB downloaded\n"
]
}
],
"source": [
"word2vec_100 = downloader.load(\"glove-twitter-100\")"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {},
"outputs": [],
"source": [
"train_x_w2v = [np.mean([word2vec_100[word.lower()] for word in doc.split() if word.lower() in word2vec_100]\n",
" or [np.zeros(100, dtype=float)], axis=0) for doc in train_x]\n"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {},
"outputs": [],
"source": [
"dev_x_w2v2 = [np.mean([word2vec_100[word.lower()] for word in doc.split() if word.lower() in word2vec_100]\n",
" or [np.zeros(100, dtype=float)], axis=0) for doc in dev_x]"
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {},
"outputs": [],
"source": [
"test_x_w2v = [np.mean([word2vec_100[word.lower()] for word in doc.split() if word.lower() in word2vec_100]\n",
" or [np.zeros(100, dtype=float)], axis=0) for doc in test_x]"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'list'>\n"
]
}
],
"source": [
"print(type(x_train_w2v))"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [],
"source": [
"class NeuralNetworkModelx(torch.nn.Module):\n",
"\n",
" def __init__(self):\n",
" super(NeuralNetworkModelx, self).__init__()\n",
" self.fc1 = torch.nn.Linear(100,500)\n",
" self.fc2 = torch.nn.Linear(500,1)\n",
"\n",
" def forward(self, x):\n",
" x = self.fc1(x)\n",
" x = torch.relu(x)\n",
" x = self.fc2(x)\n",
" x = torch.sigmoid(x)\n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [],
"source": [
"def predict(model, data):\n",
" model.eval()\n",
" predictions = []\n",
" for x in data:\n",
" X = torch.tensor(np.array(x).astype(np.float32))\n",
" Y_predictions = model(X)\n",
" if Y_predictions[0] > 0.5:\n",
" predictions.append(\"1\")\n",
" else:\n",
" predictions.append(\"0\")\n",
" return predictions"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [],
"source": [
"BATCH_SIZE = 22"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {},
"outputs": [],
"source": [
"FEATURES = 100"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [],
"source": [
"model = NeuralNetworkModelx()\n",
"criterion = torch.nn.BCELoss()\n",
"optimizer = torch.optim.ASGD(model.parameters(), lr=0.1)"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {},
"outputs": [],
"source": [
"def get_loss_acc(model, X_dataset, Y_dataset):\n",
" loss_score = 0\n",
" acc_score = 0\n",
" items_total = 0\n",
" model.eval()\n",
" for i in range(0, Y_dataset.shape[0], BATCH_SIZE):\n",
" X = np.array(X_dataset[i:i+BATCH_SIZE]).astype(np.float32)\n",
" X = torch.tensor(X)\n",
" Y = Y_dataset[i:i+BATCH_SIZE]\n",
" Y = torch.tensor(Y.astype(np.float32)).reshape(-1,1)\n",
" Y_predictions = model(X)\n",
" acc_score += torch.sum((Y_predictions > 0.5) == Y).item()\n",
" items_total += Y.shape[0]\n",
"\n",
" loss = criterion(Y_predictions, Y)\n",
"\n",
" loss_score += loss.item() * Y.shape[0]"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5251316127311283 0.7293691876828085\n"
]
},
{
"data": {
"text/plain": [
"1"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5236849654193508 0.7303671882284282\n"
]
},
{
"data": {
"text/plain": [
"2"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5224315920787511 0.7310509394672956\n"
]
},
{
"data": {
"text/plain": [
"3"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5211956211888409 0.7323010301161341\n"
]
},
{
"data": {
"text/plain": [
"4"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5201234243425219 0.7329606083314052\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5192769648569354 0.7337203319301469\n"
]
},
{
"data": {
"text/plain": [
"6"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5182789765264713 0.7341761660893918\n"
]
},
{
"data": {
"text/plain": [
"7"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5173362161154499 0.7348944502191112\n"
]
},
{
"data": {
"text/plain": [
"8"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5163200458762819 0.7358717310302197\n"
]
},
{
"data": {
"text/plain": [
"9"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5155178654158614 0.7361583540242904\n"
]
}
],
"source": [
"for epoch in range(10):\n",
" loss_score = 0\n",
" acc_score = 0\n",
" items_total = 0\n",
" for i in range(0, train_y.shape[0], BATCH_SIZE):\n",
" x = train_x_w2v[i:i+BATCH_SIZE]\n",
" x = torch.tensor(np.array(x).astype(np.float32))\n",
" y = train_y[i:i+BATCH_SIZE]\n",
" y = torch.tensor(y.astype(np.float32)).reshape(-1, 1)\n",
" y_pred = model(x)\n",
" acc_score += torch.sum((y_pred > 0.5) == y).item()\n",
" items_total += y.shape[0]\n",
"\n",
" optimizer.zero_grad()\n",
" loss = criterion(y_pred, y)\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" loss_score += loss.item() * y.shape[0]\n",
" display(epoch)\n",
" #display(get_loss_acc(model, train_x_w2v, train_y))\n",
" #display(get_loss_acc(model, dev_x_w2v2, dev_y))\n",
" print((loss_score / items_total), (acc_score / items_total))"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [],
"source": [
"pred_dev = predict(model, dev_x_w2v2)\n",
"pred_test = predict(model, test_x_w2v)"
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {},
"outputs": [],
"source": [
"dev_pred = [int(i) for i in pred_dev]\n",
"test_pred = [int(i) for i in pred_test]"
]
},
{
"cell_type": "code",
"execution_count": 121,
"metadata": {},
"outputs": [],
"source": [
"dev_pred = np.array(dev_pred)\n",
"test_pred = np.array(test_pred)"
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"numpy.ndarray"
]
},
"execution_count": 122,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(dev_pred)"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 0, ..., 0, 1, 0])"
]
},
"execution_count": 123,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dev_pred"
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [],
"source": [
"np.savetxt(\"dev-0/out.tsv\",dev_pred, delimiter=\"\\t\", fmt='%d')\n",
"np.savetxt(\"test-A/out.tsv\",test_pred, delimiter=\"\\t\", fmt='%d')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "py",
"language": "python",
"name": "py"
},
"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.10.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

File diff suppressed because it is too large Load Diff