简体   繁体   中英

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM