Reputation: 125
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)
Upvotes: 0
Views: 778
Reputation: 2316
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]
Upvotes: 1