TensorFlow 中的变量
TensorFlow 是一个用于高效数值计算的Python库。它是一个基础库,可用于开发机器学习和深度学习模型。 TensorFlow 是一个高级库。变量是可以通过对其执行操作来修改的状态或值。在 TensorFlow 中,变量是使用 Variable() 构造函数创建的。
Variable() 构造函数需要一个变量的初始值,它可以是任何种类或形状的张量。变量的类型和形式由其初始值定义。形状和变量一旦创建就固定了。让我们看几个如何在 TensorFlow 中创建变量的示例。
Syntax: tf.Variable(initial_value=None, trainable=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, import_scope=None, constraint=None,synchronization=tf.VariableSynchronization.AUTO, aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None)
Parameters:
- initial_value: by default None. The initial value for the Variable is a Tensor, or a Python object convertible to a Tensor.
- trainable: by default None. If True, GradientTapes will keep an eye on this variable’s usage.
- validate_shape: by default True. Allows the variable to be initialised with an unknown shape value if False. The shape of initial value must be known if True, which is the default.
- name:by default None. The variable’s optional name. Defaults to ‘Variable’ and is automatically uniquified.
- variable_def: by default None.
- dtype: by default None. If set, initial_value will be converted to the given type. If None, either the datatype will be kept (if initial_value is a Tensor), or convert_to_tensor will decide.
- shape: by default None. if None the shape of initial_value will be used. if any shape is specified, the variable will be assigned with that particular shape.
创建变量
tf.Variable() 构造函数用于在 TensorFlow 中创建变量。
Python3
tensor = tf.Variable([3,4])
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# The shape of the variable
print("The shape of the variable: ",
tensor1.shape)
# The number of dimensions in the variable
print("The number of dimensions in the variable:",
tf.rank(tensor1).numpy())
# The size of the variable
print("The size of the tensorflow variable:",
tf.size(tensor1).numpy())
# checking the datatype of the variable
print("The datatype of the tensorflow variable is:",
tensor1.dtype)
Python3
import tensorflow as tf
tensor1 = tf.Variable([3, 4])
tensor1[1].assign(5)
tensor1
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# using assign_add() function
tensor1.assign_add([1, 1])
tensor1
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# using assign_sub() function
tensor1.assign_sub([1, 1])
tensor1
Python3
import tensorflow as tf
tensor1 = tf.Variable([[1, 2, 3, 4]])
tf.reshape(tensor1, shape=(2, 2))
tensor1
Python3
import tensorflow as tf
tensor1 = tf.Variable([[1, 2, 3, 4]], dtype=float)
tensor1
Python3
# import packages
import tensorflow as tf
# create two variables
tensor1 = tf.Variable([3, 4])
tensor2 = tf.Variable([5, 6])
print("Addition of tensors", tensor1+tensor2)
print("Subtraction of tensors", tensor1-tensor2)
print("Multiplication of tensors", tensor1*tensor2)
print("division of tensors", tensor1/tensor2)
Python3
# import packages
import tensorflow as tf
# create two variables
tensor1 = tf.Variable([3, 4])
tensor2 = tf.Variable([2])
# broadcasting
output = tensor1*tensor2
print(output)
Python3
# import packages
import tensorflow as tf
# create a variable
tensor1 = tf.Variable([3, 4])
print('The type of hardware variable used : '+tensor1.device)
输出:
TensorFlow 变量的维度、大小、形状和数据类型
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# The shape of the variable
print("The shape of the variable: ",
tensor1.shape)
# The number of dimensions in the variable
print("The number of dimensions in the variable:",
tf.rank(tensor1).numpy())
# The size of the variable
print("The size of the tensorflow variable:",
tf.size(tensor1).numpy())
# checking the datatype of the variable
print("The datatype of the tensorflow variable is:",
tensor1.dtype)
输出:
The shape of the variable: (2,)
The number of dimensions in the variable: 1
The size of the tensorflow variable: 2
The datatype of the tensorflow variable is:
分配或修改变量中的元素
我们使用 assign() 方法来修改变量。它更像是索引,然后使用 assign() 方法。还有更多方法可以分配或修改变量,例如 Variable.assign_add() 和 Variable.assign_sub())。
示例 1:
assign():用于更新或添加新值。
Syntax: assign(value, use_locking=False, name=None, read_value=True)
parameters:
- value: The new value for this variable.
- use_locking: locking during assignment if “true”.
Python3
import tensorflow as tf
tensor1 = tf.Variable([3, 4])
tensor1[1].assign(5)
tensor1
输出:
示例 2:
Syntax: assign_add(delta, use_locking=False, name=None, read_value=True)
parameters:
- delta: The value to be added to the variable(Tensor).
- use_locking: During the operation, if True, utilise locking.
- name: name of the operation.
- read_value: If True, anything that evaluates to the modified value of the variable will be returned; if False, the assign op will be returned.
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# using assign_add() function
tensor1.assign_add([1, 1])
tensor1
输出:
示例 3:
Syntax: assign_sub( delta, use_locking=False, name=None, read_value=True)
parameters:
- delta: The value to be subtracted from the variable
- use_locking: During the operation, if True, utilise locking.
- name: name of the operation.
- read_value: If True, anything that evaluates to the modified value of the variable will be returned; if False, the assign op will be returned.
Python3
# import packages
import tensorflow as tf
# create variable
tensor1 = tf.Variable([3, 4])
# using assign_sub() function
tensor1.assign_sub([1, 1])
tensor1
输出:
改变变量的形状
tf.reshape() 方法用于改变变量的形状。必须传递变量和形状。
Python3
import tensorflow as tf
tensor1 = tf.Variable([[1, 2, 3, 4]])
tf.reshape(tensor1, shape=(2, 2))
tensor1
输出:
更改张量的数据类型
如果我们希望变量具有特定的数据类型,我们必须在创建变量时指定 dtype。在此示例中,我们将 dtype 指定为 float。
Python3
import tensorflow as tf
tensor1 = tf.Variable([[1, 2, 3, 4]], dtype=float)
tensor1
输出:
变量操作
我们可以使用 TensorFlow 变量执行加法、减法、乘法、除法和更多操作。
Python3
# import packages
import tensorflow as tf
# create two variables
tensor1 = tf.Variable([3, 4])
tensor2 = tf.Variable([5, 6])
print("Addition of tensors", tensor1+tensor2)
print("Subtraction of tensors", tensor1-tensor2)
print("Multiplication of tensors", tensor1*tensor2)
print("division of tensors", tensor1/tensor2)
输出:
Addition of tensors tf.Tensor([ 8 10], shape=(2,), dtype=int32)
Subtraction of tensors tf.Tensor([-2 -2], shape=(2,), dtype=int32)
Multiplication of tensors tf.Tensor([15 24], shape=(2,), dtype=int32)
division of tensors tf.Tensor([0.6 0.66666667], shape=(2,), dtype=float64)
广播
当我们尝试对多个变量对象执行组合操作时,就像使用张量对象一样,较小的变量可以立即扩展以适应较大的变量,就像 NumPy 数组一样。当您尝试将标量变量与变量相乘时,标量会被拉伸以乘以变量的每个元素。
Python3
# import packages
import tensorflow as tf
# create two variables
tensor1 = tf.Variable([3, 4])
tensor2 = tf.Variable([2])
# broadcasting
output = tensor1*tensor2
print(output)
输出:
tf.Tensor([6 8], shape=(2,), dtype=int32)
变量的硬件选择
我们可以利用它来查看使用什么类型的设备(即处理器)来处理我们的变量。 .device 属性被使用。
Python3
# import packages
import tensorflow as tf
# create a variable
tensor1 = tf.Variable([3, 4])
print('The type of hardware variable used : '+tensor1.device)
输出:
The type of hardware variable used : /job:localhost/replica:0/task:0/device:CPU:0