【问题标题】:Feature extraction in Keras on last layersKeras 中最后一层的特征提取
【发布时间】:2020-08-12 22:57:49
【问题描述】:

我想在展平后保存图层的特征向量。我怎么做?作为输入,我想给出所有测试图像并让它预测结果,但在分类层之前,我需要提取网络学习的特征并将其保存为向量。这可能吗?

这是我的代码:

from keras.datasets import mnist
from keras.utils import to_categorical
from keras import layers
from keras import models

(train_img,train_label), (test_img, test_label) = mnist.load_data()

#preprocessing
train_img = train_img.reshape((60000,28,28,1))
train_img = train_img.astype('float32')/255

test_img = test_img.reshape((10000,28,28,1))
test_img = test_img.astype('float32')/255


train_label = to_categorical(train_label)
test_label = to_categorical(test_label)

# model

model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64,(3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64,(3,3),activation='relu'))
#check summary for output
#model.summary()

model.add(layers.Flatten())

# !!! I need the a vector of features that this layer learned!!!!
model.add(layers.Dense(64,activation='relu'))


model.add(layers.Dense(10,activation='softmax'))

#model.summary()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# training

model.fit(train_img, train_label, epochs=5, batch_size=64)

【问题讨论】:

    标签: python tensorflow machine-learning keras


    【解决方案1】:

    您可以为特定层设置名称:

    model.add(layers.Dense(64,activation='relu', name='features'))
    

    训练完成后,可以得到权重:

    model.get_layer('features').get_weights()[0]
    

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 2018-08-18
      • 2017-07-28
      • 2020-11-29
      • 1970-01-01
      • 2019-07-31
      • 2017-09-06
      • 2016-12-05
      • 2019-10-28
      相关资源
      最近更新 更多