简体   繁体   English

如何在预测阶段获得所有 output keras 层(特征图)?

[英]How can i get the all output keras layers (features maps) during prediction phase?

I tried to take cfiar data set and to try to get the feature map of every output giving as an input one of the test images.我尝试获取 cfiar 数据集并尝试获取每个 output 的特征 map 作为测试图像的输入之一。

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck']

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
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'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

model.compile(optimizer='adam',
          loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
          metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                validation_data=(test_images, test_labels))

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

layer_input = test_images[0]                  

for i in range(len(model.layers)):
    get_layer_output = K.function(inputs = model.layers[i].input, outputs = model.layers[i].output)
    print(get_layer_output(layer_input))
    layer_input = model.layers[i].output

My feeling is that i misunderstand something regarding how to set the input and also how to take the output during the prediction.我的感觉是我误解了一些关于如何设置输入以及如何在预测期间采用 output 的内容。

You should set the input to model.layers[0].input if you are using Sequential model.如果您使用的是Sequential model,则应将输入设置为model.layers[0].input .input。


First , expand the dimensionality of the Test Input to include the Batch_Size:首先,扩展测试输入的维度包含 Batch_Size:

layer_input = test_images[0]    
plt.imshow(layer_input)   # Plot Test Image
layer_input = tf.expand_dims(layer_input,0)   # Add prefix of Batch Size 
print(layer_input.shape)  # Prints  : (1, 32, 32, 3)

Output : Output

original_image

Modified code for plotting:修改后的绘图代码:

for i in range(len(model.layers)):
    get_layer_output = K.function(inputs = model.layers[0].input, outputs = model.layers[i].output)

    get_1_output = get_layer_output(layer_input)
    # print(get_1_output.shape) << Use this to check if the Output shape matches the shape of Model.summary()

    if get_1_output.ndim == 4:             # Check for Dimensionality to plot ONE feature map (Batch size, Length, Width
      plt.imshow(get_1_output[0][:,:,:3])  # Plots the output of Conv2D and MaxPooling
    else:
      print(get_1_output)   # If not Image, ie. Array, print the Values

    plt.show()

Output : Output

特征图


I hope I answered your question.我希望我回答了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras model 特征 output 在预测单个图像期间全为零 - Keras model feature output is all zeros during prediction of a single image output层可以在训练过程中用keras实时获取吗? - Can output layers be taken during the training in real time with keras? 如何批量获取中间Keras层的输出? - How to get output of intermediate Keras layers in batches? Keras / Tensorflow:有效获取所有图层的预测或输出 - Keras/Tensorflow: Get predictions or output of all layers efficiently 如何获得QGis向量层中所有层的特征 - How to get features of all the layers in QGis vector layer 如何在 keras 的 LSTM 自动编码器中获取中间层的输出 - How to get output of middel layers in LSTM autoencoder in keras 我怎样才能得到所有的预测概率值? - How can i get all the prediction probability value? 在预测期间从 Keras/Tensorflow 获取中间输出并在传递到下一层之前修改值 - Get intermediate output from Keras/Tensorflow during prediction and modify the value before passing to next layer 在 Keras 中,如何在预测期间使用自定义回调 - In Keras, how to use custom callbacks during prediction 如何在 Keras 中获取深度 RNN 的所有中间层的输出 - How to get outputs of all intermediate layers of a deep RNN in Keras
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM