python - TypeError: mul() 参数“其他”(位置 1)必须是张量,而不是 ReLU
问题描述
我想torch.nn.ReLU()
在 fc1 和 fc2 层之间添加一个层。
原始代码:
模型:
# ...
self.fc1 = nn.Linear(4096, 256)
self.fc2 = nn.Linear(256, 4096)
# ...
def forward(...):
# ...
x = x.view(-1, 4096)
x = self.fc1(x))
if a7 is not None:
x = x * a7.squeeze()
# ...
我试过了
# ...
x = x.view(-1, 4096)
x = nn.ReLU(self.fc1(x)))
if a7 is not None:
x = x * a7.squeeze()
# ...
并弹出此错误。
解决方案
我的回答假设__init__
是一个错字,应该是forward
。如果不是这样,请告诉我,我会删除它。
import torch
from torch import nn
class SimpleModel(nn.Module):
def __init__(self, with_relu=False):
super(SimpleModel, self).__init__()
self.fc1 = nn.Sequential(nn.Linear(3, 10), nn.ReLU(inplace=True)) if with_relu else nn.Linear(3, 10)
self.fc2 = nn.Linear(10, 3)
def forward(self, x):
x = self.fc1(x)
print(torch.min(x)) # just to show you ReLU is working...
return self.fc2(x)
# Model without ReLU
net_without_relu = SimpleModel(with_relu=False)
print(net_without_relu)
# Model with ReLU
net_with_relu = SimpleModel(with_relu=True)
print(net_with_relu)
# random input data
x = torch.randn((5, 3))
print(x)
# we expect it to print something < 0
output1 = net_without_relu(x)
# we expect it to print 0.
output2 = net_with_relu(x)
您可以查看 Colab 上运行的以下代码:https ://colab.research.google.com/drive/1W3Dh4_KPd3iABx5FSzZm3tilm6tnJh0v
要按照您的尝试使用:
x = nn.ReLU(self.fc1(x)))
您可以使用功能 API:
from torch.nn import functional as F
# ...
x = F.relu(self.fc1(x)))
推荐阅读
- python - 用于执行字数统计的 Python 脚本
- kubernetes-helm - Rancher 不接受目录中的更改
- xpages - Xpages Type Ahead 下拉字体大小
- r - R 调查包:svyby + svymean:一对多变量
- c# - ACR 用户对话框 - 更改忙碌指示器颜色?
- php - Yii强制登录总是返回主页
- sql - 使用 listagg 选择不同的值
- python - 如何修复“ImportError:尝试在没有已知父包的情况下进行相对导入”
- php - spatie/laravel-medialibrary 更改主键
- google-cloud-platform - 带有环境变量的 Cloudbuild.yaml?