python - Tensorflow 和 Numpy 产生不同的结果
问题描述
我在这里看到Tensorflow 在 Dense 层中使用 matmul 。我尝试在 Numpy 中做同样的事情,但它会产生不同的结果。
y = np.random.rand(8, 500)
w = np.random.normal(size=(y.shape[1], 128))
y_tf = tf.constant(y, dtype='float32')
yy = tf.keras.layers.Dense(128, activation='relu', weights=[w], use_bias=False)
y_tf = tf.keras.layers.Input(tensor=y_tf)
y_tf = yy(y_tf)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(fetches=y_tf)
y = np.matmul(y, w)
y[y<0] = 0 # relu
np.testing.assert_almost_equal(y, res, decimal=3)
解决方案
你对这个操作的理解是正确的,你的代码几乎是正确的。尝试更换
yy = tf.keras.layers.Dense(128, activation='relu', weights=[w], use_bias=False)
和
yy = tf.keras.layers.Dense(128, activation=None, kernel_initializer=lambda *args, **kwargs: w, use_bias=False)
以防止权重随机初始化,测试将通过。
推荐阅读
- guice - Google Guice:公开一个命名对象,但在没有名称的模块中保持它可用
- kubernetes - OpenEBS 是否支持 arm64 架构?
- sql - Oracle - 来自带有 * 参数的多个表的记录
- javascript - Vue JS 在生产模式下的行为不同
- node.js - Node 的 promisify 不适用于基于回调的函数
- android - 当有新的孩子添加到 Firebase 实时数据库时,如何获得通知?(我想使用android服务而不是FCM)
- sql - 如何编写一个 SQL 查询,根据条件从现有列中的两个填充列
- excel - 输入文本时如何在 Excel 中创建自动组合 URL?
- java - mono.zip 功能未按预期工作
- html - 两个不同图像的动画和变化