# Using Python state
x = tf.zeros([10, 10])
x += 2 # This is equivalent to x = x + 2, which does not mutate the original
# value of x
print(x)
x从0更改为2。它显示x = tf.zeros([10,10])的以下结果:
<tf.Tensor: id=266, shape=(10, 10), dtype=float32, numpy=
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>
然后在执行后更改为以下内容:x + = 2
<tf.Tensor: id=263, shape=(10, 10), dtype=float32, numpy=
array([[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.]], dtype=float32)>
为什么评论说“不会改变x的原始值”?
克里斯·希尔德(Chris Heald)是对的。最容易看到使用NumPy的区别:
import numpy as np
a = np.array(2)
b = a # Set up an alias
a += 1 # NumPy operations are in-place - they mutate the array
print(b) # Output: 3!
由于的ndarray
会__iadd__
原位改变数组,因此对该数组的所有引用都会更新,因此代码为print 3
。在这方面,NumPy数组更像对象。
将此与Tensor
不可变的TF进行比较(代码为TF 2):
import tensorflow as tf
a = tf.constant(2)
b = a # Set up an alias
a += 1 # Tensor operations are not in-place - a new tensor is created
print(b) # Output: 2
打印2,因为Tensor
是不可变的。因此它们更像原始值。
这样就可以直接访问原始值-只需将其分配给其他变量(就像我对进行的操作b = a
)。
描述此问题的另一种方法是使用列表:
l = [1]
l[0] = 2 # I can mutate the list...
l = [2] # ... or I can create a new one
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句