在Keras中指定参数列表

彼得·史密斯

我为权重和偏差定义了两个变量偏差。如何在Keras中使用这些变量?基本上,我想做的事情如下:

w = tf.get_variable("weight", shape=[784, 512], trainable=True)
b = tf.get_variable("bias", shape=[512], trainable=True)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,), weights=w, biases=b))

有谁知道如何用Keras做到这一点?

霸王龙

直接传递一个Numpy数组,Keras将为您处理张量转换;此外,还可以weights处理“常规”权重和偏差。完整示例如下:

from keras.layers import Dense
from keras.models import Sequential
import numpy as np

input_shape = (784,)
dense_dim = 512

W = np.random.randn(input_shape[0], dense_dim)
b = np.random.randn(dense_dim)

model = Sequential()
model.add(Dense(dense_dim, activation='relu', input_shape=input_shape, weights=[W, b]))

确保按层期望的顺序传递权重-可以直接检查权重

print(model.layers[0].weights)
[<tf.Variable 'dense_1/kernel:0' shape=(784, 512) dtype=float32_ref>,
 <tf.Variable 'dense_1/bias:0' shape=(512,) dtype=float32_ref>]

建立模型设置权重:使用layer.set_weights()

model.layers[0].set_weights([W, b]) # again, mind the order

使用tf.get_variable:不能做;使用来自set_weights() 源代码的代码K.batch_set_value代码对原始数组值(而不是张量)进行操作。如果您的目标是跟踪图层的权重变量,则可以直接直接获取并用于K.eval()获取其值(或.numpy()对于TF2):

import keras.backend as K
dense1_weights, dense1_biases = model.layers[0].weights

if tf.__version__[0] == '2':
    print(dense1_weights.numpy())
else:
    print(K.eval(dense1_weights))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章