Python Tensorflow:如何修改张量中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37071788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:46:13  来源:igfitidea点击:

Tensorflow: How to modify the value in tensor

pythonnumpytensorflow

提问by user3030046

Since I need to write some preprocesses for the data before using Tensorflow to train models, some modifications on the tensoris needed. However, I have no idea about how to modify the values in tensorlike the way using numpy.

由于我需要在使用 Tensorflow 训练模型之前对数据进行一些预处理,因此需要对其进行一些修改tensor。但是,我不知道如何tensor像使用numpy.

The best way of doing so is that it is able to modify tensordirectly. Yet, it seems not possible in the current version of Tensorflow. An alternative way is changing tensorto ndarrayfor the process, and then use tf.convert_to_tensorto change back.

这样做的最好方法是它能够tensor直接修改。然而,在当前版本的 Tensorflow 中似乎不可能。另一种方法是改变tensorndarray该进程,然后用tf.convert_to_tensor改回来。

The key is how to change tensorto ndarray.
1) tf.contrib.util.make_ndarray(tensor): https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray
It seems the easiest way as per the document, yet I cannot find this function in the current version of the Tensorflow. Second, the input of it is TensorProtorather than tensor.
2) Use a.eval()to copy ato another ndarray
Yet, it works only at using tf.InteractiveSession()in notebook.

关键是如何改变tensorndarray
1)tf.contrib.util.make_ndarray(tensor)https: //www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray
根据文档,这似乎是最简单的方法,但我在当前版本中找不到此功能的 Tensorflow。其次,它的输入是TensorProto而不是tensor
2)a.eval()用于复制a到另一个ndarray
然而,它仅适用于tf.InteractiveSession()在笔记本中使用。

A simple case with codes shows below. The purpose of this code is making that the tfchas the same output as npcafter the process.

下面是一个带有代码的简单案例。此代码的目的是使tfc具有与npc处理后相同的输出。

HINT
You should treat that tfcand npcare independent to each other. This meets the situation that at first the retrieved training data is in tensorformat with tf.placeholder().

提示
您应该对待它tfc并且npc彼此独立。这满足了首先检索到的训练数据tensor格式为tf.placeholder().



Source code

源代码

import numpy as np
import tensorflow as tf
tf.InteractiveSession()

tfc = tf.constant([[1.,2.],[3.,4.]])
npc = np.array([[1.,2.],[3.,4.]])
row = np.array([[.1,.2]])
print('tfc:\n', tfc.eval())
print('npc:\n', npc)
for i in range(2):
    for j in range(2):
        npc[i,j] += row[0,j]

print('modified tfc:\n', tfc.eval())
print('modified npc:\n', npc)


Output:

输出:

tfc:
[[ 1. 2.]
[ 3. 4.]]
npc:
[[ 1. 2.]
[ 3. 4.]]
modified tfc:
[[ 1. 2.]
[ 3. 4.]]
modified npc:
[[ 1.1 2.2]
[ 3.1 4.2]]

tfc:
[[ 1. 2.]
[ 3. 4.]]
npc:
[[ 1. 2.]
[ 3. 4.]]
修改 tfc:
[[ 1. 2.]
[ 3. 4.]]
修改npc:
[[ 1.1 2.2]
[ 3.1 4.2]]

采纳答案by Sung Kim

Use assign and eval (or sess.run) the assign:

使用分配和评估(或 sess.run)分配:

import numpy as np
import tensorflow as tf

npc = np.array([[1.,2.],[3.,4.]])
tfc = tf.Variable(npc) # Use variable 

row = np.array([[.1,.2]])

with tf.Session() as sess:   
    tf.initialize_all_variables().run() # need to initialize all variables

    print('tfc:\n', tfc.eval())
    print('npc:\n', npc)
    for i in range(2):
        for j in range(2):
            npc[i,j] += row[0,j]
    tfc.assign(npc).eval() # assign_sub/assign_add is also available.
    print('modified tfc:\n', tfc.eval())
    print('modified npc:\n', npc)

It outputs:

它输出:

tfc:
 [[ 1.  2.]
 [ 3.  4.]]
npc:
 [[ 1.  2.]
 [ 3.  4.]]
modified tfc:
 [[ 1.1  2.2]
 [ 3.1  4.2]]
modified npc:
 [[ 1.1  2.2]
 [ 3.1  4.2]]

回答by user5931

I struggled with this for a while. The answer given will add assignoperations to the graph (and thus needlessly increase the size of the .metaif you subsequently save a checkpoint). A better solution is to use tf.keras.backend.set_value. One could emulate that with raw tensorflow by doing:

我为此挣扎了一段时间。给出的答案将向assign图形添加操作(因此,.meta如果您随后保存检查点,则不必要地增加图形的大小)。更好的解决方案是使用tf.keras.backend.set_value. 可以通过执行以下操作使用原始 tensorflow 来模拟:

    for x, value in zip(tf.global_variables(), values_npfmt):
      if hasattr(x, '_assign_placeholder'):
        assign_placeholder = x._assign_placeholder
        assign_op = x._assign_op
      else:
        assign_placeholder = array_ops.placeholder(tf_dtype, shape=value.shape)
        assign_op = x.assign(assign_placeholder)
        x._assign_placeholder = assign_placeholder
        x._assign_op = assign_op
      get_session().run(assign_op, feed_dict={assign_placeholder: value})