python - 如何解决以下 CNN 架构的错误“mat1 和 mat2 形状不能相乘”?
问题描述
我正在尝试Conv1d
使用批量标准化实现模型,但出现错误:
RuntimeError Traceback (most recent call last)
<ipython-input-117-ef6e122ea50c> in <module>()
----> 1 test()
2 for epoch in range(1, n_epochs + 1):
3 train(epoch)
4 test()
7 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
1751 if has_torch_function_variadic(input, weight):
1752 return handle_torch_function(linear, (input, weight), input, weight, bias=bias)
-> 1753 return torch._C._nn.linear(input, weight, bias)
1754
1755
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x140 and 100x10)
我使用的批量大小为 32,数据的特征数为 40。我一直在尝试计算数据的32 x 140
来源,但我无法做到这一点。这是我尝试使用的 CNN 架构:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
#self.flatten=nn.Flatten()
self.net_stack=nn.Sequential(
nn.Conv1d(in_channels=1, out_channels=25, kernel_size=5, stride=2), #applying batch norm
nn.ReLU(),
nn.BatchNorm1d(25, affine=True),
nn.Conv1d(in_channels=25, out_channels=20, kernel_size=5, stride=2), #applying batch norm
nn.ReLU(),
nn.BatchNorm1d(20, affine=True),
nn.Flatten()
nn.Linear(20*5, 10),
nn.Softmax(dim=1))
def forward(self,x):
# result=self.net_stack(x[None])
result=self.net_stack(x[:, None, :])
return result
解决方案
这个完全连接的应该从:
nn.Linear(20*5, 10)
至:
nn.Linear(20*7, 10)
为什么?
如果您的输入数据长度为 40,则 (B
是批量大小):
- 第一次转换后的输出(K=25):
B x 25 x 18
- 第二次转换后的输出(K=20):
B x 20 x 7
nn.Flatten()
:之后的输出B x 140
,即如果 B=32,则32x140
推荐阅读
- swift - 如何在 Github Actions 上使用催化剂运行 macOS 构建?
- php - 如何仅显示发送到数据库的最后一篇文章?PHPMYADMIN
- list - 按谓词过滤列表并将结果放入新列表
- azure - Azure Functions 主机实例与 VM 实例
- ios - 有什么方法可以在 SwiftUI 中使用 @ViewBuilder 创建/提取视图数组
- vue.js - 卸载 Electron 应用后删除 Vuex 商店
- python - ModuleNotFoundError: No module named 'chefsBackEnd.wsgi' Django RF API 使用 Heroku 和 Gunicorn 部署
- python - 添加字典值,其中值是列表
- raspberry-pi - 使用 L293D(电机控制器)连接到 Raspberry Pi 的电机在过载时不运行
- flutter - 无法在颤振中添加包(仅在 mac 上)