Tensor 基本觀念 (2)
前言 & 概述
Tensor 指的是多維度的陣列,是深度學習中最基本的運算元素。本文參考 TensorFlow 官方教學,將 Tensor 的相關介紹,以更簡單易懂的方式介紹給讀者!我們將 Tensor 基本觀念的介紹分為兩個部分:(1)、(2) 與 (3)。
在本篇文章 (2) 中,我們將學習如何透過 Python 中 Indexing 的概念取得 Tensor 中的特定元素,以及操作 Tensor 的形狀。
Tensor Indexing
在 TensorFlow 中,我們可以使用 Python 程式語言原來的 Indexing 概念,取得 Tensor 中的特定元素。Python Indexing 的基本三原則:
- Index 從 0 開始
- Index 為負數時表示從最後往前算
- 冒號的意義為 => 開始 : 間隔 : 停止
舉例來說,首先我們建立一個 tf.Tensor。
rank_1_tensor = tf.constant([0, 1, 2, 3, 4, 5, 7, 11, 30]) print(rank_1_tensor) # output tf.Tensor([ 0 1 2 3 4 5 7 11 30], shape=(9,), dtype=int32)
接著,我們想取得 Tensor 中的第 0 個 (也就是最前面的) 元素。
print(rank_1_tensor[0]) # output tf.Tensor(0, shape=(), dtype=int32)
接著,我們想取得 Tensor 中的前面 5 個元素。
print(rank_1_tensor[0:5]) # output tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32)
接著,我們想取得 Tensor 中的倒數第 1 個元素。
print(rank_1_tensor[-1]) # output tf.Tensor(30, shape=(), dtype=int32)
看到這裡,相信你已經發現 Tensor Indexing 的方式完全與 Python 中 List Indexing 的方式一樣呀! 接著,我們再舉一個 2 維 Tensor 演練一次。
首先,我們先建立一個 2 維的 Tensor:

如果我們想要取得 2 這一個元素,那就是指定第 0 個 Row、第 1 個 Col。

如果我們想要取得 1、3、5 這三個三素,那就是指定第 0 個 Row 到第 2 個 Row (但是實際上要寫 3) 並指定第 0 個 Col。

在深度學習的實作中,我們更常遇到 3 個維度以上的 Tensor,因此我們再以一個 3 維的 Tensor 舉例說明!
與前面相同,我們先建立一個 3 維的 Tensor。

如果我們希望取得 4、9、14、19、24、29 這幾個元素的話,程式碼應該怎麼寫呢? 乍看之下,可能不好理解,但是如果想成下面這張圖片的話,就會相對容易!由下圖我們可以知道,我們是要取得每一個 Layer 的每一個 Row的第 4 個 Col。

因此,在程式碼的實作上,第 1 個 Index 會填上「:」表示所有的 Layer;第 1 個 Index 會填上「:」表示所有的 Row;第 1 個 Index 會填上「4」表示第 4 個 Col。

操作 Tensor 的形狀 (Shape)
在實作深度學習演算法時,我們經常需要改變 Tensor 的 Shape,才能輸入到神經網路中。「改變 Tensor 的 Shape」稱為 Reshape。只要 Reshape 前後的元素數量是一致的,那 Reshape 的操作就會成功!
舉例來說,我們先建立一個 shape=(3, 2, 4) 的 Tensor。Tensor 中的元素皆為 1。

接著,我們將其形狀變成 shape=(3, 8)。

我們可以發現 Tensor 的 shape 由原來的 (3, 2, 4) 變成為 (3, 8)。原來的元素數量 (size) 為 3 x 2 x 4 = 24,後來的 size 為 3 x 8 = 24。因為 Reshape 前後的 size 一樣,因此 Reshape 的操作是可以成功的!
但是必須特別注意,Reshape 使用時機應該是合併或分裂「相鄰的維度」,而不是只要 size 相同就任意的 Reshape。
最後,我們經常需要將一個高維度的 Tensor 轉為 1 維,這個過程稱為 Flatten。我們只需要將 tf.reshape( ) 的 shape 設為 [-1] 就可以進行 Flatten 操作。

結語
在本篇文章中,我們瞭解了 Tensor Indexing 與 Tensor Reshape 的概念。在下一篇文章中,將會說明 Tensor 中元素的 Type、Broadcasting 與其餘不同種類的 Tensor。
👣 👣 👣 我喜歡撰寫程式開發、資料科學領域相關的文章,希望可以透過簡單的文字解釋複雜的觀念!如果你也有興趣可以到我的其他平台逛逛哦!
👉🏻 DataSci Ocean
👉🏻 YouTube
👉🏻 Instagram
系列文章
延伸閱讀
👉🏻 Google Colaboratory 介紹
👉🏻 條件機率 vs 聯合機率
👉🏻 將 Django App 部署到 Heroku on Mac
👉🏻 在 LINE Developers 上建立 LINE Bot
Like my work? Don't forget to support and clap, let me know that you are with me on the road of creation. Keep this enthusiasm together!

- Author
- More