MindSpore: 解决'ValueError: For 'BatchNorm2d', the in_shape must have 4 dims, but got 2.' 错误
MindSpore: 解决'ValueError: For 'BatchNorm2d', the in_shape must have 4 dims, but got 2.' 错误
该错误提示是由于代码中使用了BatchNorm2d算子,但是输入的数据维度不符合要求。因为BatchNorm2d需要输入的数据维度为四维,即[batch_size, channel, height, width],而当前代码中的输入数据x只有两维,缺少batch_size和channel两个维度。因此,需要将输入数据x的维度补充完整,可以使用unsqueeze函数将x的维度扩展为[batch_size, channel, height, width],修改后的代码如下:
class my_net(nn.Cell):
# 定义算子
def __init__(self):
super(my_net, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, stride=1, pad_mode='valid')
self.bn1 = nn.BatchNorm2d(num_features=32)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, pad_mode='valid')
self.bn2 = nn.BatchNorm2d(num_features=64)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=5, stride=1, pad_mode='valid')
self.bn3 = nn.BatchNorm2d(num_features=128)
self.relu = nn.ReLU() # 激活函数
self.pool = nn.MaxPool2d(kernel_size=2,stride=2)
self.flatten = nn.Flatten()
#self.dropout = nn.Dropout(0.2)
self.fc1 = nn.Dense(10368, 2048) # 全连接层
self.fc2 = nn.Dense(2048, 34) # 全连接层
# 建构网络
def construct(self, x):
x = x.unsqueeze(1)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu(x)
x = self.pool(x)
x = self.flatten(x)
x = self.fc1(x)
x = self.relu(x)
#x = self.dropout(x)
x = self.fc2(x)
return x
在代码中,我们添加了x = x.unsqueeze(1)语句,将输入数据x的维度扩展为[batch_size, channel, height, width],其中batch_size默认为1,channel为1,height和width为原始数据x的维度。
通过上述修改,就可以解决'ValueError: For 'BatchNorm2d', the in_shape must have 4 dims, but got 2.' 错误。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mHBx 著作权归作者所有。请勿转载和采集!