【问题标题】:Tensorflow and Numpy produce different resultsTensorflow 和 Numpy 产生不同的结果
【发布时间】:2020-05-25 07:14:38
【问题描述】:

我已经看到here 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)

【问题讨论】:

    标签: python numpy tensorflow keras


    【解决方案1】:

    你对这个操作的理解是正确的,你的代码也几乎是正确的。 尝试替换

    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)
    

    防止随机初始化权重,测试将通过。

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2019-09-25
      • 2018-05-23
      相关资源
      最近更新 更多