【发布时间】:2020-09-30 00:11:47
【问题描述】:
我是 pytorch 的新手,我遵循了一个关于使用 RNN 生成句子的教程,我正在尝试修改它以生成位置序列,但是我在定义正确的模型参数(例如 input_size、output_size)时遇到了麻烦, hidden_dim, batch_size。
背景: 我有 596 个 x,y 位置序列,每个看起来像 [[x1,y1],[x2,y2],...,[xn,yn]]。每个序列代表车辆的二维路径。我想训练一个模型,给定一个起点(或部分序列),它可以生成其中一个序列。
-我已经对序列进行了填充/截断,使它们的长度都为 50,这意味着每个序列都是一个形状为 [50,2] 的数组
-然后我把这个数据分成input_seq和target_seq:
input_seq:torch.Size([596, 49, 2]) 的张量。包含所有 596 个序列,每个序列都没有最后一个位置。
target_seq:torch.Size([596, 49, 2]) 的张量。包含所有 596 个序列,每个序列都没有第一个位置。
模型类:
class Model(nn.Module):
def __init__(self, input_size, output_size, hidden_dim, n_layers):
super(Model, self).__init__()
# Defining some parameters
self.hidden_dim = hidden_dim
self.n_layers = n_layers
#Defining the layers
# RNN Layer
self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first=True)
# Fully connected layer
self.fc = nn.Linear(hidden_dim, output_size)
def forward(self, x):
batch_size = x.size(0)
# Initializing hidden state for first input using method defined below
hidden = self.init_hidden(batch_size)
# Passing in the input and hidden state into the model and obtaining outputs
out, hidden = self.rnn(x, hidden)
# Reshaping the outputs such that it can be fit into the fully connected layer
out = out.contiguous().view(-1, self.hidden_dim)
out = self.fc(out)
return out, hidden
def init_hidden(self, batch_size):
# This method generates the first hidden state of zeros which we'll use in the forward pass
# We'll send the tensor holding the hidden state to the device we specified earlier as well
hidden = torch.zeros(self.n_layers, batch_size, self.hidden_dim)
return hidden
我使用以下参数实例化模型:
input_size 为 2(一个 [x,y] 位置)
output_size 为 2(一个 [x,y] 位置)
hidden_dim of 2(一个 [x,y] 位置)(或者在完整序列的长度中应该是 50?)
model = Model(input_size=2, output_size=2, hidden_dim=2, n_layers=1)
n_epochs = 100
lr=0.01
# Define Loss, Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# Training Run
for epoch in range(1, n_epochs + 1):
optimizer.zero_grad() # Clears existing gradients from previous epoch
output, hidden = model(input_seq)
loss = criterion(output, target_seq.view(-1).long())
loss.backward() # Does backpropagation and calculates gradients
optimizer.step() # Updates the weights accordingly
if epoch%10 == 0:
print('Epoch: {}/{}.............'.format(epoch, n_epochs), end=' ')
print("Loss: {:.4f}".format(loss.item()))
当我运行训练循环时,它失败并出现以下错误:
ValueError Traceback (most recent call last)
<ipython-input-9-ad1575e0914b> in <module>
3 optimizer.zero_grad() # Clears existing gradients from previous epoch
4 output, hidden = model(input_seq)
----> 5 loss = criterion(output, target_seq.view(-1).long())
6 loss.backward() # Does backpropagation and calculates gradients
7 optimizer.step() # Updates the weights accordingly
...
ValueError: Expected input batch_size (29204) to match target batch_size (58408).
我尝试修改 input_size、output_size、hidden_dim 和 batch_size 并重塑张量,但我尝试的越多,我就越困惑。有人能指出我做错了什么吗?
此外,由于批次大小在 Model.forward(self,x) 中定义为 x.size(0),这意味着我只有一个大小为 596 的批次,对吗?拥有多个小批量的正确方法是什么?
【问题讨论】:
标签: python machine-learning pytorch lstm recurrent-neural-network