Python 3.x 将张量变量初始化为numpyArray-减少和问题
我正在预处理一个numpy数组,并希望将其作为tensorflow变量输入。我尝试过遵循其他堆栈交换建议,但迄今为止没有成功。我想看看我在这里是否犯了什么特别的错误Python 3.x 将张量变量初始化为numpyArray-减少和问题,python-3.x,numpy,tensorflow,Python 3.x,Numpy,Tensorflow,我正在预处理一个numpy数组,并希望将其作为tensorflow变量输入。我尝试过遵循其他堆栈交换建议,但迄今为止没有成功。我想看看我在这里是否犯了什么特别的错误 npW = np.zeros((784,10)) npW[0,0] = 20 W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32)) sess = tf.InteractiveSession() tf.global_variables_ini
npW = np.zeros((784,10))
npW[0,0] = 20
W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
print("npsum", np.sum(npW))
print(tf.reduce_sum(W))
这就是结果。
我不知道为什么W变量的约化和保持为零。我在这里遗漏了什么吗?所以我对它进行了一些不同的测试,发现变量分配正确,但是,约化求和函数没有按预期工作。如果有人对此有任何解释,我们将不胜感激
npW = np.zeros((2,2))
npW[0,0] = 20
W = tf.Variable(npW, dtype = tf.float32)
A= tf.constant([[20,0],[0,0]])
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Train
print("npsum", np.sum(npW))
x=tf.reduce_sum(W,0)
print(x)
print(tf.reduce_sum(A))
print(W.eval())
print(A.eval())
这有产出
npsum 20.0
Tensor("Sum:0", shape=(2,), dtype=float32)
Tensor("Sum_1:0", shape=(), dtype=int32)
[[ 20. 0.],
[ 0. 0.]]
[[20 0],
[ 0 0]]
您需要了解Tensorflow不同于传统计算。首先,声明一个计算图。然后,通过图形运行操作 以您的示例为例,您有numpy变量:
npW = np.zeros((784,10))
npW[0,0] = 20
接下来,这些说明是tensorflow变量的定义,即计算图中的节点:
W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))
sum = tf.reduce_sum(W)
为了能够计算运算,您需要在图形中运行运算,并使用session,即:
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
result = sess.run(sum)
print(result) # print 20
另一种方法是调用eval而不是sess.run()
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
result = sess.run(sum)
print(result) # print 20
print(sum.eval()) # print 20