Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import os
- import random
- import string
- import time
- import matplotlib.pyplot as plt
- import matplotlib.ticker as ticker
- import torch
- from torch import nn
- #sva slova abecede koja koristimo za rijeci, broj tih slova, broj ukupnih kategorija
- all_letters = string.ascii_letters
- n_letters = len(all_letters)
- class AnimalDataset():
- def readLines(filename):
- lines = open(filename, encoding='utf-8').read().strip().split('\n')
- return [line for line in lines]
- def __init__(self, data_root):
- self.data_root = data_root
- self.animals = []
- self.animal_words = {}
- for animal in os.listdir(self.data_root): # otvori Data direktorij
- self.animals.append(animal)
- animal_folder = os.path.join(self.data_root, animal) # put poddirektorija
- filepath = animal_folder + "/" + str(os.listdir(animal_folder)[0]) # put seta podataka
- lines = open(filepath, encoding='utf-8').read().strip().split('\n')
- self.animal_words[animal] = lines
- # dodajemo uzorke u mapu: Zivotinja - rijec za zivotinju
- # Find letter index from all_letters, e.g. "a" = 0
- def letterToIndex(letter):
- return all_letters.find(letter)
- # Turn a line into a <line_length x 1 x n_letters>,
- # or an array of one-hot letter vectors
- def lineToTensor(line):
- tensor = torch.zeros(len(line), 1, n_letters)
- for li, letter in enumerate(line):
- tensor[li][0][letterToIndex(letter)] = 1
- return tensor
- dataset = AnimalDataset('/home/pero/Documents/Neuronske/Data/') #promjeniti na lokaciju dataseta
- all_categories = dataset.animals
- words = dataset.animal_words
- n_categories = len(all_categories)
- class RNN(nn.Module):
- def __init__(self, input_size, hidden_size, output_size):
- super(RNN, self).__init__()
- self.hidden_size = hidden_size
- self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
- self.i2o = nn.Linear(input_size + hidden_size, output_size)
- self.softmax = nn.LogSoftmax(dim=1)
- def forward(self, input, hidden):
- combined = torch.cat((input, hidden), 1)
- hidden = self.i2h(combined)
- output = self.i2o(combined)
- output = self.softmax(output)
- return output, hidden
- def initHidden(self):
- return torch.zeros(1, self.hidden_size)
- def categoryFromOutput(output):
- top_n, top_i = output.topk(1)
- category_i = top_i[0].item()
- return all_categories[category_i], category_i
- n_hidden = 500
- rnn = RNN(n_letters, n_hidden, n_categories)
- inputs = lineToTensor('kamel')
- hidden = torch.zeros(1, n_hidden)
- output, next_hidden = rnn(inputs[0], hidden)
- print(output) #test run za jedno ponavljanje mreže
- print(categoryFromOutput(output))
- def randomChoice(l):
- return l[random.randint(0, len(l) - 1)]
- def randomTrainingExample():
- category = randomChoice(all_categories)
- line = randomChoice(words[category])
- category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long)
- line_tensor = lineToTensor(line)
- return category, line, category_tensor, line_tensor
- for i in range(10):
- category, line, category_tensor, line_tensor = randomTrainingExample()
- print('category =', category, '/ line =', line)
- criterion = nn.NLLLoss()
- learning_rate = 0.00045 #PARAM 1
- def train(category_tensor, line_tensor):
- hidden = rnn.initHidden()
- rnn.zero_grad()
- for i in range(line_tensor.size()[0]):
- output, hidden = rnn(line_tensor[i], hidden)
- loss = criterion(output, category_tensor)
- loss.backward()
- # Add parameters' gradients to their values, multiplied by learning rate
- for p in rnn.parameters():
- p.data.add_(-learning_rate, p.grad.data)
- return output, loss.item()
- n_iters = 70000 #PARAM 2
- print_every = 500
- plot_every = 100
- # Keep track of losses for plotting
- current_loss = 0
- all_losses = []
- def timeSince(since):
- now = time.time()
- s = now - since
- m = math.floor(s / 60)
- s -= m * 60
- return '%dm %ds' % (m, s)
- start = time.time()
- for iter in range(1, n_iters):
- category, line, category_tensor, line_tensor = randomTrainingExample()
- output, loss = train(category_tensor, line_tensor)
- current_loss += loss
- # Print iter number, loss, name and guess
- if iter % print_every == 0:
- guess, guess_i = categoryFromOutput(output)
- correct = '✓' if guess == category else '✗ (%s)' % category
- print(
- '%d %d%% (%s) %.4f %s / %s %s' % (iter, iter / n_iters * 100, timeSince(start), loss, line, guess, correct))
- # Add current loss avg to list of losses
- if iter % plot_every == 0:
- all_losses.append(current_loss / plot_every)
- current_loss = 0
- plt.figure()
- plt.plot(all_losses)
- # Keep track of correct guesses in a confusion matrix
- confusion = torch.zeros(n_categories, n_categories)
- n_confusion = 10000
- # Just return an output given a line
- def evaluate(line_tensor):
- hidden = rnn.initHidden()
- for i in range(line_tensor.size()[0]):
- output, hidden = rnn(line_tensor[i], hidden)
- return output
- # Go through a bunch of examples and record which are correctly guessed
- for i in range(n_confusion):
- category, line, category_tensor, line_tensor = randomTrainingExample()
- output = evaluate(line_tensor)
- guess, guess_i = categoryFromOutput(output)
- category_i = all_categories.index(category)
- confusion[category_i][guess_i] += 1
- # Normalize by dividing every row by its sum
- for i in range(n_categories):
- confusion[i] = confusion[i] / confusion[i].sum()
- # Set up plot
- fig = plt.figure()
- ax = fig.add_subplot(111)
- cax = ax.matshow(confusion.numpy())
- fig.colorbar(cax)
- # Set up axes
- ax.set_xticklabels([''] + all_categories, rotation=90)
- ax.set_yticklabels([''] + all_categories)
- # Force label at every tick
- ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
- ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
- # sphinx_gallery_thumbnail_number = 2
- plt.show()
- def predict(input_line, n_predictions=3):
- print('\n> %s' % input_line)
- with torch.no_grad():
- output = evaluate(lineToTensor(input_line))
- # Get top N categories
- topv, topi = output.topk(n_predictions, 1, True)
- predictions = []
- for i in range(n_predictions):
- value = topv[0][i].item()
- category_index = topi[0][i].item()
- print('(%.2f) %s' % (value, all_categories[category_index]))
- predictions.append([value, all_categories[category_index]])
- predict('pes')
- predict('cucak')
- predict('dva')
- predict('treger')
- a = input("Daj zivinu: ")
- while a != 'kraj':
- predict(str(a))
- a = input("Daj zivinu: ")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement