Keras 在进行迁移学习时如何重塑pytorch CNN模型的最后一层

Keras 在进行迁移学习时如何重塑pytorch CNN模型的最后一层,keras,neural-network,pytorch,transfer-learning,Keras,Neural Network,Pytorch,Transfer Learning,实际上,我正试图将keras结构复制到pytorch中。 这是凯拉斯建筑 base_model = InceptionV3(weights='imagenet', include_top=False) x = base_model.output x = Dense(512, activation='relu')(x) predictions = Dense(49*6,activation='sigmoid')(x) reshape=Reshape((49,6))(predictions) mod

实际上,我正试图将keras结构复制到pytorch中。 这是凯拉斯建筑

base_model = InceptionV3(weights='imagenet', include_top=False)
x = base_model.output
x = Dense(512, activation='relu')(x)
predictions = Dense(49*6,activation='sigmoid')(x)
reshape=Reshape((49,6))(predictions)
model = Model(inputs=base_model.input, outputs=reshape)
for layer in base_model.layers:
    layer.trainable = False
我想重塑netwrok的最后一层。我已经实施了迁移学习

model =  models.inception_v3(pretrained=True)

for param in model.parameters():
    param.requires_grad = False

num_ftrs = model.fc.in_features
我相信,如果我能用下面的体系结构连接resnet的最后一层,问题就可以解决了。但我不知道怎样才能把它们连接起来

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.fc1 = nn.Linear(num_ftrs, 512)
        self.fc2 = nn.Linear(512, 49*6)

    def forward(self, x):
        print (x.shape)
        x = x.view(-1,num_ftrs)
        #print (x.shape)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        x=torch.sigmoid(x.view(49,6))
        return x

任何想法,如何解决这个问题

你问什么或你的问题是什么还不是很清楚。也就是说,从对代码的初始检查来看,在我看来,您可能需要
num\u ftrs=model.fc.out\u功能
,并且由于它们在输出中有一个批处理维度,所以您可能希望在转发过程中使用
x.view(-1,49,6))
,而不是
x.view(49,6)
您需要将
num\u ftrs
传递到您的
\uuuu init\uuuu
中。之后,有几种连接网络的方法。最简单的方法可能是定义另一个模型,它是
CNN
的一个实例,可能像
model\u CNN=CNN(num\u ftrs)
那样,然后将初始网络的输出按如下方式传递…
output=model\u CNN(model(data))
。您也可以将
model
model\u cnn
包装在一个
torch.nn.顺序
模型中。