[英]Feature extraction in Keras on last layers
I want to save a feature vector of the layer after flatten.我想在展平后保存图层的特征向量。 how do i do that?我怎么做? as input, i want to give all the test images and let it to predict the results but before the classification layer, i need to extract the features that network learn and save it as a vector.作为输入,我想给出所有测试图像并让它预测结果,但在分类层之前,我需要提取网络学习的特征并将其保存为向量。 is that possible?那可能吗?
here is my code:这是我的代码:
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)
You can set a name to the specific layer:您可以为特定图层设置名称:
model.add(layers.Dense(64,activation='relu', name='features'))
After training is done, you can get weights:训练完成后,您可以获得权重:
model.get_layer('features').get_weights()[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.