Mismatch in shape: grad_output[0] has a shape of torch.Size([2]) and output[0] has a shape of torch.
Posted 我想月薪过万
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mismatch in shape: grad_output[0] has a shape of torch.Size([2]) and output[0] has a shape of torch.相关的知识,希望对你有一定的参考价值。
错误日志
错误一:
Mismatch in shape: grad_output[0] has a shape of torch.Size([2]) and output[0] has a shape of torch.Size([2, 2])
错误二
expected sequence of length 2 at dim 1 (got 1)
错误原因
在进行 张量 梯度求解时,传入数据维度不对
错误代码示例
import torch
# 第一步:创建 tensor
x = torch.ones(2,2,requires_grad=True)
print(x)
# 第二步:对 tensor 做处理
y = x**2
print(y)
# 第三步:求梯度
y.backward(torch.tensor([[3,2],[2]],dtype=float))# 这里加了一个类型
print(x.grad)
正确代码示例
import torch
# 第一步:创建 tensor
x = torch.ones(2,2,requires_grad=True)
print(x)
# 第二步:对 tensor 做处理
y = x**2
print(y)
# 第三步:求梯度
y.backward(torch.tensor([[3,2],[2,2]],dtype=float))# 这里加了一个类型
print(x.grad)
运行结果
以上是关于Mismatch in shape: grad_output[0] has a shape of torch.Size([2]) and output[0] has a shape of torch.的主要内容,如果未能解决你的问题,请参考以下文章
Tensorflow+keras解决Exception has occurred: ValueError Shape mismatch: The shape of labels (received(代
Shap LSTM (Keras, TensorFlow) ValueError: shape mismatch: objects cannot be broadcast to a single sh
size mismatch for roi_heads.box_predictor.cls_score.weight: copying a param with shape torch.Size([9
pytorch 训练时错误size mismatch for module_list.88.Conv2d.weight: copying a param with shape torch.Size
MySQLInnoDB: Error: checksum mismatch in data file 报错
ValueError: feature_names mismatch: in xgboost in the predict() function