projekt-uma/neural_network.ipynb
2021-06-30 14:45:40 +02:00

7.1 KiB

import pandas as pd
import numpy as np
import torch
from nltk.tokenize import word_tokenize
import gensim.downloader
#wczytywanie danych
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'])
x_train = x_train.content.str.lower()
x_dev = x_dev.content.str.lower()
x_test = x_test.content.str.lower()
import nltk
nltk.download('punkt')
[nltk_data] Downloading package punkt to /home/tomasz/nltk_data...
[nltk_data]   Unzipping tokenizers/punkt.zip.
True
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 = gensim.downloader.load("word2vec-google-news-300")
def document_vector(doc):
    """Create document vectors by averaging word vectors. Remove out-of-vocabulary words."""
    return np.mean([word2vec[w] for w in doc if w in word2vec] or [np.zeros(300)], axis=0)
x_train = [document_vector(doc) for doc in x_train]
x_dev = [document_vector(doc) for doc in x_dev]
x_test = [document_vector(doc) for doc in x_test]
class NeuralNetwork(torch.nn.Module): 
    def __init__(self, hidden_size):
        super(NeuralNetwork, self).__init__()
        self.l1 = torch.nn.Linear(300, hidden_size)
        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
hidden_size = 600
epochs = 5
batch_size = 15
model = NeuralNetwork(hidden_size)
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(epochs):
    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()
/home/tomasz/.local/lib/python3.8/site-packages/torch/autograd/__init__.py:130: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at  /pytorch/c10/cuda/CUDAFunctions.cpp:100.)
  Variable._execution_engine.run_backward(
y_dev = []
y_test = []
model.eval()
NeuralNetwork(
  (l1): Linear(in_features=300, out_features=600, bias=True)
  (l2): Linear(in_features=600, out_features=1, bias=True)
)
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)
        y_dev.extend(prediction)

    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())
        y = (outputs > 0.5)
        y_test.extend(prediction)
y_dev = np.asarray(y_dev, dtype=np.int32)
y_test = np.asarray(y_test, dtype=np.int32)

y_dev = pd.DataFrame({'label':y_dev})
y_test = pd.DataFrame({'label':y_test})

y_dev.to_csv(r'dev-0/out.tsv', sep='\t', index=False,  header=False)
y_test.to_csv(r'test-A/out.tsv', sep='\t', index=False,  header=False)