如何在 tensorflow 中复制变量 [英] How can I copy a variable in tensorflow

查看:75
本文介绍了如何在 tensorflow 中复制变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 numpy 中,我可以使用 numpy.copy.是否有类似的方法可以用来在 TensorFlow 中创建张量的副本?

In numpy I can create a copy of the variable with numpy.copy. Is there a similar method, that I can use to create a copy of a Tensor in TensorFlow?

推荐答案

您问的是如何在标题中复制变量,但如何在问题中复制张量.让我们看看不同的可能答案.

You asked how to copy a variable in the title, but how to copy a tensor in the question. Let's look at the different possible answers.

(1) 您想要创建一个 张量,它的值与当前存储在我们称为 var变量 中的值相同>.

(1) You want to create a tensor that has the same value that is currently stored in a variable that we'll call var.

tensor = tf.identity(var)

但请记住,'tensor' 是一个图形节点,在评估时将具有该值,并且任何时候评估它时,它都会获取 varcurrent 值.您可以使用 控制流操作,例如 with_dependencies() 查看变量更新的顺序和标识的时间.

But remember, 'tensor' is a graph node that will have that value when evaluated, and any time you evaluate it, it will grab the current value of var. You can play around with control flow ops such as with_dependencies() to see the ordering of updates to the variable and the timing of the identity.

(2) 您想创建另一个变量并将其值设置为当前存储在变量中的值:

(2) You want to create another variable and set its value to the value currently stored in a variable:

import tensorflow as tf
var = tf.Variable(0.9)
var2 = tf.Variable(0.0)
copy_first_variable = var2.assign(var)
init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

print sess.run(var2)
sess.run(copy_first_variable)
print sess.run(var2)

(3) 您想定义一个变量并将其起始值设置为您已将变量初始化为的相同值(这就是 nivwu .. 上面的回答):

(3) You want to define a variable and set its starting value to the same thing you already initialized a variable to (this is what nivwu.. above answered):

var2 = tf.Variable(var.initialized_value())

当您调用 tf.initialize_all_variables 时,

var2 将被初始化.在您已经初始化图形并开始运行之后,您不能使用它来复制 var.

var2 will get initialized when you call tf.initialize_all_variables. You can't use this to copy var after you've already initialized the graph and started running things.

这篇关于如何在 tensorflow 中复制变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆