Keras layer.weights和layer.get_weights()给出不同的值 [英] Keras layer.weights and layer.get_weights() give different values
问题描述
我的Keras模型具有Dense层,我需要访问这些层的权重和偏差值.我可以使用get_weights()方法访问它们.它会返回给我预期的大小和权重矩阵(权重为57X50).
My Keras model have Dense layers which I need to access the weights and bias values. I can access them using get_weights() method. It returns me expected sized matrices (57X50 for the weights) for weights and biases.
model.layers[0].get_weights()[0]
但是,以下代码段为我提供了大小相同但大小不同的矩阵.
However the following code snippet gives me same sized matrices with different values.
import tensorflow as tf
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(model.layers[0].weights[0]))
在第二种方法中,由于所有模型的全零和权重与get_weights()方法的输出不同,因此会返回偏差值.
In the second method bias values are returned as all zeros for all models and weights are different than the output of get_weights() method.
您是否知道哪种方法正确,第二种方法究竟能做什么?
Do you have any idea which way is correct and what exactly the second method does?
推荐答案
使用init_op
初始化所有可训练变量,这意味着偏差为零,模型的其他权重为随机值.试试:
With init_op
, you initialize all trainable variables, which means zeros for biases and random values for the other weights of your model. Try:
import keras.backend as K
with K.get_session() as sess:
print(sess.run(model.layers[0].weights[0]))
这篇关于Keras layer.weights和layer.get_weights()给出不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!