首页 > 解决方案 > 为什么 get_tensor_by_name 无法正确获取 tf.keras.layers 定义的层权重

问题描述

我尝试tf.keras.layers通过使用get_tensor_by_namein获得层的权重tensorflow。代码如下

# encoding: utf-8
import tensorflow as tf

x = tf.placeholder(tf.float32, (None,3))
h = tf.keras.layers.dense(3)(x)
y = tf.keras.layers.dense(1)(h)

for tn in tf.trainable_variables():
    print(tn.name)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
w = tf.get_default_graph().get_tensor_by_name("dense/kernel:0")
print(sess.run(w))

重量的名称是dense/kernel:0。但是,输出sess.run(w)很奇怪

[( 10,) ( 44,) ( 47,) (106,) (111,) ( 98,) ( 58,) (108,) (111,) ( 99,)
 ( 97,) (108,) (104,) (111,) (115,) (116,) ( 47,) (114,) (101,) 
 ... ]

这不是一个浮点数组。事实上,如果我用它tf.layers.dense来定义网络,一切都很好。所以我的问题是如何tf.keras.layers通过正确使用张量名称来获得定义的层的权重。

标签: tensorflowkeras

解决方案


您可以get_weights()在图层上使用来获取特定图层的权重值。这是您的案例的示例代码:

import tensorflow as tf

input_x = tf.placeholder(tf.float32, [None, 3], name='x')    
dense1 = tf.keras.Dense(3, activation='relu')
l1 = dense1(input_x)
dense2 = tf.keras.Dense(1)
y = dense2(l1)

weights = dense1.get_weights()

可以使用 Keras API 以更简单的方式完成,如下所示:

def mymodel():
    i = Input(shape=(3, ))
    x = Dense(3, activation='relu')(i)
    o = Dense(1)(x)

    model = Model(input=i, output=o)
    return model


model = mymodel()

names = [weight.name for layer in model.layers for weight in layer.weights]
weights = model.get_weights()

for name, weight in zip(names, weights):
    print(name, weight.shape)

此示例获取模型每一层的权重矩阵。


推荐阅读