How can I copy a variable in tensorflow

前端 未结 4 961
清歌不尽
清歌不尽 2020-12-24 13:19

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?

4条回答
  •  青春惊慌失措
    2020-12-24 14:14

    You can do this in a couple of ways.

    • this will create you a copy: v2 = tf.Variable(v1)
    • you can also use identity op: v2 = tf.identity(v1) (which I think is a proper way of doing it.

    Here is a code example:

    import tensorflow as tf
    
    v1 = tf.Variable([[1, 2], [3, 4]])
    v_copy1 = tf.Variable(v1)
    v_copy2 = tf.identity(v1)
    
    init = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init)
    a, b = sess.run([v_copy1, v_copy2])
    sess.close()
    
    print a
    print b
    

    Both of them would print the same tensors.

提交回复
热议问题