tf.identity()

介绍

返回具有与输入相同的形状和内容的张量

相当于python中的 浅拷贝 或 深拷贝

语法

tf.identity(
    input,
    name=None
)
参数
  • input:一个 Tensor
返回值
  • 返回一个和输入的 tensor 大小和数值都一样的 tensor

作用

观察下面的代码

a=tf.Variable(3)
b=a

a.assign(1)

a,b

执行结果:

(<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>,
 <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>)

也就是说修改a的值后,b的值也同时改变,因为b和a所指向的地址是同一个

解决

a=tf.Variable(3)
b=tf.identity(a)

a.assign(1)

a,b

执行结果如下:

(<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>,
 <tf.Tensor: id=178, shape=(), dtype=int32, numpy=3>)

原文出处:/show_1EF4gksfKWdr.html