由于在使用Tensorflow训练模型之前需要为数据编写一些预处理,因此需要对tensor
进行一些修改。但是,我不知道如何像使用numpy
那样修改tensor
中的值。
最好的方法是它能够直接修改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
格式的,带有^{
源代码
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
操作(因此,如果随后保存检查点,则不必要地增加.meta
的大小)。更好的解决方案是使用tf.keras.backend.set_value
。我们可以用原始的tensorflow来模拟:使用assign和eval(或sess.run)赋值:
它输出:
相关问题 更多 >
编程相关推荐