hyunsu-yang / PyTorch

Deep Learning Zero to All - Pytorch
0 stars 0 forks source link

pytorch study 10주차 #12

Open hyunsu-yang opened 3 years ago

hyunsu-yang commented 3 years ago

강의

목차

hyunsu-yang commented 3 years ago

Lab-11-0 RNN intro

핵심

hyunsu-yang commented 3 years ago

Lab-11-1 RNN basics

핵심


# sequential example
# shape : (3, 5, 4)
h = [1, 0, 0, 0]
e = [0, 1, 0, 0]
l = [0, 0, 1, 0]
o = [0, 0, 0, 1]
input_data_np = np.array([[h, e, l, l, o], [e, o, l, l, l], [l, l, e, e, l]], dtype=np.float32)

# transform as torch tensor
input_data = torch.Tensor(input_data_np)

# declare dimension
input_size = 4
hidden_size = 2

# declare RNN
rnn = torch.nn.RNN(input_size, hidden_size)

# check output
outputs, _status = rnn(input_data)
hyunsu-yang commented 3 years ago

Lab-11-2 RNN hihello and charseq

핵심

Random seed to make results deterministic and reproducible

torch.manual_seed(0)

char_set = ['h', 'i', 'e', 'l', 'o']

hyper parameters

input_size = len(char_set) hidden_size = len(char_set) learning_rate = 0.01

data setting

x_data = [[0, 1, 0, 2, 3, 3]] x_one_hot = [[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 1, 0]]] y_data = [[1, 0, 2, 3, 3, 4]]

transform as torch tensor variable

X = torch.FloatTensor(x_one_hot) Y = torch.LongTensor(y_data)

declare RNN

rnn = torch.nn.RNN(input_size, hidden_size, batch_first=True) # batch_first guarantees the order of output = (B, S, F)

loss & optimizer setting

criterion = torch.nn.CrossEntropyLoss() optimizer = optim.Adam(rnn.parameters(), learning_rate)

start training

for i in range(1000): optimizer.zero_grad() outputs, _status = rnn(X) loss = criterion(outputs.view(-1, input_size), Y.view(-1)) loss.backward() optimizer.step()

result = outputs.data.numpy().argmax(axis=2)
result_str = ''.join([char_set[c] for c in np.squeeze(result)])
print(i, "loss: ", loss.item(), "prediction: ", result, "true Y: ", y_data, "prediction str: ", result_str)
hyunsu-yang commented 3 years ago

번외