如何在 Tensorflow 中打印权重?

use*_*232 6 python tensorflow

我正在尝试获取我的 hidden_​​layer2 的权重矩阵并打印它。似乎我能够获得权重矩阵,但我无法打印它。

使用时tf.Print(w, [w])不打印任何内容。使用时,print(tf.Print(w,[w])它至少会打印有关张量的信息:

Tensor("hidden_layer2_2/Print:0", shape=(3, 2), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

我也尝试tf.Print()with -Statement之外使用,结果相同。

完整代码在这里,我只是在前馈神经网络中处理随机数据:https : //pastebin.com/KiQUBqK4

我的代码的一部分:

hidden_layer2 = tf.layers.dense(
        inputs=hidden_layer1,
        units=2,
        activation=tf.nn.relu,
        name="hidden_layer2")


with tf.variable_scope("hidden_layer2", reuse=True):
        w = tf.get_variable("kernel")
        tf.Print(w, [w])
        # Also tried tf.Print(hidden_layer2, [w])
Run Code Online (Sandbox Code Playgroud)

Tim*_*lin 7

为 TensorFlow 2.X 更新

从TensorFlow 2.0(>=2.0)开始,由于Sessionobject已经被移除,推荐的高层后端是Keras,所以获取权重的方法是:

from tensorflow.keras.applications import MobileNetV2

model = MobileNetV2(input_shape=[128, 128, 3], include_top=False) #or whatever model
print(model.layers[0].get_weights()[0])
Run Code Online (Sandbox Code Playgroud)


小智 0

尝试这样做,

w = tf.get_variable("kernel")
print(w.eval())
Run Code Online (Sandbox Code Playgroud)