我正在尝试将Tensorflow变量转换为numpy数组或列表列表,以便在外部python函数中迭代,我不想因为某个原因而修改它:
import tensorflow as tf
import numpy as np
v = tf.Variable(np.array([[1,2,3,4],[1,2,3,4]]),dtype=tf.float32)
def numpy_func(x):
new_v = []
for v1 in v:
print(v1)
new_v.append(v1)
return new_v
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
v1 = tf.Variable(numpy_func(np.array(v.eval())),dtype=tf.float32)
这会返回TypeError: 'Variable' object is not iterable.
,因为tf.Variable
仍会转移到该功能。我试图将它转换为张量,但它也保持tf.Variable
完整:
v1 = tf.Variable(numpy_func(np.array(tf.convert_to_tensor(v,dtype=tf.float32).eval())),dtype=tf.float32)
TypeError: 'Variable' object is not iterable.
我该怎么办?我想要pythonic list或numpy数组,而不是tensorflow对象。
PS。解决方法是使用类似
的方法修改函数for i in range(0,v.shape[0]):
v1 = v[i,:].eval()
但我不想这样做,因为我希望从不同的地方调用pythonic函数。