【问题标题】:How to get a tensor value in Keras?如何在 Keras 中获得张量值?
【发布时间】:2018-11-08 19:39:06
【问题描述】:

我想比较两张图片。

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

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

以下代码用于使用带有 Keras 的 CNN 对图像进行编码然后解码。

但是,我需要获取张量 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')])

【问题讨论】:

    标签: python keras tensor


    【解决方案1】:

    如果我正确理解您的问题,您是否希望从卷积自动编码器中获得 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)

    【讨论】:

    • 谢谢你,丹尼尔。有用。我输入的代码是:encoder2 = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer("max_pooling2d_3").output) y = encoder2.predict(x_test)
    • 酷!高兴听到! :)
    【解决方案2】:

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

    encoder = Model(input_img, encoded)
    

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

    【讨论】:

    • 谢谢你,努里克。您建议的答案是正确的。代码为:encoder = Model(input_img, encoded) y = encoder.predict(x_test)
    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2021-12-16
    • 2021-11-03
    • 1970-01-01
    • 2018-07-25
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多