paranormal-or-skeptic-ISI-p.../run.py
2022-05-25 22:54:49 +02:00

114 lines
3.5 KiB
Python
Executable File

#!/usr/bin/env python
# coding: utf-8
import lzma
from gensim.models import Word2Vec
import gensim.downloader
import numpy as np
import pandas as pd
import torch
X_train = lzma.open("train/in.tsv.xz", mode='rt', encoding='utf-8').readlines()
y_train = np.array(open('train/expected.tsv').readlines())
X_dev0 = lzma.open("dev-0/in.tsv.xz", mode='rt', encoding='utf-8').readlines()
y_expected_dev0 = np.array(open("dev-0/expected.tsv", "r").readlines())
X_test = lzma.open("test-A/in.tsv.xz", mode='rt', encoding='utf-8').readlines()
X_train = [line.split() for line in X_train]
X_dev0 = [line.split() for line in X_dev0]
X_test = [line.split() for line in X_test]
model_w2v = Word2Vec(X_train, vector_size=100, window=5, min_count=1, workers=4)
def vectorize(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])
X_train_w2v = vectorize(model_w2v, X_train)
X_dev0_w2v = vectorize(model_w2v, X_dev0)
X_test_w2v = vectorize(model_w2v, X_test)
FEATURES = 100
class NeuralNetworkModel(torch.nn.Module):
def __init__(self):
super(NeuralNetworkModel, self).__init__()
self.fc1 = torch.nn.Linear(FEATURES,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
nn_model = NeuralNetworkModel()
BATCH_SIZE = 42
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(nn_model.parameters(), lr = 0.1)
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)
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
for epoch in range(10):
loss_score = 0
acc_score = 0
items_total = 0
nn_model.train()
for i in range(0, y_train.shape[0], BATCH_SIZE):
X = X_train_w2v[i:i+BATCH_SIZE]
X = torch.tensor(X)
Y = y_train[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, X_train_w2v, y_train))
display(get_loss_acc(nn_model, X_dev0_w2v, y_expected_dev0))
y_pred_dev0 = predict(nn_model, X_dev0_w2v)
y_pred_test = predict(nn_model, X_test_w2v)
open('dev-0/out.tsv', 'w').writelines([i+'\n' for i in y_pred_dev0])
open('test-A/out.tsv', 'w').writelines([i+'\n' for i in y_pred_test])