Keras 权重和 get_weights() 显示不同的值

Ye_*_*Ye_ 1 keras tensorflow

我在 Tensorflow 中使用 Keras。Keras 层有一个方法“get_weights()”和一个属性“weights”。我的理解是“权重”输出权重的 Tensorflow 张量,“get_weights()”评估权重张量并将值输出为 numpy 数组。然而,两者实际上向我展示了不同的价值观。这是要复制的代码。

from keras.applications.vgg19 import VGG19
import tensorflow as tf

vgg19 = VGG19(weights='imagenet', include_top=False)

vgg19.get_layer('block5_conv1').get_weights()[0][0,0,0,0]
#result is 0.0028906602, this is actually the pretrained weight

sess = tf.Session()

sess.run(tf.global_variables_initializer())
#I have to run the initializer here. Otherwise, the next line will give me an error
sess.run(vgg19.get_layer('block5_conv1').weights[0][0,0,0,0])
#The result here is -0.017039195 for me. It seems to be a random number each time.
Run Code Online (Sandbox Code Playgroud)

我的 Keras 版本是 2.0.6。我的 Tensorflow 是 1.3.0。谢谢!

Ye_*_*Ye_ 5

该方法get_weights()实际上只是评估属性给出的 Tensorflow 张量的值weights。我在get_weights()和之间得到不同值的原因sess.run(weight)是我指的是两个不同会话中的变量。当我运行时vgg19 = VGG19(weights='imagenet', include_top=False),Keras 已经创建了一个 Tensorflow 会话并在该会话中使用预先训练的值初始化了权重。然后我通过运行创建了另一个名为 sess 的 Tensorflow 会话sess = tf.Session()。在此会话中,权重尚未初始化。然后当我运行时sess.run(tf.global_variables_initializer()),随机数被分配给这个会话中的权重。所以关键是确保你在使用 Tensorflow 和 Keras 时使用同一个会话。以下代码显示get_weights()sess.run(weight)给出相同的值。

import tensorflow as tf
from keras import backend as K
from keras.applications.vgg19 import VGG19

sess = tf.Session()
K.set_session(sess)

vgg19 = VGG19(weights='imagenet', include_top=False)

vgg19.get_layer('block5_conv1').get_weights()[0][0,0,0,0]
#result is 0.0028906602, this is actually the pretrained weight

sess.run(vgg19.get_layer('block5_conv1').weights[0][0,0,0,0])
#The result here is also 0.0028906602
Run Code Online (Sandbox Code Playgroud)