Tensorflow变量是用于表示程序处理的共享持久状态的推荐方法。
- 创建变量
要创建变量,要先提供初始值,tf.Variable与初始值的dtype相同。
import tensorflow as tf
my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
my_variable = tf.Variable(my_tensor)
变量与张量的定义方式和操作行为都十分相似,它们都是 tf.Tensor 支持的一种数据结构。变量也有 dtype 和形状,并且可以导出至 NumPy。
print("Shape: ",my_variable.shape)
print("DType: ",my_variable.dtype)
print("As NumPy: ", my_variable.numpy)
Shape: (2, 2)
DType: <dtype: ‘float32’>
As NumPy: <bound method BaseResourceVariable.numpy of <tf.Variable ‘Variable:0’ shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>>
大部分张量运算在变量上也可以按预期运行
import tensorflow as tf
my_tensor = tf.constant([ [1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
my_variable = tf.Variable(my_tensor)
print("Shape: ", my_variable.shape)
print("\nIndex of highest value:", tf.argmax(my_variable))
Shape: (4, 2)
Index of highest value: tf.Tensor([3 3], shape=(2,), dtype=int64)
注意:tf.argmax(my_variable)结果是: tf.Tensor([3 3]是分别从的第一个数数,从列的一个数数,找到最大的数。
a = tf.Variable([2.0, 3.0])
a.assign([1, 2])
a.assign([1.0, 2.0, 3.0])
print(a)
ValueError: Shapes (2,) and (3,) are incompatible
注意:使用 tf.Variable.assign 重新分配张量。调用 assign(通常)不会分配新张量,而会重用现有张量的内存,即变量无法重构形状。
从现有变量创建新变量会复制支持张量。两个变量不能共享同一内存空间。
a = tf.Variable([2.0, 3.0])
# Create b based on the value of a
b = tf.Variable(a)
a.assign([5, 6])
# a and b are different
print(a.numpy()) # [5. 6.]
print(b.numpy()) # [2. 3.]
# There are other versions of assign
print(a.assign_add([2,3]).numpy()) # [7. 9.]
print(a.assign_sub([7,9]).numpy()) # [0. 0.]
- 放置变量和张量
即使存在可用的 GPU,我们也可以将一个浮点张量和一个变量放置在 CPU 上。
with tf.device('CPU:0'):
# Create some tensors
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
将变量或张量的位置设置在一个设备上,然后在另一个设备上执行计算。但这样会产生延迟,因为需要在两个设备之间复制数据。
with tf.device('CPU:0'):
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.Variable([[1.0, 2.0, 3.0]])
with tf.device('GPU:0'):
# Element-wise multiply
k = a * b
print(k)