作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 PyTorch 1.4,需要在 forward
中的循环内导出带有卷积的模型:
class MyCell(torch.nn.Module):
def __init__(self):
super(MyCell, self).__init__()
def forward(self, x):
for i in range(5):
conv = torch.nn.Conv1d(1, 1, 2*i+3)
x = torch.nn.Relu()(conv(x))
return x
torch.jit.script(MyCell())
RuntimeError:
Arguments for call are not valid.
The following variants are available:
_single(float[1] x) -> (float[]):
Expected a value of type 'List[float]' for argument 'x' but instead found type 'Tensor'.
_single(int[1] x) -> (int[]):
Expected a value of type 'List[int]' for argument 'x' but instead found type 'Tensor'.
The original call is:
File "***/torch/nn/modules/conv.py", line 187
padding=0, dilation=1, groups=1,
bias=True, padding_mode='zeros'):
kernel_size = _single(kernel_size)
~~~~~~~ <--- HERE
stride = _single(stride)
padding = _single(padding)
'Conv1d.__init__' is being compiled since it was called from 'Conv1d'
File "***", line ***
def forward(self, x):
for _ in range(5):
conv = torch.nn.Conv1d(1, 1, 2*i+3)
~~~~~~~~~~~~~~~ <--- HERE
x = torch.nn.Relu()(conv(x))
return x
'Conv1d' is being compiled since it was called from 'MyCell.forward'
File "***", line ***
def forward(self, x, h):
for _ in range(5):
conv = torch.nn.Conv1d(1, 1, 2*i+3)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
x = torch.nn.Relu()(conv(x))
return x
conv
'然后将它们放在
__init__
内的列表中,但 TorchScript 不允许这样的类型:
class MyCell(torch.nn.Module):
def __init__(self):
super(MyCell, self).__init__()
self.conv = [torch.nn.Conv1d(1, 1, 2*i+3) for i in range(5)]
def forward(self, x):
for i in range(len(self.conv)):
x = torch.nn.Relu()(self.conv[i](x))
return x
torch.jit.script(MyCell())
RuntimeError:
Module 'MyCell' has no attribute 'conv' (This attribute exists on the Python module, but we failed to convert Python type: 'list' to a TorchScript type.):
File "***", line ***
def forward(self, x):
for i in range(len(self.conv)):
~~~~~~~~~ <--- HERE
x = torch.nn.Relu()(self.conv[i](x))
return x
nn.Sequential
可能适用于这种简化的情况,实际上我需要在每次迭代中与所有历史卷积输出进行卷积,这不仅仅是链接层。
最佳答案
作为 [ https://stackoverflow.com/users/6210807/kharshit] 的替代品建议,您可以定义网络功能方式:
class MyCell(torch.nn.Module):
def __init__(self):
super(MyCell, self).__init__()
self.w = []
for i in range(5):
self.w.append( torch.Tensor( 1, 1, 2*i+3 ) )
# init w[i] here, maybe make it "requires grad"
def forward(self, x):
for i in range(5):
x = torch.nn.functional.conv1d( x, self.w[i] )
x = torch.nn.functional.relu( x )
return x
关于pytorch - 使用 _ConvNd 对模块进行 Torchscripting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60530703/
我正在使用 PyTorch 1.4,需要在 forward 中的循环内导出带有卷积的模型: class MyCell(torch.nn.Module): def __init__(self):
我是一名优秀的程序员,十分优秀!