Python Tensorflow和Numpy产生不同的结果

Python Tensorflow和Numpy产生不同的结果,python,numpy,tensorflow,keras,Python,Numpy,Tensorflow,Keras,我已经看到Tensorflow在稠密层中使用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 =

我已经看到Tensorflow在稠密层中使用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)

y=np.random.rand(8500)
w=np.random.normal(大小=(y.shape[1],128))
y_tf=tf.常量(y,dtype='float32')
yy=tf.keras.layers.density(128,激活=relu',权重=[w],使用_bias=False)
y_tf=tf.keras.layers.Input(张量=y_tf)
y_tf=yy(y_tf)
使用tf.Session()作为sess:
sess.run(tf.global\u variables\u initializer())
res=sess.run(fetches=y\u tf)
y=np.matmul(y,w)

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

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)