首页 > 解决方案 > 在 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 做到这一点?

标签: pythontensorflowkerasneural-network

解决方案


直接传入一个 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))

推荐阅读