Compare commits

...

3 Commits

Author SHA1 Message Date
Druminska
279693e9e8 my brilliant 2022-05-28 15:40:45 +02:00
Druminska
77aa85972a my brilliant 2022-05-27 22:35:23 +02:00
Druminska
dca3122fab my brilliant solution 2022-05-08 10:21:29 +02:00
5 changed files with 11437 additions and 0 deletions

5272
dev-0/out.tsv Normal file

File diff suppressed because it is too large Load Diff

160
foo.py Normal file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import pathlib
from collections import Counter
from sklearn.metrics import *
import pandas as pd
# In[1]:
import numpy as np, pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import confusion_matrix, accuracy_score
sns.set() # use seaborn plotting style
# In[5]:
train_x = pd.read_csv('train/in.tsv', header=None, sep='\t')
train_y = pd.read_csv('train/expected.tsv', header=None, sep='\t')
dev_x = pd.read_csv('dev-0/in.tsv', header=None, sep='\t')
dev_y = pd.read_csv('dev-0/expected.tsv', header=None, sep='\t')
test_x = pd.read_csv('test-A/in.tsv', header=None, sep='\t')
# In[61]:
print(dev_y.shape)
print(dev_x.shape)
# In[11]:
print(train_x[:15])
# In[27]:
print(train_x.shape)
# In[49]:
print(train_y.shape)
# In[8]:
print(train_y[:15])
# In[53]:
print(dev_x[:4])
# In[119]:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
vec = CountVectorizer(stop_words='english')
x1 = vec.fit_transform(train_x[:20000][0])
tfidf_transformer = TfidfTransformer()
x1_tf = tfidf_transformer.fit_transform(x1)
# In[120]:
# Build the model
#model = make_pipeline(TfidfVectorizer(), MultinomialNB())
clf = MultinomialNB().fit(x1_tf, train_y[:20000][0])
# In[121]:
# Train the model using the training data
#model.fit(x1[:][0], train_y[:289541][0])
# Predict the categories of the test data
X_new_counts = vec.transform(dev_x[:][0])
# We call transform instead of fit_transform because it's already been fit
X_new_tfidf = tfidf_transformer.transform(X_new_counts)
#predicted_categories = model.predict(dev_x[:][0])
# In[122]:
predicted = clf.predict(X_new_tfidf)
# In[125]:
print(predicted[:10])
# In[126]:
print(predicted.shape)
# In[123]:
#mat = confusion_matrix(dev_y[:][0],predicted_categories)
print("The accuracy is {}".format(accuracy_score( dev_y[:][0],predicted_categories)))
# In[124]:
print('We got an accuracy of',np.mean(predicted == dev_y[:][0])*100, '% over the test data.')
# In[130]:
np.savetxt("out.tsv",predicted, delimiter="\t", fmt='%d')
# In[131]:
X_test = vec.transform(test_x[:][0])
# We call transform instead of fit_transform because it's already been fit
X_tfidf_test = tfidf_transformer.transform(X_test)
predicted_test = clf.predict(X_tfidf_test)
np.savetxt("out.tsv",predicted_test, delimiter="\t", fmt='%d')
# In[ ]:

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
}

305
run_pytorch.py Normal file
View File

@ -0,0 +1,305 @@
#!/usr/bin/env python
# coding: utf-8
# In[3]:
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_20newsgroups
# https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score
# In[71]:
import numpy as np
import gensim
import torch
import pandas as pd
from gensim.test.utils import common_texts
from gensim.models import Word2Vec
import csv
# In[84]:
train_x = pd.read_csv('train/in.tsv', header=None, sep='\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)
train_y = pd.read_csv('train/expected.tsv', header=None, sep='\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)
dev_x = pd.read_csv('dev-0/in.tsv', header=None, sep='\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)
dev_y = pd.read_csv('dev-0/expected.tsv', header=None, sep='\t', quoting=csv.QUOTE_NONE, error_bad_lines=False)
test_x = pd.read_csv('test-A/in.tsv', header=None, sep='\t',quoting=csv.QUOTE_NONE, error_bad_lines=False)
# In[85]:
print(len(train_x))
# In[86]:
print(len(train_y))
# In[87]:
train_y = train_y[0]
# In[100]:
dev_y = dev_y[0]
# In[88]:
print(type(train_y))
# In[89]:
train_y = train_y.to_numpy()
# In[102]:
dev_y = dev_y.to_numpy()
# In[90]:
train_x.head
# In[91]:
dev_x.head()
# In[92]:
train_x = train_x[0]
# In[93]:
vec_model = Word2Vec(train_x, vector_size=100, window=5, min_count=1, workers=4)
# In[ ]:
def w2v(model, data):
return np.array([np.mean([model.wv[word] if word in model.wv.key_to_index else np.zeros(100, dtype=float) for word in doc], axis=0) for doc in data])
# In[ ]:
w2v()
# In[96]:
dev_x = dev_x[0]
test_x = test_x[0]
# In[95]:
vec_x_train = np.array([np.mean([vec_model.wv[word] if word in vec_model.wv.key_to_index else np.zeros(100, dtype=float) for word in doc], axis=0) for doc in train_x])
# In[97]:
vec_x_dev = np.array([np.mean([vec_model.wv[word] if word in vec_model.wv.key_to_index else np.zeros(100, dtype=float) for word in doc], axis=0) for doc in dev_x])
vec_x_test = np.array([np.mean([vec_model.wv[word] if word in vec_model.wv.key_to_index else np.zeros(100, dtype=float) for word in doc], axis=0) for doc in test_x])
# In[36]:
X_dev0_w2v = vectorize(vec_model,dev_x)
X_test_w2v = vectorize(vec_model,test_x)
# In[7]:
class NeuralNetworkModel(torch.nn.Module):
def __init__(self):
super(NeuralNetworkModel, self).__init__()
self.fc1 = torch.nn.Linear(FEAUTERES,500)
self.fc2 = torch.nn.Linear(500,1)
def forward(self, x):
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
x = torch.sigmoid(x)
return x
# In[37]:
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(nn_model.parameters(), lr = 0.1)
# In[8]:
def get_loss_acc(model, X_dataset, Y_dataset):
loss_score = 0
acc_score = 0
items_total = 0
model.eval()
for i in range(0, Y_dataset.shape[0], BATCH_SIZE):
X = np.array(X_dataset[i:i+BATCH_SIZE]).astype(np.float32)
X = torch.tensor(X)
Y = Y_dataset[i:i+BATCH_SIZE]
Y = torch.tensor(Y.astype(np.float32)).reshape(-1,1)
Y_predictions = model(X)
acc_score += torch.sum((Y_predictions > 0.5) == Y).item()
items_total += Y.shape[0]
loss = criterion(Y_predictions, Y)
loss_score += loss.item() * Y.shape[0]
return (loss_score / items_total), (acc_score / items_total)
# In[9]:
def predict(model, data):
model.eval()
predictions = []
for x in data:
X = torch.tensor(np.array(x).astype(np.float32))
Y_predictions = model(X)
if Y_predictions[0] > 0.5:
predictions.append("1")
else:
predictions.append("0")
return predictions
# In[18]:
FEAUTERES = 100
# In[62]:
BATCH_SIZE = 5
# In[58]:
nn_model = NeuralNetworkModel()
# In[103]:
for epoch in range(7):
loss_score = 0
acc_score = 0
items_total = 0
nn_model.train()
for i in range(0, train_y.shape[0], BATCH_SIZE):
X = vec_x_train[i:i+BATCH_SIZE]
X = torch.tensor(X)
Y = train_y[i:i+BATCH_SIZE]
Y = torch.tensor(Y.astype(np.float32)).reshape(-1,1)
Y_predictions = nn_model(X)
acc_score += torch.sum((Y_predictions > 0.5) == Y).item()
items_total += Y.shape[0]
optimizer.zero_grad()
loss = criterion(Y_predictions, Y)
loss.backward()
optimizer.step()
loss_score += loss.item() * Y.shape[0]
display(epoch)
display(get_loss_acc(nn_model,vec_x_train, train_y))
display(get_loss_acc(nn_model, vec_x_dev, dev_y))
# In[104]:
dev_pred = predict(nn_model, vec_x_dev)
test_pred = predict(nn_model, vec_x_test)
# In[105]:
dev_pred
# In[119]:
dev_pred = [int(i) for i in dev_pred]
test_pred = [int(i) for i in test_pred]
# In[120]:
dev_pred = np.array(dev_pred)
test_pred = np.array(test_pred)
# In[117]:
dev_pred
# In[121]:
np.savetxt("dev-0/out.tsv",dev_pred, delimiter="\t", fmt='%d')
# In[122]:
np.savetxt("test-A/out.tsv",test_pred, delimiter="\t", fmt='%d')
# In[ ]:

5152
test-A/out.tsv Normal file

File diff suppressed because it is too large Load Diff