5个简单的步骤掌握Tensorflow的Tensor

作者 | Orhan G. Yalçın

编译|VK

来源 | 数据

如果您正在阅读本文,我相信我们有相似的兴趣并且正在/将从事相似的行业。

在本文中,我们将深入研究细节。我们将通过以下五个简单步骤涵盖所有相关主题:

张量的定义:什么是张量

张量是统一的多维数组。它们与 NumPy 数组非常相似,并且它们是不可变的,这意味着它们一旦创建就无法更改。只有编辑可用于创建新副本。

让我们看看张量如何与代码示例一起工作。但首先,要使用对象,我们需要导入库。我们经常将 NumPy 与 NumPy 一起使用,因此我们也可以使用以下行导入 NumPy:

import tensorflow as tf
import numpy as np

张量的创建:创建张量对象

有几种方法可以创建 tf. 对象。让我们从几个例子开始。可以使用多个函数创建张量对象,如下例所示:

# 你可以用`tf.constant`函数创建tf.Tensor对象:
x = tf.constant([[1, 2, 3, 4 ,5]])
# 你可以用`tf.ones`函数创建tf.Tensor对象:
y = tf.ones((1,5))
# 你可以用`tf.zeros`函数创建tf.Tensor对象:
z = tf.zeros((1,5))
# 你可以用`tf.range`函数创建tf.Tensor对象:
q = tf.range(start=1, limit=6, delta=1)
print(x)
print(y)
print(z)
print(q)

输出:
tf.Tensor([[1 2 3 4 5]], shape=(1, 5), dtype=int32)
tf.Tensor([[1. 1. 1. 1. 1.]], shape=(1, 5), dtype=float32) 
tf.Tensor([[0. 0. 0. 0. 0.]], shape=(1, 5), dtype=float32) 
tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)

如您所见,我们使用三个不同的函数创建了一个形状为 (1, 5) 的张量对象,并使用 tf.range() 函数创建了第四个形状为 (5,) 的张量对象。注意 tf.ones而 tf.zeros 接受 shape 作为必需参数,因为它们的元素值是预先确定的。

张量对象的特征

tf。创建具有几个特征的对象。首先,它们具有维数。其次,它们有一个形状,一个由尺寸长度组成的列表。所有张量都有一个大小,即张量中元素的总数。最后,它们的元素都记录在一个统一的数据类型( )中。让我们仔细看看这些特征。

方面

张量根据其维度分类:

例如,我们可以通过传递 tf. 来创建一个 Rank-3 张量。三级嵌套列表对象。对于此示例,我们可以将数字拆分为一个 3 级嵌套列表,每个列表包含 3 个元素:

three_level_nested_list = [[[0, 1, 2], 
                             [3, 4, 5]], 
                           [[6, 7, 8], 
                            [9, 10, 11]] ]
rank_3_tensor = tf.constant(three_level_nested_list)
print(rank_3_tensor)

Output:
tf.Tensor( [[[ 0  1  2]   
             [ 3  4  5]]   
             
            [[ 6  7  8]   
             [ 9 10 11]]],
  shape=(2, 2, 3), dtype=int32)

我们可以看到“”对象当前有多少个维度具有“.ndim”属性。

tensor_ndim = rank_3_tensor.ndim
print("The number of dimensions in our Tensor object is", tensor_ndim)

Output:
The number of dimensions in our Tensor object is 3

形状

形状特征是每个张量都具有的另一个属性。它将每个维度的大小显示为列表。我们可以查看使用 .shape 属性创建的对象的形状,如下所示:

tensor_shape = rank_3_tensor.shape
print("The shape of our Tensor object is", tensor_shape)

Output:
The shape of our Tensor object is (2, 2, 3)

如您所见,我们的张量在第一层有两个元素,在第二层有两个元素,在第三层有三个元素。

尺寸

大小是张量的另一个特征,它表示张量有多少个元素。我们不能用张量对象的属性来测量大小。相反,我们需要使用 tf.size 函数。最后,我们将使用实例函数 .NumPy() 将输出转换为 NumPy 以获得更易读的结果:

tensor_size = tf.size(rank_3_tensor).numpy()
print("The size of our Tensor object is", tensor_size)

Output:
The size of our Tensor object is 12

数据类型

张量通常包含数字数据类型,例如浮点数和整数,但也可能包含许多其他数据类型,例如复数和字符串。

但是,每个张量对象必须将其所有元素存储在统一的数据类型中。因此,我们还可以使用 .dtype 属性来查看为特定张量对象选择的数据类型,如下所示:

tensor_dtype = rank_3_tensor.dtype
print("The data type selected for this Tensor object is", tensor_dtype)

Output:
The data type selected for this Tensor object is 

张量运算指数

索引是项目在序列中的位置的数字表示。这个序列可以引用很多东西:一个列表、一个字符串或任何值序列。

还遵循标准索引规则,类似于列表索引或 NumPy 数组索引。

关于索引的一些规则:

索引从零开始 (0).

负索引(“-n”)值表示从末尾倒数。

冒号 (“:”) 用于 slice:start:stop:step。

逗号 (“,”) 用于达到更深层次。

让我们用以下几行来创建它:

single_level_nested_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
rank_1_tensor = tf.constant(single_level_nested_list)
print(rank_1_tensor)

Output: 
tf.Tensor([ 0  1  2  3  4  5  6  7  8  9 10 11], 
  shape=(12,), dtype=int32)

测试我们的规则 1、2、3:

# 规则1,索引从0开始
print("First element is:",
  rank_1_tensor[0].numpy())
# 规则2,负索引
print("Last element is:",
  rank_1_tensor[-1].numpy())
# 规则3,切片
print("Elements in between the 1st and the last are:",
  rank_1_tensor[1:-1].numpy())

Output: 
First element is: 0 
Last element is: 11 
Elements in between the 1st and the last are: [ 1  2  3  4  5  6  7  8  9 10]

现在,让我们使用以下代码创建它:

two_level_nested_list = [ [0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11] ]
rank_2_tensor = tf.constant(two_level_nested_list)
print(rank_2_tensor)

Output:
tf.Tensor( [[ 0  1  2  3  4  5]  
            [ 6  7  8  9 10 11]], shape=(2, 6), dtype=int32)

并用几个例子测试规则 4:

print("The 1st element of the first level is:",
  rank_2_tensor[0].numpy())
print("The 2nd element of the first level is:",
  rank_2_tensor[1].numpy())
# 规则4, 逗号代表进入更深层
print("The 1st element of the second level is:",
  rank_2_tensor[0, 0].numpy())
print("The 3rd element of the second level is:",
  rank_2_tensor[0, 2].numpy())

Output: 
The first element of the first level is: [0 1 2 3 4 5] 
The second element of the first level is: [ 6  7  8  9 10 11] 
The first element of the second level is: 0 
The third element of the second level is: 2

现在我们已经介绍了索引的基础知识,让我们看看我们可以对张量进行的基本操作。

张量的基本操作

您可以轻松地对张量进行基本数学运算,例如:

添加

逐元素乘法

矩阵乘法

找到最大值或最小值

查找 Max 元素的索引

计算出来的

让我们看看这些操作。我们将创建两个张量对象并应用这些操作。

a = tf.constant([[2, 4], 
                 [6, 8]], dtype=tf.float32)
b = tf.constant([[1, 3], 
                 [5, 7]], dtype=tf.float32)

我们可以从加法开始。

# 我们可以使用' tf.add() '函数并将张量作为参数传递。
add_tensors = tf.add(a,b)
print(add_tensors)

Output:
tf.Tensor( [[ 3.  7.]  
            [11. 15.]], shape=(2, 2), dtype=float32)

乘法

# 我们可以使用' tf.multiply() '函数并将张量作为参数传递。
multiply_tensors = tf.multiply(a,b)
print(multiply_tensors)

Output:
tf.Tensor( [[ 2. 12.]  
            [30. 56.]], shape=(2, 2), dtype=float32)

矩阵乘法:

# 我们可以使用' tf.matmul() '函数并将张量作为参数传递。
matmul_tensors = tf.matmul(a,b)
print(matmul_tensors)

Output:
tf.Tensor( [[ 2. 12.]  
            [30. 56.]], shape=(2, 2), dtype=float32)

注意:操作是深度学习算法的核心。因此,即使您不会直接使用它们,了解这些操作也很重要。

我们上面列出的其他操作示例:

# 使用' tf.reduce_max() '和' tf.reduce_min() '函数可以找到最大值或最小值
print("The Max value of the tensor object b is:",
  tf.reduce_max(b).numpy())
# 使用' tf.argmax() '函数可以找到最大元素的索引
print("The index position of the max element of the tensor object b is:",
  tf.argmax(b).numpy())
# 使用 tf.nn.softmax'函数计算softmax
print("The softmax computation result of the tensor object b is:",
  tf.nn.softmax(b).numpy())

Output:
The Max value of the tensor object b is: 1.0 
The index position of the Max of the tensor object b is: [1 1] 
The softmax computation result of the tensor object b is: [[0.11920291 0.880797  ]  [0.11920291 0.880797  ]]

操纵形状

就像在 NumPy 数组和数据帧中一样,您也可以重塑张量对象。

这种变形操作非常快,因为不需要复制底层数据。对于重塑操作,我们可以使用 tf. 功能

# 我们的初始张量
a = tf.constant([[1, 2, 3, 4, 5, 6]])
print('The shape of the initial Tensor object is:', a.shape)
b = tf.reshape(a, [6, 1])
print('The shape of the first reshaped Tensor object is:', b.shape)
c = tf.reshape(a, [3, 2])
print('The shape of the second reshaped Tensor object is:', c.shape)
# 如果我们以shape参数传递-1,那么张量就变平坦化。
print('The shape of the flattened Tensor object is:', tf.reshape(a, [-1]))

Output:
The shape of our initial Tensor object is: (1, 6) 
The shape of our initial Tensor object is: (6, 1) 
The shape of our initial Tensor object is: (3, 2) 
The shape of our flattened Tensor object is: tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)

如您所见,我们可以轻松地重塑我们的张量对象。但需要注意的是,开发者在进行 操作时必须是合理的。否则,张量可能会混淆甚至产生错误。所以,要小心

分类:

技术要点:

相关文章:

© 版权声明
THE END
喜欢就支持一下吧
点赞10赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容