6.0 KiB
6.0 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 as api
#Sieć neuronowa z ćwiczeń 8
class NeuralNetwork(torch.nn.Module):
def __init__(self, hidden_size):
super(NeuralNetwork, self).__init__()
self.l1 = torch.nn.Linear(300, hidden_size) #Korzystamy z Googlowego word2vec-google-news-300 który ma zawsze na wejściu wymiar 300
self.l2 = torch.nn.Linear(hidden_size, 1)
def forward(self, x):
x = self.l1(x)
x = torch.relu(x)
x = self.l2(x)
x = torch.sigmoid(x)
return x
# Wczytanie X i Y do Train oraz X do Dev i Test
X_train = pd.read_table('train/in.tsv', sep='\t', error_bad_lines=False, quoting=3, header=None, names=['content', 'id'], usecols=['content'])
y_train = pd.read_table('train/expected.tsv', sep='\t', error_bad_lines=False, quoting=3, header=None, names=['label'])
X_dev = pd.read_table('dev-0/in.tsv', sep='\t', error_bad_lines=False, header=None, quoting=3, names=['content', 'id'], usecols=['content'])
X_test = pd.read_table('test-A/in.tsv', sep='\t', error_bad_lines=False, header=None, quoting=3, names=['content', 'id'], usecols=['content'])
# Preprocessing danych
# lowercase
# https://www.datacamp.com/community/tutorials/case-conversion-python
X_train = X_train.content.str.lower()
y_train = y_train['label']
X_dev = X_dev.content.str.lower()
X_test = X_test.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
# https://radimrehurek.com/gensim/auto_examples/howtos/run_downloader_api.html
w2v = api.load('word2vec-google-news-300')
X_train = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_train]
X_dev = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_dev]
X_test = [np.mean([w2v[w] for w in content if w in w2v] or [np.zeros(300)], axis=0) for content in X_test]
model = NeuralNetwork(600)
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
batch_size = 15
# Trening modelu z ćwiczeń 8
for epoch in range(5):
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()
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')