作者|Orhan G. Yalçın
编译|VK
起源|Towards Datas Science

如果你正在读这篇文章,我置信咱们有着类似的趣味,当初/未来也会从事相似的行业。

在这篇文章中,咱们将深入研究Tensorflow Tensor的细节。咱们将在以下五个简略步骤中介绍与Tensorflow的Tensor中相干的所有主题:

  • 第一步:张量的定义→什么是张量?
  • 第二步:创立张量→创立张量对象的函数
  • 第三步:张量对象的特色
  • 第四步:张量操作→索引、根本张量操作、形态操作、播送
  • 第五步:非凡张量

张量的定义:什么是张量

张量是TensorFlow的平均型多维数组。它们十分相似于NumPy数组,并且它们是不可变的,这意味着一旦创立它们就不能被更改。只能应用编辑创立新正本。

让咱们看看张量如何与代码示例一起工作。然而首先,要应用TensorFlow对象,咱们须要导入TensorFlow库。咱们常常将NumPy与TensorFlow一起应用,因而咱们还能够应用以下行导入NumPy:

import tensorflow as tfimport numpy as np

张量的创立:创立张量对象

有几种办法能够创立tf.Tensor对象。让咱们从几个例子开始。能够应用多个TensorFlow函数创立张量对象,如下例所示:

# 你能够用`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承受形态作为必须的参数,因为它们的元素值是预先确定的。

张量对象的特色

tf.Tensor创建对象,它们有几个特色。首先,他们有维度数量。其次,它们有一个形态,一个由维度的长度组成的列表。所有张量都有一个大小,即张量中元素的总数。最初,它们的元素都被记录在一个对立的数据类型(datatype)中。让咱们认真看看这些特色。

维度

张量依据其维数进行分类:

  • Rank-0(标量)张量:蕴含单个值且没有轴的张量(0维);
  • Rank-1张量:蕴含单轴(一维)值列表的张量;
  • Rank-2张量:蕴含2个轴(2维)的张量;以及
  • Rank-N张量:蕴含N轴的张量(三维)。

例如,咱们能够通过向tf.constant传递一个三层嵌套的list对象来创立一个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)

咱们能够查看“rank_3_tensor”对象以后具备“.ndim”属性的维度数。

tensor_ndim = rank_3_tensor.ndimprint("The number of dimensions in our Tensor object is", tensor_ndim)
Output:The number of dimensions in our Tensor object is 3

形态

形态特色是每个张量都具备的另一个属性。它以列表的模式显示每个维度的大小。咱们能够查看应用.shape属性创立的rank_3_tensor对象的形态,如下所示:

tensor_shape = rank_3_tensor.shapeprint("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.dtypeprint("The data type selected for this Tensor object is", tensor_dtype)
Output:The data type selected for this Tensor object is <dtype: 'int32'>

张量运算

索引

索引是我的项目在序列中地位的数字示意。这个序列能够援用很多货色:一个列表、一个字符串或任意的值序列。

TensorFlow还遵循规范的Python索引规定,这相似于列表索引或NumPy数组索引。

对于索引的一些规定:

  1. 索引从零(0)开始。
  2. 负索引(“-n”)值示意从开端向后计数。
  3. 冒号(“:”)用于切片:开始:进行:步骤。
  4. 逗号(“,”)用于达到更深层次。

让咱们用以下几行创立rank_1_tensor:

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]

当初,让咱们用以下代码创立rank_2_tensor:

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

当初,咱们曾经介绍了索引的基本知识,让咱们看看咱们能够对张量进行的基本操作。

张量根本运算

你能够轻松地对张量进行根本的数学运算,例如:

  1. 加法
  2. 元素乘法
  3. 矩阵乘法
  4. 求最大值或最小值
  5. 找到Max元素的索引
  6. 计算Softmax值

让咱们看看这些运算。咱们将创立两个张量对象并利用这些操作。

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)

留神:Matmul操作是深度学习算法的外围。因而,只管你不会间接应用matmul,但理解这些操作是至关重要的。

咱们下面列出的其余操作示例:

# 应用' 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'函数计算softmaxprint("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数组和pandas数据帧中一样,你也能够重塑张量对象。

这个变形操作十分快,因为底层数据不须要复制。对于重塑操作,咱们能够应用tf.reshape函数

# 咱们的初始张量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)

如你所见,咱们能够很容易地重塑咱们的张量对象。但要留神的是,在进行重塑操作时,开发人员必须是正当的。否则,张量可能会混同,甚至会产生谬误。所以,小心点????.

播送

当咱们尝试应用多个张量对象进行组合操作时,较小的张量能够主动舒展以适应较大的张量,就像NumPy数组一样。例如,当你尝试将标量张量与秩2张量相乘时,标量将被拉伸以乘以每个秩2张量元素。参见以下示例:

m = tf.constant([5])n = tf.constant([[1,2],[3,4]])print(tf.multiply(m, n))
Output:tf.Tensor( [[ 5 10]              [15 20]], shape=(2, 2), dtype=int32)

多亏了播送,在对张量进行数学运算时,你不用放心大小匹配。

张量的非凡类型

咱们偏向于生成矩形的张量,并将数值存储为元素。然而,TensorFlow还反对不规则或非凡的张量类型,这些类型包含:

  1. 参差不齐的张量
  2. 字符串张量
  3. 稠密张量

让咱们认真看看每一个都是什么。

参差不齐的张量

参差不齐张量是沿着尺寸轴具备不同数量元素的张量

能够构建不规则张量,如下所示

ragged_list = [[1, 2, 3],[4, 5],[6]]ragged_tensor = tf.ragged.constant(ragged_list)print(ragged_tensor)
Output:<tf.RaggedTensor [[1, 2, 3],                   [4, 5],                   [6]]>

字符串张量

字符串张量是存储字符串对象的张量。咱们能够建设一个字符串张量,就像你创立一个一般的张量对象。然而,咱们将字符串对象作为元素而不是数字对象传递,如下所示:

string_tensor = tf.constant(["With this",                              "code, I am",                              "creating a String Tensor"])print(string_tensor)
Output:tf.Tensor([b'With this'            b'code, I am'            b'creating a String Tensor'],  shape=(3,), dtype=string)

稠密张量

最初,稠密张量是稠密数据的矩形张量。当数据中有空值时,稠密张量就是对象。创立稠密张量有点耗时,应该更支流一些。这里有一个例子:

sparse_tensor = tf.sparse.SparseTensor(indices=[[0, 0], [2, 2], [4, 4]],                                        values=[25, 50, 100],                                        dense_shape=[5, 5])# 咱们能够把稠密张量转换成密集张量print(tf.sparse.to_dense(sparse_tensor))
Output:tf.Tensor( [[ 25   0   0   0   0]            [  0   0   0   0   0]            [  0   0  50   0   0]            [  0   0   0   0   0]            [  0   0   0   0 100]], shape=(5, 5), dtype=int32)

结尾

咱们曾经胜利地介绍了TensorFlow的张量对象的基础知识。

这应该会给你很大的信念,因为你当初对TensorFlow框架的基本知识理解得更多了。

查看本教程系列的第1局部:https://link.medium.com/yJp16...

原文链接:https://towardsdatascience.co...

欢送关注磐创AI博客站:
http://panchuang.net/

sklearn机器学习中文官网文档:
http://sklearn123.com/

欢送关注磐创博客资源汇总站:
http://docs.panchuang.net/