将 Keras 模型转换为 PyTorch(形状不能相乘)

问题描述 投票:0回答:1

我已经使用 Keras 制作了一个模型,但现在需要将其转换为 PyTorch 兼容版本。

input_shape = 200, 100, 1

def make_model():
    return keras.models.Sequential([
        keras.layers.Conv2D(32, kernel_size=(2, 2), activation='relu', input_shape=input_shape),
        keras.layers.MaxPooling2D(pool_size=(2, 2)),
        keras.layers.Dropout(0.2),
        keras.layers.Flatten(),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(64, activation='relu'),
        keras.layers.Dense(3, activation='sigmoid'),
    ])
    
model = make_model()

model.summary()

Model: "sequential_164"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d_16 (Conv2D)          (None, 199, 99, 32)       160       
                                                                 
 max_pooling2d_16 (MaxPooli  (None, 99, 49, 32)        0         
 ng2D)                                                           
                                                                 
 dropout_66 (Dropout)        (None, 99, 49, 32)        0         
                                                                 
 flatten_23 (Flatten)        (None, 155232)            0         
                                                                 
 dense_322 (Dense)           (None, 128)               19869824  
                                                                 
 dense_323 (Dense)           (None, 51)                6579      
                                                                 
=================================================================
Total params: 19876563 (75.82 MB)
Trainable params: 19876563 (75.82 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________

这是我的 PyTorch 方法...

class MyCNN(nn.Module):
    def __init__(self):
        super(CustomCNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=(2, 2))
        self.pool = nn.MaxPool2d(2)
        self.dropout = nn.Dropout(0.2)
        self.fc1 = nn.Linear(155232, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 3)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool(x)
        x = self.dropout(x)
        x = torch.flatten(x, start_dim=1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.softmax(self.fc3(x))
        return x

虽然 Keras 模型训练得很好,但使用 PyTorch 时我收到此错误:

RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x4851 and 155232x128) 

我认为这个错误很奇怪,因为我使用与 Keras 相同的属性。

keras pytorch conv-neural-network max-pooling
1个回答
0
投票

而不是

x = torch.flatten(x, start_dim=1)
 x = torch.flatten(x)
是正确的版本

© www.soinside.com 2019 - 2024. All rights reserved.