<jupyter_start><jupyter_text>Classify names to the country they might correspondClassifying names with a character-level RNN<jupyter_code>from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os
import unicodedata
import string
def findFiles(path):
    return glob.glob(path)

print(findFiles('name_data/names/*.txt'))
all_letters = string.ascii_letters + ".,;''"
n_letters = len(all_letters)

print(all_letters)
print()
print(n_letters)<jupyter_output>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,;''

57<jupyter_text>Transform from unicode to ascii<jupyter_code>def unicodeToAscii(s):
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn' and c in all_letters
    )
print(unicodeToAscii('Björn'))
category_lines = {}
all_categories = []

def readLines(filename):
    lines = open(filename, encoding='utf-8').read().strip().split('\n')
    return [unicodeToAscii(line) for line in lines]

for filename in findFiles('name_data/names/*.txt'):
    category = os.path.splitext(os.path.basename(filename))[0]
    all_categories.append(category)
    lines = readLines(filename)
    category_lines[category] = lines
    
n_categories = len(all_categories)
n_categories
print(category_lines['Italian'][:5])<jupyter_output>['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni']<jupyter_text>Turning names to tensorsCreate tensor of size (line_length X 1 X n_letters). Middle index is for batch.<jupyter_code>import torch

def letterToIndex(letter):
    return all_letters.find(letter)


def letterToTensor(letter):
    tensor = torch.zeros(1, n_letters)
    tensor[0][letterToIndex(letter)] = 1
    return tensor


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
print(letterToTensor('J'))
print()
print(lineToTensor('Jones').size())<jupyter_output>tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
         0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0.]])

torch.Size([5, 1, 57])<jupyter_text>Create the network<jupyter_code>from IPython.display import Image, display
print('Network architecture.')

Image('https://i.imgur.com/Z2xbySO.png')
import torch.nn as nn
import torch.nn.functional as F

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 = F.relu(self.i2o(combined))
        output = self.softmax(output)
        return output, hidden
    
    def initHidden(self):
        return torch.zeros(1, self.hidden_size)
    
    
n_hidden = 256
rnn = RNN(n_letters, n_hidden, n_categories)
        
        
        
        
input = letterToTensor('A')
hidden = torch.zeros(1, n_hidden)
output, next_hidden = rnn(input, hidden)

print(output)<jupyter_output>tensor([[-2.8515, -2.9116, -2.9116, -2.9116, -2.8076, -2.8940, -2.8629, -2.8999,
         -2.9116, -2.9043, -2.9116, -2.8618, -2.9116, -2.9116, -2.9093, -2.8489,
         -2.9093, -2.9047]], grad_fn=<LogSoftmaxBackward>)<jupyter_text>Prepare for training<jupyter_code>def categoryFromOutput(output):
    top_n, top_i = output.topk(1)
    category_i = top_i[0].item()
    return all_categories[category_i], category_i

print(categoryFromOutput(output))

import random

def randomChoice(l):
    return l[random.randint(0, len(l) - 1)]

def randomTrainingExample():
    category = randomChoice(all_categories)
    line = randomChoice(category_lines[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.0003

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()
    
    # update parameters
    for p in rnn.parameters():
        p.data.add_(p.grad.data, alpha=-learning_rate)
        
    return output, loss.item()
        
import time
import math

n_iters = int(1e5)
print_every = 5000
plot_every = 1000

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.time()

for iter in range(1, n_iters + 1):
    category, line, category_tensor, line_tensor = randomTrainingExample()
    output, loss = train(category_tensor, line_tensor)
    current_loss += loss
    
    if iter % print_every == 0:
        guess, guess_i = categoryFromOutput(output)
        correct = 'correct' if guess == category else "wrong" 
        print('%d %d%% (%s) %.4f %s / %s %s' % (
            iter, 
            iter / n_iters * 100, 
            timeSince(start_time), 
            loss, 
            line, 
            guess,
            correct)
             )
        
    if iter % plot_every == 0:
        all_losses.append(current_loss/plot_every)
        current_loss = 0
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)<jupyter_output><empty_output><jupyter_text>Evaluate results<jupyter_code>confusion = torch.zeros(n_categories, n_categories)
n_confusion = 10000

def evaluate(line_tensor):
    hidden = rnn.initHidden()
    
    for i in range(line_tensor.size()[0]):
        output, hidden = rnn(line_tensor[i], hidden)
        
    return output

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
    
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()<jupyter_output><ipython-input-18-b33e8ea7a866>:30: UserWarning: FixedFormatter should only be used together with FixedLocator
  ax.set_xticklabels([''] + all_categories, rotation=90)
<ipython-input-18-b33e8ea7a866>:31: UserWarning: FixedFormatter should only be used together with FixedLocator
  ax.set_yticklabels([''] + all_categories)<jupyter_text>Predict<jupyter_code>def predict(input_line, n_predictions=3):
    print('\n> %s' % input_line)    
    with torch.no_grad():
        output = evaluate(lineToTensor(input_line))
        
        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('Dovesky')
predict('Jackson')
predict('Satoshi')<jupyter_output>> Dovesky
(-2.43) English
(-2.52) Japanese
(-2.53) Scottish

> Jackson
(-2.21) Scottish
(-2.42) English
(-2.54) Irish

> Satoshi
(-2.12) Italian
(-2.22) Japanese
(-2.65) Dutch
{'fraction_non_alphanumeric': 0.13615421920465567, 'fraction_numerical': 0.03419010669253152, 'mean_word_length': 3.432563138097797, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 30, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '43998', 'license': 'MIT', 'n_tokens_mistral': 3078, 'n_tokens_neox': 2862, 'n_words': 623, 'path': 'notebooks/.ipynb_checkpoints/NLP From Scrach Example from Pytorch-checkpoint.ipynb', 'repo_name': 'gilberto-BE/aifi-pytorch', 'size': '8248'}