在我的一些代码中,我使用 tensorflow 创建了一个神经网络,并可以访问表示该网络输出的张量。我想复制这个张量,这样即使我再训练神经网络,我也可以访问张量的原始值。
根据其他答案和 tensorflow 文档,我尝试了 tf.identity() 函数,但它似乎没有满足我的需要。其他一些链接建议使用 tf.tile(),但这也无济于事。我不想使用 sess.run()、计算张量并将其存储在别处。
这是一个玩具示例,描述了我需要做什么:
import tensorflow as tf
import numpy as np
t1 = tf.placeholder(tf.float32, [None, 1])
t2 = tf.layers.dense(t1, 1, activation=tf.nn.relu)
expected_out = tf.placeholder(tf.float32, [None, 1])
loss = tf.reduce_mean(tf.square(expected_out - t2))
train_op = tf.train.AdamOptimizer(1e-4).minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(t2, feed_dict={t1: np.array([1]).reshape(-1,1)}))
t3 = tf.identity(t2) # Need to make copy here
print(sess.run(t3, feed_dict={t1: np.array([1]).reshape(-1,1)}))
print("\nTraining \n")
for i in range(1000):
sess.run(train_op, feed_dict={t1: np.array([1]).reshape(-1,1), expected_out: np.array([1]).reshape(-1,1)})
print(sess.run(t2, feed_dict={t1: np.array([1]).reshape(-1,1)}))
print(sess.run(t3, feed_dict={t1: np.array([1]).reshape(-1,1)}))
上面代码的结果是t2
和t3
有相同的值。
[[1.5078927]]
[[1.5078927]]
Training
[[1.3262703]]
[[1.3262703]]
我想要的是让 t3
保持其值不被复制。
[[1.5078927]]
[[1.5078927]]
Training
[[1.3262703]]
[[1.5078927]]
预先感谢您的帮助。
最佳答案
您可以使用一个命名的 tf.assign
操作,然后通过 Graph.get_operation_by_name
仅运行该操作.这不会获取张量的值,而只是在图上运行分配操作。考虑以下示例:
import tensorflow as tf
a = tf.placeholder(tf.int32, shape=(2,))
w = tf.Variable([1, 2]) # Updated in the training loop.
b = tf.Variable([0, 0]) # Backup; stores intermediate result.
t = tf.assign(w, tf.math.multiply(a, w)) # Update during training.
tf.assign(b, w, name='backup')
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
x = [2, 2]
# Emulate training loop:
for i in range(3):
print('w = ', sess.run(t, feed_dict={a: x}))
# Backup without retrieving the value (returns None).
print('Backup now: ', end='')
print(sess.run(tf.get_default_graph().get_operation_by_name('backup')))
# Train a bit more:
for i in range(3):
print('w = ', sess.run(t, feed_dict={a: x}))
# Check the backed-up value:
print('Backup: ', sess.run(b)) # Is [8, 16].
因此对于您的示例,您可以这样做:
t3 = tf.Variable([], validate_shape=False)
tf.assign(t3, t2, validate_shape=False, name='backup')
关于python - tensorflow python中张量的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57120680/