将张量变量初始化为numpyArray - 减少总和问题

时间:2017-12-09 15:59:39

标签: 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_initializer().run()

  print("npsum", np.sum(npW))
  print(tf.reduce_sum(W))

这就是结果。

npsum 20.0
Tensor("Sum:0", shape=(), dtype=float32)

我不知道为什么W变量的总和保持为零。我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:1)

您需要了解Tensorflow与传统计算不同。首先,您声明一个计算图。然后,您通过图表运行操作。

举个例子,你有你的numpy变量:

npW = np.zeros((784,10))
npW[0,0] = 20

接下来,这些指令是张量流变量的定义,即计算图中的节点:

W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))
sum = tf.reduce_sum(W)

为了能够计算操作,你需要通过图形运行op,并使用sesssion,即:

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
result = sess.run(sum)
print(result) # print 20

另一种方法是调用eval而不是sess.run()

print(sum.eval()) # print 20

答案 1 :(得分:0)

所以我测试了一下,发现变量被正确分配,但是,reduce_sum函数没有按预期工作。如果任何人对此有解释,那将非常感激。

1 - Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt"); //Read data from file in int[].

2 - Integer[] recur(Integer[] entries_p){} //change it as int[] recur(int[] entries_p) 

这有输出

  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())