6.6 KiB
6.6 KiB
import pandas as pd
import numpy as np
import torch
import csv
from nltk.tokenize import word_tokenize
from gensim.models import Word2Vec
import gensim.downloader
class NeuralNetwork(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetwork, self).__init__()
self.l1 = torch.nn.Linear(input_size, hidden_size)
self.l2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, x):
x = self.l1(x)
x = torch.relu(x)
x = self.l2(x)
x = torch.sigmoid(x)
return x
col_names = ['content', 'id', 'label']
print('Wczytanie danych...')
# loading dataset
train_set_features = pd.read_table('train/in.tsv.xz', error_bad_lines=False, quoting=csv.QUOTE_NONE, header=None, names=col_names[:2])
train_set_labels = pd.read_table('train/expected.tsv', error_bad_lines=False, quoting=csv.QUOTE_NONE, header=None, names=col_names[2:])
dev_set = pd.read_table('dev-0/in.tsv.xz', error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE, names=col_names[:2])
test_set = pd.read_table('test-A/in.tsv.xz', error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE, names=col_names[:2])
Wczytanie danych...
print('Preprocessing danych...')
# lowercase
X_train = train_set_features['content'].str.lower()
y_train = train_set_labels['label']
Preprocessing danych...
X_dev = dev_set['content'].str.lower()
X_test = test_set['content'].str.lower()
# tokenize
X_train = [word_tokenize(content) for content in X_train]
X_dev = [word_tokenize(content) for content in X_dev]
X_test = [word_tokenize(content) for content in X_test]
# word2vec
word2vec = gensim.downloader.load('word2vec-google-news-300')
X_train = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_train]
X_dev = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_dev]
X_test = [np.mean([word2vec[word] for word in content if word in word2vec] or [np.zeros(300)], axis=0) for content in X_test]
[==================================================] 100.0% 1662.8/1662.8MB downloaded
model = NeuralNetwork(300, 600, 1)
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
batch_size = 10
print('Trenowanie modelu...')
for epoch in range(6):
model.train()
for i in range(0, y_train.shape[0], batch_size):
X = X_train[i:i+batch_size]
X = torch.tensor(X)
y = y_train[i:i+batch_size]
y = torch.tensor(y.astype(np.float32).to_numpy()).reshape(-1,1)
outputs = model(X.float())
loss = criterion(outputs, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
Trenowanie modelu...
print('Predykcje...')
dev_prediction = []
test_prediction = []
model.eval()
with torch.no_grad():
for i in range(0, len(X_dev), batch_size):
X = X_dev[i:i+batch_size]
X = torch.tensor(X)
outputs = model(X.float())
prediction = (outputs > 0.5)
dev_prediction = dev_prediction + prediction.tolist()
for i in range(0, len(X_test), batch_size):
X = X_test[i:i+batch_size]
X = torch.tensor(X)
outputs = model(X.float())
prediction = (outputs > 0.5)
test_prediction = test_prediction + prediction.tolist()
dev_prediction = np.asarray(dev_prediction, dtype=np.int32)
test_prediction = np.asarray(test_prediction, dtype=np.int32)
Predykcje...
dev_prediction.tofile('./dev-0/out.tsv', sep='\n')
test_prediction.tofile('./test-A/out.tsv', sep='\n')