Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy a variable in tensorflow

Tags:

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?

like image 447
randomizer Avatar asked Nov 15 '15 08:11

randomizer


People also ask

How do you save a variable in tf?

To save and restore your variables, all you need to do is to call the tf. train. Saver() at the end of you graph. This will create 3 files ( data , index , meta ) with a suffix of the step you saved your model.

How do I get tf variable value?

To get the current value of a variable x in TensorFlow 2, you can simply print it with print(x) . This prints a representation of the tf. Variable object that also shows you its current value.

How do I assign a value in TensorFlow?

Tensorflow variables represent the tensors whose values can be changed by running operations on them. The assign() is the method available in the Variable class which is used to assign the new tf. Tensor to the variable. The new value must have the same shape and dtype as the old Variable value.

How do you store values in TensorFlow?

One way would be to do a. numpy(). save('file. npy') then converting back to a tensor after loading.


1 Answers

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) 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) 

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) 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) 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()) 

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.

like image 167
dga Avatar answered Oct 12 '22 11:10

dga