Tensorflow:如何修改张量值

use*_*046 11 python numpy tensorflow

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

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

关键是如何改变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()于笔记本电脑.

代码的简单案例如下所示.此代码的目的是使其tfc具有与npc进程后相同的输出.

提示
您应该对待它tfc并且npc彼此独立.这符合以下情况:检索到的训练数据首先是tensor格式化的tf.placeholder().


源代码

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

Sun*_*Kim 9

使用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)
Run Code Online (Sandbox Code Playgroud)

它输出:

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]]
Run Code Online (Sandbox Code Playgroud)