由于我需要在使用Tensorflow训练模型之前为数据编写一些预处理程序,因此需要对进行一些修改tensor
。但是,我不知道如何tensor
像使用一样修改值numpy
。
最好的方法是可以tensor
直接修改。但是,在当前版本的Tensorflow中似乎不可能。另一种方法是改变tensor
到ndarray
该进程,然后用tf.convert_to_tensor
改回来。
关键是如何更改tensor
为ndarray
。
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)
输出:
tfc:
[[1. 2.]
[3. 4.]]
npc:
[[1. 2.]
[3. 4.]]
修改tfc:
[[1. 2.]
[3. 4.]]
修改npc:
[[1.1 2.2]
[3.1 4.2]]
使用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]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句