【发布时间】:2023-03-12 03:00:01
【问题描述】:
在我的一些代码中,我使用 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]]
提前感谢您的帮助。
【问题讨论】:
标签: python tensorflow machine-learning deep-learning