Python Tensorflow';s占位符初始化不同于tensorflow';s常量初始化。为什么?

Python Tensorflow';s占位符初始化不同于tensorflow';s常量初始化。为什么?,python,tensorflow,initialization,Python,Tensorflow,Initialization,我已经编写了两个函数,它们以不同的方式初始化tensorflow的变量。我不知道为什么结果不同。以下是第一个使用占位符进行初始化的函数: 第一功能 结果是: result = [[-1.98748544] [-2.76826248] [-0.78635415] [-2.77463846]] 第二功能 第二个函数使用tf.constant初始化变量: def linear_function(): np.random.seed(1) X = tf.constant(np.

我已经编写了两个函数,它们以不同的方式初始化tensorflow的变量。我不知道为什么结果不同。以下是第一个使用占位符进行初始化的函数:

第一功能 结果是:

result = [[-1.98748544]
 [-2.76826248]
 [-0.78635415]
 [-2.77463846]]
第二功能 第二个函数使用
tf.constant
初始化变量:

def linear_function():

    np.random.seed(1)

    X = tf.constant(np.random.randn(3,1), name ="X")
    W = tf.constant(np.random.randn(4,3), name ="X")
    b = tf.constant(np.random.randn(4,1), name ="X")
    Y = tf.add(tf.matmul(W,X), b)

    sess = tf.Session()
    result = sess.run(Y)

    sess.close()

    return result

print( "result = " + str(linear_function()))
结果:

result = [[-2.15657382]
 [ 2.95891446]
 [-1.08926781]
 [-0.84538042]]
有什么问题?它与np.random.seed(1)有关吗


谢谢。

在第一段代码中,提要是:

{W:np.random.randn(4,3), X:np.random.randn(3,1), b:np.random.randn(4,1)}
因此,首先为
W
生成一个随机值,然后为
X
生成一个随机值,然后为
b
生成一个随机值。但是,在第二个代码段中,随机值的顺序是
X
W
b
。由于生成随机数的顺序不同,因此值不同。例如,如果您在第一个代码段的
feed\u dict
中适当更改顺序,您将得到与第二个代码段相同的结果:

import tensorflow as tf
import numpy as np

def linear_function():
    np.random.seed(1)

    X = tf.placeholder(dtype = tf.float64, name='X')
    W = tf.placeholder(dtype = tf.float64, name='W')
    b = tf.placeholder(dtype = tf.float64, name='b')
    Y = tf.add(tf.matmul(W, X), b)

    sess = tf.Session()

    result = sess.run(Y, feed_dict={X:np.random.randn(3,1), W:np.random.randn(4,3), b:np.random.randn(4,1)})
    sess.close()
    return result

print( "result = " + str(linear_function()))
输出:

result=[-2.15657382]
[ 2.95891446]
[-1.08926781]
[-0.84538042]]

谢谢。为什么np.random如此麻烦:(@Muser基本上每个伪随机数生成器都是这样工作的。您可以使用
种子将其设置为一个众所周知的初始状态,因此如果您在之后执行完全相同的随机操作,您将得到相同的结果。但是,不同的随机操作序列(即使是不同顺序的同一组操作)将始终(或应该始终)产生不同的值。感谢您的解释。现在我可以正确使用np.random.seed。
import tensorflow as tf
import numpy as np

def linear_function():
    np.random.seed(1)

    X = tf.placeholder(dtype = tf.float64, name='X')
    W = tf.placeholder(dtype = tf.float64, name='W')
    b = tf.placeholder(dtype = tf.float64, name='b')
    Y = tf.add(tf.matmul(W, X), b)

    sess = tf.Session()

    result = sess.run(Y, feed_dict={X:np.random.randn(3,1), W:np.random.randn(4,3), b:np.random.randn(4,1)})
    sess.close()
    return result

print( "result = " + str(linear_function()))