如何在 Keras 中获取张量值?

How to get a tensor value in Keras?

我想比较 2 张图片。

我采用的方法是对它们进行编码。

然后计算两个编码向量之间的角度以进行相似性度量。

下面的代码用于使用 CNN 和 Keras 对图像进行编码和解码。

但是,我需要得到张量的值encoded

如何实现?

非常感谢。

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K

input_img = Input(shape=(28, 28, 1))  
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
#----------------------------------------------------------------#
# How to get the values of the tensor "encoded"?                   #
#----------------------------------------------------------------#
x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

.....

autoencoder.fit(x_train, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test, x_test),
                callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

如果我对你的问题理解正确,你想从卷积自动编码器中获得 128 维编码表示,用于图像比较?

您可以做的是在网络的编码器部分创建一个参考,训练整个自动编码器,然后使用编码器参考的权重对图像进行编码。

放这个:

self.autoencoder = autoencoder self.encoder = Model(inputs=self.autoencoder.input, outputs=self.autoencoder.get_layer('encoded').output)

autoencoder.compile()

之后

并创建编码:

encoded_img = self.encoder.predict(input)

为了获得中间输出,您需要创建一个单独的模型,其中包含到该点为止的计算图。对于您的情况,您可以:

encoder = Model(input_img, encoded)

使用 autoencoder 完成训练后,您可以 encoder.predict 这将 return 您得到中间编码结果。您还可以像保存任何其他模型一样单独保存模型,而不必每次都进行训练。简而言之,Model 是构建计算图的层的容器。