点击上方“公众号”可订阅哦!
TensorFlow 变量是用于表示程序处理的共享持久状态的推荐方法。本指南介绍在 TensorFlow 中如何创建、更新和管理 tf.Variable
的实例。
变量通过 tf.Variable
类进行创建和跟踪。tf.Variable
表示张量,对它执行运算可以改变其值。利用特定运算可以读取和修改此张量的值。更高级的库(如 tf.keras
)使用 tf.Variable
来存储模型参数。
01
创建变量
创建变量
import tensorflow as tf
my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
my_variable = tf.Variable(my_tensor)
变量可以是各种类型,就像张量一样
bool_variable = tf.Variable([False, False, False, True])
complex_variable = tf.Variable([5 + 4j, 6 + 1j])
变量与张量的定义方式和操作行为都十分相似,实际上,它们都是 tf.Tensor
支持的一种数据结构。与张量类似,变量也有 dtype
和形状,并且可以导出至 NumPy。
print("Shape: ",my_variable.shape)
print("DType: ",my_variable.dtype)
print("As NumPy: ", my_variable.numpy)
# output
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)>>
大部分张量运算在变量上也可以按预期运行,不过变量无法重构形状。
print("A variable:",my_variable)
print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable))
print("\nIndex of highest value:", tf.argmax(my_variable))
# This creates a new tensor; it does not reshape the variable.
print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4]))
# output
A variable: <tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
Viewed as a tensor: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float32)
Index of highest value: tf.Tensor([1 1], shape=(2,), dtype=int64)
Copying and reshaping: tf.Tensor([[1. 2. 3. 4.]], shape=(1, 4), dtype=float32)
参考文献:文档主要参考TensorFlow官网
点击上方“蓝字”关注本公众号
点击上方“蓝字”关注本公众号
END
扫码关注
微信号|sdxx_rmbj