7.7 KiB
7.7 KiB
import torch
import gensim.downloader as downloader
import pandas as pd
import csv
from nltk.tokenize import word_tokenize as tokenize
import numpy as np
class NeuralNetworkModel(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetworkModel, self).__init__()
self.fc1 = torch.nn.Linear(input_size,hidden_size)
self.fc2 = torch.nn.Linear(hidden_size,num_classes)
def forward(self,x):
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
x = torch.sigmoid(x)
return x
w2v = downloader.load('word2vec-google-news-300')
[==================================================] 100.0% 1662.8/1662.8MB downloaded
#model + settings
nn = NeuralNetworkModel(300,300,1)
crit = torch.nn.BCELoss()
opti = torch.optim.SGD(nn.parameters(), lr=0.08)
BATCH_SIZE = 5
epochs = 5
#trening
#wczytanie danych
train_data_in = pd.read_csv('train/in.tsv.xz', compression='xz', header=None, error_bad_lines=False, quoting=csv.QUOTE_NONE, sep='\t', nrows=3000)
train_data_ex = pd.read_csv('train/expected.tsv', header=None, error_bad_lines=False, quoting=csv.QUOTE_NONE, sep='\t', nrows=3000)
#preprocessing
train_in = train_data_in[0].str.lower()
train_in = [tokenize(line) for line in train_in]
train_in = [np.mean([w2v[x] for x in data if x in w2v] or [np.zeros(300)], axis=0) for data in train_in]
train_ex = train_data_ex[0]
for epoch in range(epochs):
nn.train()
for i in range(0,train_data_ex.shape[0],BATCH_SIZE):
x = train_in[i:i + BATCH_SIZE]
x = torch.tensor(x)
y = train_ex[i:i + BATCH_SIZE]
y = torch.tensor(y.astype(np.float32).to_numpy()).reshape(-1,1)
opti.zero_grad()
y_pred = nn(x.float())
loss = crit(y_pred,y)
loss.backward()
opti.step()
#dev-0 predict
#wczytanie danych
dev0_data = pd.read_csv('dev-0/in.tsv.xz', compression='xz', header=None, error_bad_lines=False, quoting=csv.QUOTE_NONE, sep='\t')
dev0_data = dev0_data[0].str.lower()
dev0_data = [tokenize(line) for line in dev0_data]
dev0_data = [np.mean([w2v[x] for x in data if x in w2v] or [np.zeros(300)], axis=0) for data in dev0_data]
dev0_y=[]
nn.eval()
with torch.no_grad():
for i in range(0, len(dev0_data), BATCH_SIZE):
x = dev0_data[i:i + BATCH_SIZE]
x = torch.tensor(x)
dev0_y_pred = nn(x.float())
dev0_y_prediction = (dev0_y_pred > 0.5)
dev0_y.extend(dev0_y_prediction)
#zapis wyników
np.asarray(dev0_y, dtype=np.int32).tofile('dev-0/out.tsv', sep='\n')
<ipython-input-27-b22b834acfd4>:21: FutureWarning: The input object of type 'Tensor' is an array-like implementing one of the corresponding protocols (`__array__`, `__array_interface__` or `__array_struct__`); but not a sequence (or 0-D). In the future, this object will be coerced as if it was first converted using `np.array(obj)`. To retain the old behaviour, you have to either modify the type 'Tensor', or assign to an empty array created with `np.empty(correct_shape, dtype=object)`. np.asarray(dev0_y, dtype=np.int32).tofile('dev-0/out.tsv', sep='\n') <ipython-input-27-b22b834acfd4>:21: DeprecationWarning: setting an array element with a sequence. This was supported in some cases where the elements are arrays with a single element. For example `np.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dtype=int)`. np.asarray(dev0_y, dtype=np.int32).tofile('dev-0/out.tsv', sep='\n')
#test-A predict
#wczytanie danych
testA_data = pd.read_csv('test-A/in.tsv.xz', compression='xz', header=None, quoting=csv.QUOTE_NONE, sep='\t')
testA_data = testA_data[0].str.lower()
testA_data = [tokenize(line) for line in testA_data]
testA_data = [np.mean([w2v[x] for x in data if x in w2v] or [np.zeros(300)], axis=0) for data in testA_data]
testA_y=[]
nn.eval()
with torch.no_grad():
for i in range(0, len(testA_data), BATCH_SIZE):
x = testA_data[i:i + BATCH_SIZE]
x = torch.tensor(x)
testA_y_pred = nn(x.float())
testA_y_prediction = (testA_y_pred > 0.5)
testA_y.extend(testA_y_prediction)
#zapis wyników
np.asarray(testA_y, dtype=np.int32).tofile('test-A/out.tsv', sep='\n')
<ipython-input-28-ed4376367760>:21: FutureWarning: The input object of type 'Tensor' is an array-like implementing one of the corresponding protocols (`__array__`, `__array_interface__` or `__array_struct__`); but not a sequence (or 0-D). In the future, this object will be coerced as if it was first converted using `np.array(obj)`. To retain the old behaviour, you have to either modify the type 'Tensor', or assign to an empty array created with `np.empty(correct_shape, dtype=object)`. np.asarray(testA_y, dtype=np.int32).tofile('test-A/out.tsv', sep='\n') <ipython-input-28-ed4376367760>:21: DeprecationWarning: setting an array element with a sequence. This was supported in some cases where the elements are arrays with a single element. For example `np.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dtype=int)`. np.asarray(testA_y, dtype=np.int32).tofile('test-A/out.tsv', sep='\n')