首页 文章

在添加到keras中的(预训练/未训练的)神经网络的中间层之后训练softmax层

提问于
浏览
1

我想在keras中为cifar10数据集训练2个模型 . 首先,从头开始(模型1),然后通过微调预训练模型(模型2) . 我使用以下代码来做到这一点:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
import numpy as np
import os
from keras.models import load_model

#model 1
input_shape = (32, 32, 3)
model1 = Sequential()
model1.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
model1.add(Conv2D(64, (3, 3), activation='relu'))
model1.add(MaxPooling2D(pool_size=(2, 2)))
model1.add(Dropout(0.25))
model1.add(Flatten())
model1.add(Dense(128, activation='relu'))
model1.add(Dropout(0.5))
model1.add(Dense(10, activation='softmax'))
#... training

#model 2
kmodel = load_model('cifar10\\cifar10.h5')
model2=Sequential()
for i in range (len(kmodel.layers)):
    model2.add(kmodel.layers[i])

我想知道:

In model 1:

如何在一些中间层之后添加 softmax 层( model1.add(Dense(10, activation='softmax')) ),以便对于每个新的 softmax 层,我只与前一层连接而且与下一层没有连接?

In model 2:

如何将 softmax 层添加到中间层(即第2层,第4层,第7层),我还有上述条件的连接? (当然我应该冻结所有的 kmodel 图层,然后训练新的 softmax 图层)

1 回答

  • 1

    这里的限制是Keras的 Sequential() 运算符,它允许您只对线性堆叠图层 .

    为了避免这种情况,我们可以通过更直接(但更丑陋)的方式来指定模型,as described here . 对于您的代码,它看起来像这样:

    input_shape = (32, 32, 3)
    
    x = Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape)(inputs)
    x = Conv2D(64, kernel_size=(3, 3),activation='relu',input_shape=input_shape)(x)
    ...
    predictions = Dense(10, activation='softmax')(x)
    

    然后,您可以简单地将中间层中的预测指定为

    input_shape = (32, 32, 3)
    
    x = Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape)(inputs)
    x = Conv2D(64, kernel_size=(3, 3),activation='relu',input_shape=input_shape)(x)
    ...
    
    # do the splitting at some random point of your choice
    predictions_intermediary = Dense(10, activation='softmax')(x)
    # regular next layer
    x = Dense(128, activation='relu')(x) 
    predictions = Dense(10, activation='softmax')(x)
    

    令人遗憾的是,我不熟悉Keras告诉你它如何适用于预训练模型,但我假设您可以以某种方式类似地定义预训练模型,然后像前面的例子那样指定可训练层 .

    请注意,您的“共享与拆分”问题在这里已经过时,因为创建不同的图层/操作会自动创建不同的权重矩阵,因此您不必担心此处有共享权重(在任何情况下都无法使用,如果与softmax输入形状相比,您在下一个输入图层中有不同的输入尺寸 .

相关问题