Keras - 训练卷积网络,获得自动编码器输出

Keras - Train convolution network, get auto-encoder output

我想做的事情: 我想在两个 类 的 cifar10 数据集上训练一个卷积神经网络。然后一旦我得到我的拟合模型,我想获取所有层并重现输入图像。所以我想从网络中取回图像而不是分类。

到目前为止我做了什么:

def copy_freeze_model(model, nlayers = 1):
    new_model = Sequential()
    for l in model.layers[:nlayers]:
      l.trainable = False
      new_model.add(l)
    return new_model

numClasses = 2
(X_train, Y_train, X_test, Y_test) = load_data(numClasses)
#Part 1
rms = RMSprop()
model = Sequential()
#input shape: channels, rows, columns
model.add(Convolution2D(32, 3, 3, border_mode='same',
                        input_shape=(3, 32, 32)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation("relu"))
model.add(Dropout(0.5))
#output layer
model.add(Dense(numClasses))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer=rms,metrics=["accuracy"])

model.fit(X_train,Y_train, batch_size=32, nb_epoch=25,
          verbose=1, validation_split=0.2,
          callbacks=[EarlyStopping(monitor='val_loss', patience=2)])
print('Classifcation rate %02.3f' % model.evaluate(X_test, Y_test)[1])

##pull the layers and try to get an output from the network that is image.

newModel = copy_freeze_model(model, nlayers = 8)
newModel.add(Dense(1024))

newModel.compile(loss='mean_squared_error', optimizer=rms,metrics=["accuracy"])
newModel.fit(X_train,X_train, batch_size=32, nb_epoch=25,
          verbose=1, validation_split=0.2,
          callbacks=[EarlyStopping(monitor='val_loss', patience=2)])
preds = newModel.predict(X_test)

我也是这样:

input_shape=(3, 32, 32)

这是否意味着 3 通道 (RGB) 32 x 32 图像?

我建议你的是一个堆叠卷积自动编码器。这使得去池化层和反卷积成为强制性的。在这里你可以找到Theano(Keras建立在其上)的总体思路和代码:

https://swarbrickjones.wordpress.com/2015/04/29/convolutional-autoencoders-in-pythontheanolasagne/

可以在此处找到所需层的示例定义:

https://github.com/fchollet/keras/issues/378