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

14 KiB

#!/usr/bin/env python
# coding: utf-8
import lzma
import gensim.models
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
X_train = lzma.open("train/in.tsv.xz", mode='rt', encoding='utf-8').readlines()
y_train = open('train/expected.tsv').readlines()
X_dev0 = lzma.open("dev-0/in.tsv.xz", mode='rt', encoding='utf-8').readlines()
y_expected_dev0 = 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]

def tagged_document(list_of_list_of_words):
   for i, list_of_words in enumerate(list_of_list_of_words):
      yield gensim.models.doc2vec.TaggedDocument(list_of_words, [i])

data_training = list(tagged_document(X_train))
model = gensim.models.doc2vec.Doc2Vec(vector_size=1000)
model.build_vocab(data_training)

X_train_d2v = [model.infer_vector(line) for line in X_train]
X_dev0_d2v = [model.infer_vector(line) for line in X_dev0]
X_test_d2v = [model.infer_vector(line) for line in X_test]

y_train = np.array([int(i) for i in y_train])
y_expected_dev0 = np.array([int(i) for i in y_expected_dev0])
class Net(nn.Module):
    """W PyTorchu tworzenie sieci neuronowej
    polega na zdefiniowaniu klasy, która dziedziczy z nn.Module.
    """
    
    def __init__(self):
        super().__init__()
        
        # Warstwy splotowe
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        
        # Warstwy dropout
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        
        # Warstwy liniowe
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        """Definiujemy przechodzenie "do przodu" jako kolejne przekształcenia wejścia x"""
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output


def train(model, device, train_loader, optimizer, epoch, log_interval, dry_run):
    """Uczenie modelu"""
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)  # wrzucenie danych na kartę graficzną (jeśli dotyczy)
        optimizer.zero_grad()  # wyzerowanie gradientu
        output = model(data)  # przejście "do przodu"
        loss = F.nll_loss(output, target)  # obliczenie funkcji kosztu
        loss.backward()  # propagacja wsteczna
        optimizer.step()  # krok optymalizatora
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            if dry_run:
                break


def test(model, device, test_loader):
    """Testowanie modelu"""
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)  # wrzucenie danych na kartę graficzną (jeśli dotyczy)
            output = model(data)  # przejście "do przodu"
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # suma kosztów z każdego batcha
            pred = output.argmax(dim=1, keepdim=True)  # predykcja na podstawie maks. logarytmu prawdopodobieństwa
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)  # obliczenie kosztu na zbiorze testowym

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))


def run(
        batch_size=64,
        test_batch_size=1000,
        epochs=14,
        lr=1.0,
        gamma=0.7,
        no_cuda=False,
        dry_run=False,
        seed=1,
        log_interval=10,
        save_model=False,
    ):
    """Main training function.
    
    Arguments:
        batch_size - wielkość batcha podczas uczenia (default: 64),
        test_batch_size - wielkość batcha podczas testowania (default: 1000)
        epochs - liczba epok uczenia (default: 14)
        lr - współczynnik uczenia (learning rate) (default: 1.0)
        gamma - współczynnik gamma (dla optymalizatora) (default: 0.7)
        no_cuda - wyłącza uczenie na karcie graficznej (default: False)
        dry_run - szybko ("na sucho") sprawdza pojedyncze przejście (default: False)
        seed - ziarno generatora liczb pseudolosowych (default: 1)
        log_interval - interwał logowania stanu uczenia (default: 10)
        save_model - zapisuje bieżący model (default: False)
    """
    use_cuda = no_cuda and torch.cuda.is_available()

    torch.manual_seed(seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    train_kwargs = {'batch_size': batch_size}
    test_kwargs = {'batch_size': test_batch_size}
    if use_cuda:
        cuda_kwargs = {'num_workers': 1,
                       'pin_memory': True,
                       'shuffle': True}
        train_kwargs.update(cuda_kwargs)
        test_kwargs.update(cuda_kwargs)

    transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,))
        ])
    dataset1 = datasets.MNIST('../data', train=True, download=True,
                       transform=transform)
    dataset2 = datasets.MNIST('../data', train=False,
                       transform=transform)
    train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
    test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)

    model = Net().to(device)
    optimizer = optim.Adadelta(model.parameters(), lr=lr)

    scheduler = StepLR(optimizer, step_size=1, gamma=gamma)
    for epoch in range(1, epochs + 1):
        train(model, device, train_loader, optimizer, epoch, log_interval, dry_run)
        test(model, device, test_loader)
        scheduler.step()

    if save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")
0.003825023
FEATURES = 1000
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 = 5
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])
        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)
for epoch in range(5):
    loss_score = 0
    acc_score = 0
    items_total = 0
    nn_model.train()
    for i in range(0, y_train.shape[0], BATCH_SIZE):
        X = np.array(X_train_d2v[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_d2v, y_train))
    display(get_loss_acc(nn_model, X_dev0_d2v, y_expected_dev0))