TensorFlow 变量基础用法


发布日期 : 2024-08-05 04:21:29 UTC

访问量: 10 次浏览

Tensorflow中的变量

TensorFlow是一个用于高效数值计算的Python库。它是一个基础库,可用于开发机器学习和深度学习模型。
Tensorflow是一个高级库。变量是一种状态或数值,可以通过对其进行操作来修改。
在TensorFlow中,变量是使用 Variable() 构造函数创建的。

Variable() 构造函数希望变量有一个初始值,它可以是任何种类或形状的Tensor。
变量的类型和形式由其初始值定义。形状和变量一旦被创建就会被固定下来。
让我们看一下如何在TensorFlow中创建变量的几个例子。

语法:

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)

参数:

  • initial\_value : 默认为 None。变量的初始值是一个张量,或者一个可以转换为张量的Python对象。
  • trainable : 默认为无。如果为真,GradientTapes将关注这个变量的使用。
  • validate\_shape : 默认为True。如果是False,允许变量以未知的形状值初始化。如果是True,初始值的形状必须是已知的,这是默认的。
  • name :默认为None。变量的可选名称。默认为’Variable’,并自动唯一化。
  • variable\_def :默认为无。
  • dtype :默认为无。如果设置,initial\_value 将被转换为给定的类型。如果没有,数据类型将被保留(如果initial_value是一个Tensor),或者 convert\_to\_tensor 将决定。
  • shape :默认为无。如果无,将使用 initial\_value 的形状。如果指定了任何形状,变量将被分配到该特定形状。

创建一个变量

tf.Variable() 构造函数用于在TensorFlow中创建一个变量。

tensor = tf.Variable([3,4])

输出:

> <tf.Variable ‘Variable:0’ shape=(2,) dtype=int32,
> [numpy](https://geek-docs.com/numpy/numpy-top-tutorials/1000100_numpy_index.html "NumPy 教程")
> =array([3, 4], dtype=int32)>

TensorFlow变量的尺寸、大小、形状和d类型

# 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: <dtype: 'int32'>

分配或修改 变量中的元素

我们使用 assign() 方法来修改这个变量。这更像是索引,然后使用 assign() 方法。
还有更多的方法来分配或修改变量,如 Variable.assign\_add()Variable.assign\_sub() )。

示例 1:

assign() :它用于更新或添加一个新的值。

语法:
assign(value, use_locking=False, name=None, read_value=True)

参数:

  • value :这个变量的新值。
  • use\_locking :如果 “true”,则在赋值过程中进行锁定。
import tensorflow as tf

tensor1 = tf.Variable([3, 4])
tensor1[1].assign(5)
tensor1

输出:

> <tf.Variable ‘Variable:0’ shape=(2,) dtype=int32, numpy=array([3, 5], dtype=int32)>

示例 2:

语法:
assign_add(delta, use_locking=False, name=None, read_value=True)

参数:

  • delta:要添加到变量(Tensor)中的值。
  • use\_locking :在操作过程中,如果为真,则利用锁定。
  • name :操作的名称。
  • read\_value :如果是True,任何评估为变量的修改值的东西将被返回;如果是False,赋值操作将被返回。
# import packages
import tensorflow as tf

# create variable
tensor1 = tf.Variable([3, 4])

# using assign_add() function
tensor1.assign_add([1, 1])
tensor1

输出:

> <tf.Variable ‘Variable:0’ shape=(2,) dtype=int32, numpy=array([4, 5], dtype=int32)>

示例 3:

语法:
assign_sub( delta, use_locking=False, name=None, read_value=True)

参数:

delta :要从变量中减去的值

use\_locking :在操作过程中,如果为真,则利用锁定。

name :操作的名称。

read\_value :如果是True,任何评估为变量的修改值的东西将被返回;如果是False,赋值操作将被返回。

# import packages
import tensorflow as tf

# create variable
tensor1 = tf.Variable([3, 4])

# using assign_sub() function
tensor1.assign_sub([1, 1])
tensor1

输出:

> <tf.Variable ‘Variable:0’ shape=(2,) dtype=int32, numpy=array([2, 3], dtype=int32)>

改变变量的形状

tf.reshape() 方法用于改变变量的形状。必须传递变量和形状。

import tensorflow as tf

tensor1 = tf.Variable([[1, 2, 3, 4]])
tf.reshape(tensor1, shape=(2, 2))
tensor1

输出:

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4]], dtype=int32)>

改变张量的数据类型

如果我们想让变量有一个特定的数据类型,我们必须在创建变量时指定 dtype
在这个例子中,我们指定 dtypefloat

import tensorflow as tf

tensor1 = tf.Variable([[1, 2, 3, 4]], dtype=float)
tensor1

输出:

> <tf.Variable ‘Variable:0’ shape=(1, 4) dtype=float32, numpy=array([[1., 2., 3., 4.]], dtype=float32)>

用变量进行操作

我们可以用TensorFlow变量进行加法、减法、乘法、除法以及更多的操作。

# 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)

Broadcasting

当我们试图用几个 Variable 对象执行组合操作时,就像用Tensor对象一样,较小的变量可以像NumPy数组一样瞬间延伸出去以适应大的变量。
当你试图将一个标量变量与一个变量相乘时,标量会被拉长,以乘上变量的每个元素。

# 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)

变量的硬件选择

我们可以利用它来查看什么类型的设备(即处理器)被用来处理我们的变量。.设备属性的使用。

# 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