5個簡單的步驟掌握Tensorflow的Tensor

2021-01-11 人工智慧遇見磐創

在這篇文章中,我們將深入研究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數組索引。

關於索引的一些規則:

索引從零(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'函數計算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還支持不規則或特殊的張量類型,這些類型包括:

參差不齊的張量字符串張量稀疏張量

讓我們仔細看看每一個都是什麼。

參差不齊的張量

參差不齊張量是沿著尺寸軸具有不同數量元素的張量

可以構建不規則張量,如下所示

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框架的基本知識了解得更多了。

相關焦點

  • TensorFlow 攜手 NVIDIA,使用 TensorRT 優化 TensorFlow Serving...
    HTTP/REST API at:localhost:8501 …$ curl -o /tmp/resnet/resnet_client.py https://raw.githubusercontent.com/tensorflow/serving/master/tensorflow_serving/example/resnet_client.py
  • TensorFlow極速入門
    一、前言目前,深度學習已經廣泛應用於各個領域,比如圖像識別,圖形定位與檢測,語音識別,機器翻譯等等,對於這個神奇的領域,很多童鞋想要一探究竟,這裡拋磚引玉的簡單介紹下最火的深度學習開源框架 tensorflow。
  • 最簡單的深度學習TensorFlow應用舉例!
    小編最近準備入坑TensorFlow,沒系統的學python,想邊學tf順便一起學python,花很多時間配了環境,今天終於要拿出來曬曬太陽了~這裡為大家帶來了TensorFlow的最簡單的例子。小編我的電腦很一般,沒有32G內存,也沒有1080,就windows上直接裝了23333windows+python 3.6+pycharm+tensorflow cpu話不多說,直接線性回歸,上圖。
  • 步履不停:TensorFlow 2.4新功能一覽!
    參數伺服器訓練教程           https://tensorflow.google.cn/tutorials/distribute/parameter_server_training    ClusterCoordinator           https://tensorflow.google.cn/api_docs/python
  • tensorflow初級必學算子
    在之前的文章中介紹過,tensorflow框架的核心是將各式各樣的神經網絡抽象為一個有向無環圖,圖是由tensor以及tensor變換構成;雖然現在有很多高階API可以讓開發者忽略這層抽象,但對於靈活度要求比較高的算法仍然需要開發者自定義網絡圖,所以建議開發者儘量先學習tf1.x
  • Tensorflow基礎教程15天之創建Tensor
    在將Tensor定義為Variable之後,Tensorflow才會將其傳入計算圖。如何操作我們將在這裡介紹創建Tensor的主要方法。序列TensorTensorflow允許我們定義數組Tensor。
  • TensorFlow極簡教程:創建、保存和恢復機器學習模型
    代碼的結構與之前相同,唯一不同的是這次使用張量(tensor)操作來定義誤差。使用張量可以並行(parallel)運行代碼。每個數據點被看作是來自獨立同分布的樣本。因為每個數據點假定是獨立的,所以計算也是獨立的。當使用張量時,每個數據點都在分隔的計算內核上運行。我們有 8 個數據點,所以如果你有一個有八個內核的計算機,它的運行速度應該快八倍。
  • 如何使用TensorFlow Hub的ESRGAN模型來在安卓app中生成超分圖片
    file_path=org%2Ftensorflow%2Ftensorflow-lite%2F2.3.0%2Ftensorflow-lite-2.3.0.aar" dest "${project.rootDir}/libraries/tensorflow-lite-2.3.0.aar" overwrite false retries 5 } } task downloadTFLiteGPUDelegateAARFile
  • TensorFlow 中文資源全集,學習路徑推薦
    入門教程,簡單的模型學習和運行。實戰項目,根據自己的需求進行開發。/GitHub:https://github.com/tensorflow安裝教程中文安裝教程Mac安裝:http://www.cnblogs.com/tensorflownews/p/7298646.htmlubuntu 16.04 安裝 tensorflow-gpu:http://www.tensorflownews.com/2017/09/02/tensorflow-gpu-install-ubuntu
  • 機器學習中的embedding原理及tensorflow 相關API的理解
    原文地址:https://gshtime.github.io/2018/06/01/tensorflow-embedding-lookup-sparse/代碼地址:git@github.com:gshtime/tensorflow-api.git# embedding原理常見的特徵降維方法主要有PCA、SVD等。
  • Tensorflow 全網最全學習資料匯總之Tensorflow 的入門與安裝【2】
    《TensorFlow學習筆記1:入門》連結:http://www.jeyzhang.com/tensorflow-learning-notes.html本文與上一篇的行文思路基本一致,首先概括了TensorFlow的特性,然後介紹了graph、session、variable 等基本概念的含義,以具體代碼的形式針對每個概念給出了進一步的解釋
  • 玩轉TensorFlow?你需要知道這30功能
    地址是:tensorflow.org/tfx/?網址是:https://www.tensorflow.org/tfx/transform/?網址是:https://www.tensorflow.org/serving/?
  • 在Windows中安裝Tensorflow和Kears深度學習框架
    建立Tensorflow的Anaconda虛擬環境在一臺計算機中,我們常常需要安裝很多軟體,但是每個軟體所需要的Python的關聯模塊或版本不相同。例如,我們要使用Python開發開發網站系統,安裝的網站框架可能需要Python2.X的版本,但是安裝Tensorflow需要Python3.5的版本,此時就會發生版本不一致的問題。
  • 如何利用TensorFlow.js部署簡單的AI版「你畫我猜」圖像識別應用
    該數據集包含 345 個類別的大約 5 千萬張手繪圖像。部分圖像類別流程我們將使用 Keras 框架在谷歌 Colab 免費提供的 GPU 上訓練模型,然後使用 TensorFlow.js 直接在瀏覽器上運行模型。
  • TensorFlow 資源大全中文版
    – 一個基於深度學習的聊天機器人colornet – 使用神經網絡給灰度圖像著色圖像生成器 – Show and Tell算法實現Attention based的自動圖像生成器 – Show, Attend and Tell算法實現Weakly_detector – 用於定位的深度特徵Dynamic Capacity Networks
  • 深度解讀TensorFlow,了解它的最新發展!
    Tensorboard是tensorflow內置的一個可視化工具,它通過將tensorflow程序輸出的日誌文件的信息可視化,使得tensorflow程序的理解、調試和優化更加簡單高效。Tensorboard的可視化依賴於tensorflow程序運行輸出的日誌文件,因而tensorboard和tensorflow程序在不同的進程中運行。
  • 終於來了,TensorFlow 新增官方 Windows 支持
    現在你可以使用命令 C:\> pip install tensorflow 安裝 TensorFlow 了。GPU 支持的命令:C:\> pip install tensorflow-gpu有關 TensorFlow Windows 支持的更多細節請閱讀 r0.12 的版本注釋。
  • 教程| 如何用TensorFlow在安卓設備上實現深度學習推斷
    將 WaveNet 安裝到安卓的三個步驟。從源安裝和配置 TensorFlow(https://www.tensorflow.org/install/install_sources)。3.在 TensorFlow 目錄下運行下列命令行:bazel build tensorflow/tools/graph_transforms:transform_graphbazel-bin/tensorflow/tools/graph_transforms/transform_graph \ --in_graph=/your/.pb/file \ --outputs="output_node_name
  • 基於RTX2060構建TensorFlow-gpu(keras)學習平臺
    開始菜單運行anaconda navigator檢查是否安裝了notebook(默認有安裝)三、安裝tensorflow/keras在激活的環境中安裝:1. 如果機器上有gpu,則安裝gpu版本,沒有GPU就安裝cpu版。
  • 分享TensorFlow Lite應用案例
    不支持的 op 主要集中有兩大類情況:   包括控制流 (control flow) 的 op   相對於 TF mobile,TF Lite 的部分 op 只支持最簡單的 case   目前的一個好的消息就是 TensorFlow 項目組一直在持續的推進對 RNN 系列的支持。   3.