深度学习入门--循环神经网络
直接上例子:
题目: 构建一个RNN,使'hello'->'ohlol'
1. 总体思路:
由于’hello‘为字符串,不能构建为向量,因此需要进行一定处理,将字符与index关联。
![](https://img-blog.csdnimg.cn/20210426101218552.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbmdqaV9qb2ll,size_16,color_FFFFFF,t_70)
- 将’hello‘将为[1,0,2,2,3]索引之后,还需要将其转换为独热向量,只有该位置上的数字为1,其余都为0.
- 独热向量的列数由字符的个数也就是索引的个数决定,图1.1 中共有4个字母,因此独热向量有4列!,(也就是inputsize!)
- 将最后独热向量作为RNN的输入,其中inputsize=4,由于字符串长度为5,所以,seq_len=5,包括(x1,x2,x3,x4,x5)
![](https://img-blog.csdnimg.cn/20210426102013326.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbmdqaV9qb2ll,size_16,color_FFFFFF,t_70)
- 代表这每一个独热向量输入RNNcell,input_size=4,输入进网络
- 输出为一个多分类问题,在输入处理部分,将[e,h,l,o]=[0,1,2,3],输出为4维的向量,举例:o [0,0,0,1]
![](https://img-blog.csdnimg.cn/20210426102510625.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbmdqaV9qb2ll,size_16,color_FFFFFF,t_70)
2. 准备数据,确定输入维度,input_size=4,seq_len=5,hiddensize=4,batch_size=1
input_size=4
hidden_size=4
batch_size=1
idx2char = ['e','h','l','o']
'hello'
x_data=[1,0,2,2,3]
'ohlol'
y_data=[3,1,2,3,2]
one_hot_lookup=[
[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]
]
#print(one_hot_lookup[2])
'矩阵为seq_len*inputsize'
x_one_hot=[one_hot_lookup[x] for x in x_data]
#print(x_one_hot)
'序列长度seq_len,batchsize,inputsize,'
inputs=torch.Tensor(x_one_hot).view(-1,batch_size,input_size)
#print(inputs)
'比较值'
'+vie(-1,1) 为最后输出分类情况对比,限制其为n行1列,seq_len*1'
labels=torch.LongTensor(y_data).view(-1,1)
#print(labels)