简体   繁体   English

Tensorflow:如何修改张量值

[英]Tensorflow: How to modify the value in tensor

Since I need to write some preprocesses for the data before using Tensorflow to train models, some modifications on the tensor is needed. 由于我需要在使用Tensorflow训练模型之前为数据编写一些预处理,因此需要对tensor一些修改。 However, I have no idea about how to modify the values in tensor like the way using numpy . 但是,我不知道如何使用numpy修改tensor量值。

The best way of doing so is that it is able to modify tensor directly. 这样做的最好方法是它能够直接修改tensor Yet, it seems not possible in the current version of Tensorflow. 然而,在当前版本的Tensorflow中似乎不可能。 An alternative way is changing tensor to ndarray for the process, and then use tf.convert_to_tensor to change back. 另一种方法是将过程的tensor更改为ndarray ,然后使用tf.convert_to_tensor进行更改。

The key is how to change tensor to ndarray . 关键是如何将tensor改为ndarray
1) tf.contrib.util.make_ndarray(tensor) : https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray 1) tf.contrib.util.make_ndarray(tensor)httpstf.contrib.util.make_ndarray(tensor)
It seems the easiest way as per the document, yet I cannot find this function in the current version of the Tensorflow. 这似乎是文档中最简单的方法,但我在Tensorflow的当前版本中找不到这个功能。 Second, the input of it is TensorProto rather than tensor . 其次,它的输入是TensorProto而不是tensor
2) Use a.eval() to copy a to another ndarray 2)使用a.eval()a复制到另一个ndarray
Yet, it works only at using tf.InteractiveSession() in notebook. 然而,它只适用于在笔记本中使用tf.InteractiveSession()

A simple case with codes shows below. 代码的简单案例如下所示。 The purpose of this code is making that the tfc has the same output as npc after the process. 此代码的目的是使tfc在进程后具有与npc相同的输出。

HINT 暗示
You should treat that tfc and npc are independent to each other. 你应该认为tfcnpc是相互独立的。 This meets the situation that at first the retrieved training data is in tensor format with tf.placeholder() . 这符合以下情况:首先检索到的训练数据与tf.placeholder()tensor格式。


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: TFC:
[[ 1. 2.] [[1. 2.]
[ 3. 4.]] [3. 4.]]
npc: NPC:
[[ 1. 2.] [[1. 2.]
[ 3. 4.]] [3. 4.]]
modified tfc: 修改后的tfc:
[[ 1. 2.] [[1. 2.]
[ 3. 4.]] [3. 4.]]
modified npc: 修改后的npc:
[[ 1.1 2.2] [[1.1 2.2]
[ 3.1 4.2]] [3.1 4.2]]

Use assign and eval (or sess.run) the assign: 使用assign和eval(或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]]

I struggled with this for a while. 我挣扎了一段时间。 The answer given will add assign operations to the graph (and thus needlessly increase the size of the .meta if you subsequently save a checkpoint). 给出的答案将向图表添加assign操作(如果随后保存检查点, .meta不必要地增加.meta的大小)。 A better solution is to use tf.keras.backend.set_value . 更好的解决方案是使用tf.keras.backend.set_value One could emulate that with raw tensorflow by doing: 人们可以通过以下方式模拟原始张量流:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM