作者|Orhan G. Yal??n
編譯|VK
來源|Towards Datas Science
如果你正在讀這篇文章,我相信我們有著相似的興趣,現在/將來也會從事類似的行業,

在這篇文章中,我們將深入研究Tensorflow Tensor的細節,我們將在以下五個簡單步驟中介紹與Tensorflow的Tensor中相關的所有主題:
-
第一步:張量的定義→什么是張量?
-
第二步:創建張量→創建張量物件的函式
-
第三步:張量物件的特征
-
第四步:張量操作→索引、基本張量操作、形狀操作、廣播
-
第五步:特殊張量
張量的定義:什么是張量

張量是TensorFlow的均勻型多維陣列,它們非常類似于NumPy陣列,并且它們是不可變的,這意味著一旦創建它們就不能被更改,只能使用編輯創建新副本,
讓我們看看張量如何與代碼示例一起作業,但是首先,要使用TensorFlow物件,我們需要匯入TensorFlow庫,我們經常將NumPy與TensorFlow一起使用,因此我們還可以使用以下行匯入NumPy:
import tensorflow as tf
import 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.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屬性創建的rank_3_tensor物件的形狀,如下所示:
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 <dtype: 'int32'>
張量運算
索引
索引是專案在序列中位置的數字表示,這個序列可以參考很多東西:一個串列、一個字串或任意的值序列,
TensorFlow還遵循標準的Python索引規則,這類似于串列索引或NumPy陣列索引,
關于索引的一些規則:
-
索引從零(0)開始,
-
負索引(“-n”)值表示從末尾向后計數,
-
冒號(“:”)用于切片:開始:停止:步驟,
-
逗號(“,”)用于達到更深層次,
讓我們用以下幾行創建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
現在,我們已經介紹了索引的基本知識,讓我們看看我們可以對張量進行的基本操作,
張量基本運算
你可以輕松地對張量進行基本的數學運算,例如:
-
加法
-
元素乘法
-
矩陣乘法
-
求最大值或最小值
-
找到Max元素的索引
-
計算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'函式計算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陣列和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還支持不規則或特殊的張量型別,這些型別包括:
-
參差不齊的張量
-
字串張量
-
稀疏張量

讓我們仔細看看每一個都是什么,
參差不齊的張量
參差不齊張量是沿著尺寸軸具有不同數量元素的張量
可以構建不規則張量,如下所示
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/yJp16uPoqab
原文鏈接:https://towardsdatascience.com/mastering-tensorflow-tensors-in-5-easy-steps-35f21998bb86
歡迎關注磐創AI博客站:
http://panchuang.net/
sklearn機器學習中文官方檔案:
http://sklearn123.com/
歡迎關注磐創博客資源匯總站:
http://docs.panchuang.net/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/175058.html
標籤:其他
