【问题标题】:Initialize tensor Variable to numpyArray - Reduced Sum Issues将张量变量初始化为 numpy 数组 - 减少总和问题
【发布时间】:2017-12-09 15:59:38
【问题描述】:

我正在预处理一个 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 变量的减少总和仍然为零。我在这里错过了什么吗?

【问题讨论】:

    标签: python-3.x numpy tensorflow


    【解决方案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)
    

    并且为了能够计算操作,您需要使用会话通过图形运行操作,即:

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

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

    print(sum.eval()) # print 20
    

    【讨论】:

      【解决方案2】:

      所以我对它进行了一些不同的测试,发现变量被正确分配,但是,reduce_sum 函数没有按预期工作。如果有人对此有解释,将不胜感激。

        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]]  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        • 2010-10-31
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        相关资源
        最近更新 更多