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

12 KiB

#!/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))
0
(0.49161445487174543, 0.7499197110287693)
(0.4990149180719994, 0.7420333839150227)
1
(0.486242138754709, 0.7533833599812141)
(0.4960476360955079, 0.7448786039453718)
2
(0.48170865143118824, 0.7566018254086104)
(0.49339661830880754, 0.7448786039453718)
3
(0.47863767532834156, 0.7587877573995352)
(0.49210414077877457, 0.7503793626707133)
4
(0.4755889592268004, 0.7613466446116604)
(0.49055553189223017, 0.753793626707132)
5
(0.47395927866325194, 0.7623273787118541)
(0.4905445413022374, 0.7541729893778453)
6
(0.4721670034531442, 0.7639055318237855)
(0.4896522785377249, 0.7522761760242792)
7
(0.4713666787153674, 0.7644166186083936)
(0.4897225151384003, 0.7532245827010622)
8
(0.4687599671611641, 0.7661674361745845)
(0.4882916720620779, 0.7524658573596358)
9
(0.4669961705231401, 0.767617817590364)
(0.48753329053272426, 0.7534142640364189)
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])