gpt4 book ai didi

python - 如何在 Keras 中获取图层的权重?

转载 作者:IT老高 更新时间:2023-10-28 21:05:54 27 4
gpt4 key购买 nike

我使用的是 Windows 10、Python 3.5 和 tensorflow 1.1.0。我有以下脚本:

import tensorflow as tf
import tensorflow.contrib.keras.api.keras.backend as K
from tensorflow.contrib.keras.api.keras.layers import Dense

tf.reset_default_graph()
init = tf.global_variables_initializer()
sess = tf.Session()
K.set_session(sess) # Keras will use this sesssion to initialize all variables

input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')
dense1 = Dense(10, activation='relu')(input_x)

sess.run(init)

dense1.get_weights()

我得到错误:AttributeError: 'Tensor' object has no attribute 'weights'

我做错了什么,如何获得 dense1 的权重?我看过thisthis SO post,但我仍然无法使其工作。

最佳答案

如果你想得到所有层的权重和偏差,你可以简单地使用:

for layer in model.layers: print(layer.get_config(), layer.get_weights())

这将打印所有相关信息。

如果你希望权重直接返回为 numpy 数组,你可以使用:

first_layer_weights = model.layers[0].get_weights()[0]
first_layer_biases = model.layers[0].get_weights()[1]
second_layer_weights = model.layers[1].get_weights()[0]
second_layer_biases = model.layers[1].get_weights()[1]

等等

关于python - 如何在 Keras 中获取图层的权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43715047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com