我正在使用Keras和Tensorflow。 Keras层具有方法“get_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.
我的Keras版本是2.0.6。我的Tensorflow是1.3.0。谢谢!
答案 0 :(得分:3)
方法get_weights()
确实只是评估属性weights
给出的Tensorflow张量的值。我在get_weights()
和sess.run(weight)
之间得到不同值的原因是我指的是两个不同会话中的变量。当我运行vgg19 = VGG19(weights='imagenet', include_top=False)
时,Keras已经创建了一个Tensorflow会话,并在该会话中使用预先训练的值初始化权重。然后我通过运行sess = tf.Session()
创建了另一个名为sess的Tensorflow会话。在此会话中,权重尚未初始化。然后当我运行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