[英]Feature extraction in Keras on last layers
我想在展平后保存圖層的特征向量。 我怎么做? 作為輸入,我想給出所有測試圖像並讓它預測結果,但在分類層之前,我需要提取網絡學習的特征並將其保存為向量。 那可能嗎?
這是我的代碼:
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)
您可以為特定圖層設置名稱:
model.add(layers.Dense(64,activation='relu', name='features'))
訓練完成后,您可以獲得權重:
model.get_layer('features').get_weights()[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.