这个错误是因为输入的维度不符合模型的要求。模型的输入应该是一个3维的张量,而你的输入是一个4维的张量。你可以使用 torch.squeeze() 函数来去除多余的维度。具体来说,你可以在模型的 forward 函数中的第一行加上以下代码:

x = torch.squeeze(x, dim=2)

这样就可以将输入的维度从 [100, 1, 10000, 12] 变为 [100, 1, 10000],符合模型的要求。

示例代码:

import torch
import torch.nn as nn

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv1d(1, 5, kernel_size=3, stride=1, padding=1),
            nn.Mish()
        )
        # ... 其它层 ...
        self.fc = nn.Linear(40, 6)
        self.softmax = nn.Softmax(dim=1)
        self.loss_fn = nn.CrossEntropyLoss()

    def forward(self, x):
        x = torch.squeeze(x, dim=2)  # 添加这一行代码
        x = self.conv1(x)
        x = self.avgpool(x)
        # ... 其它层 ...
        output = self.softmax(x)
        return feature, output

注意:

  • torch.squeeze(x, dim=2) 中的 dim=2 指的是要去除的维度。你需要根据你的实际输入维度进行调整。
  • 确保你的输入数据的维度与模型的期望维度一致。
PyTorch CNN 模型错误:RuntimeError: Expected 3-dimensional input for 3-dimensional weight [5, 1, 3], but got 4-dimensional input of size [100, 1, 10000, 12] instead

原文地址: https://www.cveoy.top/t/topic/c1I7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录