tensorflow:如何分配更新的 numpy [英] tensorflow: how to assign an updated numpy

查看:25
本文介绍了tensorflow:如何分配更新的 numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 tensorflow 的新手,我正在尝试了解它的行为;我试图定义会话范围之外的所有操作,以优化计算时间.在以下代码中:

I'm new in tensorflow and I'm trying to understand its behaviors; I'm trying to define all the operations outside the session scope so to optimize the computation time. In the following code:

import tensorflow as tf
import numpy as np  
Z_tensor = tf.Variable(np.float32( np.zeros((1, 10)) ), name="Z_tensor")
Z_np = np.zeros((1,10))
update_Z = tf.assign(Z_tensor, Z_np)

Z_np[0][2:4] = 4

with tf.Session() as sess:
    sess.run(Z_tensor.initializer)
    print(Z_tensor.eval())
    print(update_Z.eval(session=sess))

我获得作为输出:

[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

相反,我期望作为输出:

Instead I expected as output:

[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 4. 4. 0. 0. 0. 0. 0. 0.]]

似乎 Z_np 数组在赋值操作中没有更新,我不明白为什么.不是操作

It seems that the Z_np array is not updated in the assign operation and I don't understand why. Doesn't the operation

  update_Z = tf.assign(Z_tensor, Z_np)

Z_np建立链接?

推荐答案

当您使用 tf.assign 时,它需要张量作为第二个参数.因为你提供了一个 Numpy 数组,它会自动将它提升为一个 CONSTANT 张量,并在那一刻将它放在图中.因此,您对 Numpy 数组所做的任何更改都不会对 TensorFlow 图产生任何影响.为了获得所需的功能,您应该使用占位符:

When you use tf.assign, it expects a tensor as the second argument. Because you provided a Numpy array, it automatically promotes it to a CONSTANT tensor and places it in the graph at that moment. Because of this, no changes you make to the Numpy array will have any effect on the TensorFlow graph. In order to get the desired functionality, you should use a placeholder:

Z_placeholder = tf.placeholder(tf.float32, Z_np.shape)

with tf.Session() as sess:
    sess.run(Z_tensor.initializer)
    print(Z_tensor.eval(feed_dict={Z_placeholder: Z_np}, session=sess))
    Z_np[0][2:4] = 4
    print(Z_tensor.eval(feed_dict={Z_placeholder: Z_np}, session=sess))

这篇关于tensorflow:如何分配更新的 numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆