使用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)
它输出:
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]]
0
由于我需要在使用Tensorflow训练模型之前为数据编写一些预处理程序,因此需要对
tensor
一些修改。但是,我不知道如何像使用numpy
那样修改tensor
的值。最好的方法是能够直接修改
tensor
。但是,在当前版本的Tensorflow中似乎不可能。另一种方法是将进程的tensor
更改为ndarray
,然后使用tf.convert_to_tensor
进行更改。关键是如何将
tensor
更改为ndarray
。1)
tf.contrib.util.make_ndarray(tensor)
: https :tf.contrib.util.make_ndarray(tensor)
根据文档,这似乎是最简单的方法,但是我在当前版本的Tensorflow中找不到此功能。其次,它的输入是
TensorProto
而不是tensor
。2)使用
a.eval()
将a
复制到另一个ndarray
但是,它仅在笔记本中使用
tf.InteractiveSession()
时有效。下面是一个带有代码的简单案例。此代码的目的是使
tfc
在该过程之后具有与npc
相同的输出。暗示
您应该将
tfc
和npc
视为彼此独立。这满足了首先使用tf.placeholder()
检索到的训练数据为tensor
格式的情况。源代码
输出:
tfc:
[[1. 2.]
[3. 4.]]
NPC:
[[1. 2.]
[3. 4.]]
修改后的tfc:
[[1. 2.]
[3. 4.]]
修改后的NPC:
[[1.1 2.2]
[3.1 4.2]