python - 在 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))
推荐阅读
- python - 在 Python 3.7 中 Counter / defaultdict 如何排序?
- xml - 带有 if 语句的 Xsl + 向变量添加内容
- c - 决定 setgroups() 和 initgroups() 必须由超级用户调用的机制是什么?
- jq - jq:传递变量参数以用作过滤器
- php - 在 Woocommerce 中将未购买的商品分页为自定义我的帐户页面内容
- php - 从模仿者中抽象或隐藏 API 调用
- scala - Akka 文件上传 - 在收到请求结束之前发送 2xx 的“早期”响应
- reactjs - IE11 空响应
- python - 从 Python 中访问 mysql-py shell 命令
- javascript - 检查此 javascript 以制作 meme