## 《深度学习框架PyTorch：入门与实践》的Loss函数构建代码运行问题

output = net(input)
target = Variable(t.arange(0,10))
criterion = nn.MSELoss()
loss = criterion(output, target)
loss


RuntimeError                              Traceback (most recent call last)
<ipython-input-37-e5c73861a53b> in <module>()
2 target = Variable(t.arange(0,10))
3 criterion = nn.MSELoss()
----> 4 loss = criterion(output, target)
5 loss

RuntimeError: Expected object of type torch.FloatTensor but found type torch.LongTensor for argument #2 'target'


#torch.from_numpy(Y).float()
output = net(input)
y = np.arange(0,10).reshape(1,10)
target = Variable(t.from_numpy(y).float())
criterion = nn.MSELoss()
loss = criterion(output, target)
loss


tensor(28.5897, grad_fn=<MseLossBackward>)


import torch.optim as optim
#新建一个优化器，指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(),lr=0.01)

#在训练过程中

#计算损失
output = net(input)
#把target改为Variable(t.from_numpy(y).float())就不会出错了
loss = criterion(output, target)

#反向传播
loss.backward()

#更新参数
optimizer.step()


import torch.optim as optim
#新建一个优化器，指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(),lr=0.01)

#在训练过程中

#计算损失
output = net(input)
#把target改为Variable(t.from_numpy(y).float())就不会出错了
loss = criterion(output, Variable(t.from_numpy(y).float()))

#反向传播
loss.backward()

#更新参数
optimizer.step()


posted on 2018-08-08 18:49  星辰之衍  阅读(1988)  评论(0编辑  收藏