PyTorch Deep Learning Practice-Liu Erduren-12 Red neuronal recurrente

Recomiendo encarecidamente al Maestro Liu Er-Práctica de aprendizaje profundo

Escrito al frente:

Pytorch revisado recientemente y conceptos básicos. Siga junto con el video.

Descubrí que no he descifrado este capítulo yo mismo, y hay relativamente pocos códigos reproducidos en Internet.

Primero haz un hoyo. descrita desde múltiples dimensiones.

1. Reproducir el código original

import torch

#基础定义
input_size = 4
hidden_size = 3
batch_size = 1
num_layers = 1
seq_len = 5

idx2char = ['e', 'h', 'l', 'o']

x_data = [1, 0, 2, 2, 3]

y_data = [2, 0, 1, 2, 1]

one_hot_lookup = [[1, 0, 0, 0],
                  [0, 1, 0, 0],
                  [0, 0, 1, 0],
                  [0, 0, 0, 1]]

x_one_hot = [one_hot_lookup[x] for x in x_data]

inputs = torch.Tensor(x_one_hot).view(seq_len, batch_size, input_size)

print("here", inputs)
#labels(seqLen*batchSize,1)为了之后进行矩阵运算,计算交叉熵
#注意这里,y_data没有view(-1,1)要明白为什么?
labels = torch.LongTensor(y_data)

class Model(torch.nn.Module):
    def __init__(self, input_size, hidden_size, batch_size, num_layers=1):
        super(Model, self).__init__()
        self.batch_size = batch_size #构造H0
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.rnn = torch.nn.RNN(input_size = self.input_size,
                                hidden_size = self.hidden_size,
                                num_layers=num_layers)

    def forward(self, input):
        hidden = torch.zeros(self.num_layers,
                             self.batch_size,
                             self.hidden_size)
        out, _ = self.rnn(input, hidden)
        #reshape(SeqLen*batchsize,hiddensize)为了方便交叉熵计算的矩阵乘法。
        return out.view(-1, self.hidden_size)

#构建模型
net = Model(input_size, hidden_size, batch_size, num_layers)


#基础的优化部分
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.05)

#输入的维度(SeqLen*batchsize*inputsize)
#输出的维度(SeqLen*batchsize*hiddensize)
#y的维度 hiddensize*1
#注意对比,如果这块是自己的数据,我们需要怎么样的修改?


for epoch in range(15):
    optimizer.zero_grad()
    outputs = net(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

    _, idx = outputs.max(dim=1)
    idx = idx.data.numpy()
    print('Predicted string: ',''.join([idx2char[x] for x in idx]), end = '')
    #这里是写死了,15,最好用个变量
    print(", Epoch [%d/15] loss = %.3f" % (epoch+1, loss.item()))


El resultado de ejecutar el código. 

Dos: Se agregó reducción de dimensionalidad de incrustación.

Esta pieza es una multiplicación de matrices, Sra. Li.

x_data = [[1, 0, 2, 2, 3]]
y_data = [3, 1, 2, 2, 3]
inputs = torch.LongTensor(x_data)
labels = torch.LongTensor(y_data)

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self .emb = torch.nn.Embedding(input_size, embedding_size)

        self.rnn = torch.nn.RNN(input_size = embedding_size,
                                hidden_size = hidden_size,
                                num_layers=num_layers,
                                batch_first = True)
                                
        self.fc = torch.nn.Linear(hidden_size, num_class)
    def forward(self, x):
        hidden = torch.zeros(num_layers, x.size(0), hidden_size)
        x = self.emb(x)
        x, _ = self.rnn(x, hidden)
        x = self.fc(x)
        return x.view(-1, num_class)

net = Model()

3. Entrenamiento de conjuntos de datos personalizados

Para ser agregado

Finalmente: Portal a GIT

reproducción de código

Supongo que te gusta

Origin blog.csdn.net/qq_33083551/article/details/129621695
Recomendado
Clasificación