0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

五個簡單步驟掌握TensorFlow中的Tensor

電子設(shè)計 ? 來源:電子設(shè)計 ? 作者:電子設(shè)計 ? 2020-12-24 14:35 ? 次閱讀

在這篇文章中,我們將深入研究Tensorflow Tensor的實現(xiàn)細(xì)節(jié)。我們將在以下五個簡單步驟中介紹與Tensorflow的Tensor中相關(guān)的所有主題:第一步:張量的定義→什么是張量?第二步:創(chuàng)建張量→創(chuàng)建張量對象的函數(shù)第三步:張量對象的特征第四步:張量操作→索引、基本張量操作、形狀操作、廣播第五步:特殊張量張量的定義:什么是張量?

張量是TensorFlow的均勻型多維數(shù)組,它非常類似于NumPy數(shù)組,并且是不可變的,這意味著一旦創(chuàng)建它們就不能被更改。首先,要使用TensorFlow對象,我們需要導(dǎo)入TensorFlow庫,因為我們經(jīng)常將NumPy與TensorFlow一起使用,因此我們也可以導(dǎo)入NumPy:import tensorflow as tf

import numpy as np

張量的創(chuàng)建:創(chuàng)建張量對象有多種方法可以創(chuàng)建tf.Tensor對象,同時也可以使用多個TensorFlow函數(shù)來創(chuàng)建張量對象,如下例所示:# 你可以用`tf.constant`函數(shù)創(chuàng)建tf.Tensor對象:
x = tf.constant([[1, 2, 3, 4 ,5]])
# 你可以用`tf.ones`函數(shù)創(chuàng)建tf.Tensor對象:
y = tf.ones((1,5))
# 你可以用`tf.zeros`函數(shù)創(chuàng)建tf.Tensor對象:
z = tf.zeros((1,5))
# 你可以用`tf.range`函數(shù)創(chuàng)建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)

如你所見,我們使用三個不同的函數(shù)創(chuàng)建了形狀(1,5)的張量對象,使用tf.range()函數(shù)創(chuàng)建了形狀(5,)的第四個張量對象。注意,tf.ones的和tf.zeros接受形狀作為必需的參數(shù),因為它們的元素值是預(yù)先確定的。張量對象的特征tf.Tensor創(chuàng)建對象有幾個特征。首先,他們有維度數(shù)量;其次,它們有一個形狀,一個由維度的長度組成的列表;所有張量都有一個大小,即張量中元素的總數(shù);最后,它們的元素都被記錄在一個統(tǒng)一的數(shù)據(jù)類型(datatype)中。讓我們仔細(xì)看看這些特征。維度張量根據(jù)其維數(shù)進(jìn)行分類:Rank-0(標(biāo)量)張量:包含單個值且沒有軸的張量(0維);Rank-1張量:包含單軸(一維)值列表的張量;Rank-2張量:包含2個軸(2維)的張量;以及Rank-N張量:包含N軸的張量(三維)。

例如,我們可以通過向tf.constant傳遞一個三層嵌套的list對象來創(chuàng)建一個Rank-3張量。我們可以將數(shù)字分割成一個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”對象當(dāng)前具有“.ndim”屬性的維度數(shù)。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屬性創(chuàng)建的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函數(shù)。最后,我們將使用實例函數(shù).NumPy()將輸出轉(zhuǎn)換為NumPy,以獲得更具可讀性的結(jié)果: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

數(shù)據(jù)類型張量通常包含數(shù)字?jǐn)?shù)據(jù)類型,如浮點和整數(shù),但也可能包含許多其他數(shù)據(jù)類型,如復(fù)數(shù)和字符串。但是,每個張量對象必須將其所有元素存儲在一個統(tǒng)一的數(shù)據(jù)類型中,因此,我們還可以使用.dtype屬性查看為特定張量對象選擇的數(shù)據(jù)類型,如下所示: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'>

張量運算索引索引是項目在序列中位置的數(shù)字表示,這個序列可以引用很多東西:一個列表、一個字符串或任意的值序列。TensorFlow還遵循標(biāo)準(zhǔn)的Python索引規(guī)則,這類似于列表索引或NumPy數(shù)組索引。關(guān)于索引的一些規(guī)則:索引從零(0)開始。負(fù)索引(“-n”)值表示從末尾向后計數(shù)。冒號(“:”)用于切片。逗號(“,”)用于進(jìn)入更深的維度。讓我們用以下幾行創(chuàng)建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)

測試一下我們的規(guī)則1,2,3:# 規(guī)則1,索引從0開始
print("First element is:",
rank_1_tensor[0].numpy())
# 規(guī)則2,負(fù)索引
print("Last element is:",
rank_1_tensor[-1].numpy())
# 規(guī)則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]

現(xiàn)在,讓我們用以下代碼創(chuàng)建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條規(guī)則: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())
# 規(guī)則4, 逗號用于進(jìn)入更深的維度
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

現(xiàn)在,我們已經(jīng)介紹了索引的基本知識,讓我們看看我們可以對張量進(jìn)行的基本操作。張量基本運算你可以輕松地對張量進(jìn)行基本的數(shù)學(xué)運算,例如:加法元素乘法矩陣乘法求最大值或最小值找到Max元素的索引計算Softmax值讓我們看看這些運算,我們將創(chuàng)建兩個張量對象并應(yīng)用這些操作。a = tf.constant([[2, 4],
[6, 8]], dtype=tf.float32)
b = tf.constant([[1, 3],
[5, 7]], dtype=tf.float32)

我們可以從加法開始。# 我們可以使用' tf.add() '函數(shù)并將張量作為參數(shù)傳遞。
add_tensors = tf.a(chǎn)dd(a,b)
print(add_tensors)
Output:
tf.Tensor( [[ 3. 7.]
[11. 15.]], shape=(2, 2), dtype=float32)

乘法# 我們可以使用' tf.multiply() '函數(shù)并將張量作為參數(shù)傳遞。
multiply_tensors = tf.multiply(a,b)
print(multiply_tensors)
Output:
tf.Tensor( [[ 2. 12.]
[30. 56.]], shape=(2, 2), dtype=float32)
矩陣乘法:# 我們可以使用' tf.matmul() '函數(shù)并將張量作為參數(shù)傳遞。
matmul_tensors = tf.matmul(a,b)
print(matmul_tensors)
Output:
tf.Tensor( [[ 2. 12.]
[30. 56.]], shape=(2, 2), dtype=float32)

注意:Matmul操作是深度學(xué)習(xí)算法的核心,因此,盡管你不會直接使用matmul,但了解這些操作是至關(guān)重要的。我們上面列出的其他操作示例:# 使用' tf.reduce_max() '和' tf.reduce_min() '函數(shù)可以找到最大值或最小值
print("The Max value of the tensor object b is:",
tf.reduce_max(b).numpy())

# 使用' tf.a(chǎn)rgmax() '函數(shù)可以找到最大元素的索引
print("The index position of the max element of the tensor object b is:",
tf.a(chǎn)rgmax(b).numpy())

# 使用 tf.nn.softmax'函數(shù)計算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數(shù)組和pandas數(shù)據(jù)幀中一樣,你也可以重塑張量對象。這個變形操作非??欤驗榈讓訑?shù)據(jù)不需要復(fù)制。對于重塑操作,我們可以使用tf.reshape函數(shù)# 我們的初始張量
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參數(shù)傳遞-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)

如你所見,我們可以很容易地重塑我們的張量對象,但要注意的是,在進(jìn)行重塑操作時,開發(fā)人員的操作必須是合理的,否則,張量可能會混淆,甚至?xí)a(chǎn)生錯誤。廣播當(dāng)我們嘗試使用多個張量對象進(jìn)行組合操作時,較小的張量可以自動伸展以適應(yīng)較大的張量,就像NumPy數(shù)組一樣。例如,當(dāng)你嘗試將標(biāo)量張量與秩2張量相乘時,標(biāo)量將被拉伸以乘以每個秩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)

由于廣播操作,在對張量進(jìn)行數(shù)學(xué)運算時,我們不必?fù)?dān)心大小匹配。張量的特殊類型我們常常會生成矩形張量,并將數(shù)值存儲為元素,但是,TensorFlow還支持不規(guī)則或特殊的張量類型,這些類型包括:參差不齊的張量字符串張量稀疏張量

讓我們仔細(xì)看看每一個都是什么。參差不齊的張量參差不齊張量是沿著尺寸軸具有不同數(shù)量元素的張量可以構(gòu)建不規(guī)則張量,如下所示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]]>

字符串張量字符串張量是存儲字符串對象的張量。我們可以建立一個字符串張量,就像你創(chuàng)建一個普通的張量對象一樣,但是,我們將字符串對象作為元素而不是數(shù)字對象傳遞,如下所示: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)

稀疏張量最后,稀疏張量是稀疏數(shù)據(jù)的矩形張量。當(dāng)數(shù)據(jù)中有空值時,稀疏張量就是對象。創(chuàng)建稀疏張量有點耗時,這里有一個例子:sparse_tensor = tf.sparse.SparseTensor(indices=[[0, 0], [2, 2], [4, 4]],
values=[25, 50, 100],
dense_shape=[5, 5])

# 我們可以把稀疏張量轉(zhuǎn)換成密集張量
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)

結(jié)尾本文我們介紹了TensorFlow的張量對象的基礎(chǔ)知識。這應(yīng)該會讓你對TensorFlow框架的基本知識了解得更多了。

審核編輯:符乾江


聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 函數(shù)
    +關(guān)注

    關(guān)注

    3

    文章

    4237

    瀏覽量

    61969
  • tensorflow
    +關(guān)注

    關(guān)注

    13

    文章

    327

    瀏覽量

    60413
收藏 人收藏

    評論

    相關(guān)推薦

    改善升壓轉(zhuǎn)換器PCB布局的步驟

    電子發(fā)燒友網(wǎng)站提供《改善升壓轉(zhuǎn)換器PCB布局的步驟.pdf》資料免費下載
    發(fā)表于 09-04 10:22 ?0次下載
    改善升壓轉(zhuǎn)換器PCB布局的<b class='flag-5'>五</b><b class='flag-5'>個</b><b class='flag-5'>步驟</b>

    交流電轉(zhuǎn)直流電的步驟

    交流電轉(zhuǎn)直流電(AC to DC)是電力電子學(xué)的一重要領(lǐng)域,廣泛應(yīng)用于各種電子設(shè)備和系統(tǒng)。本文將詳細(xì)介紹交流電轉(zhuǎn)直流電的
    的頭像 發(fā)表于 08-27 09:29 ?374次閱讀

    示波器電流探頭最簡單步驟是什么

    具有重要意義。下面介紹示波器電流探頭的三簡單步驟步驟一:選擇合適的電流探頭 確定測量范圍 :首先,需要根據(jù)待測電路的電流大小選擇合適的電流探頭。電流探頭通常有不同的量程,如10A、100A、1000A等,選擇一
    的頭像 發(fā)表于 08-09 14:24 ?228次閱讀

    如何在Tensorflow實現(xiàn)反卷積

    TensorFlow實現(xiàn)反卷積(也稱為轉(zhuǎn)置卷積或分?jǐn)?shù)步長卷積)是一涉及多個概念和步驟的過程。反卷積在深度學(xué)習(xí)領(lǐng)域,特別是在圖像分割、圖像超分辨率、以及生成模型(如生成對抗網(wǎng)絡(luò)GA
    的頭像 發(fā)表于 07-14 10:46 ?423次閱讀

    簡述使用波特力模型的三步驟

    企業(yè)了解行業(yè)的競爭環(huán)境,從而制定相應(yīng)的競爭策略。以下是使用波特力模型的三步驟。 第一步:識別行業(yè) 在使用波特力模型之前,首先需要明確分析的行業(yè)范圍。行業(yè)的定義可以根據(jù)產(chǎn)品、服務(wù)、
    的頭像 發(fā)表于 07-05 14:34 ?296次閱讀

    tensorflow和pytorch哪個更簡單?

    PyTorch更簡單。選擇TensorFlow還是PyTorch取決于您的具體需求和偏好。如果您需要一易于使用、靈活且具有強大社區(qū)支持的框架,PyTorch可能是一更好的選擇。如果
    的頭像 發(fā)表于 07-05 09:45 ?380次閱讀

    tensorflow簡單的模型訓(xùn)練

    在本文中,我們將詳細(xì)介紹如何使用TensorFlow進(jìn)行簡單的模型訓(xùn)練。TensorFlow是一開源的機器學(xué)習(xí)庫,廣泛用于各種機器學(xué)習(xí)任務(wù),包括圖像識別、自然語言處理等。我們將從安裝
    的頭像 發(fā)表于 07-05 09:38 ?295次閱讀

    keras模型轉(zhuǎn)tensorflow session

    在這篇文章,我們將討論如何將Keras模型轉(zhuǎn)換為TensorFlow session。 Keras和TensorFlow簡介 Keras是一高級神經(jīng)網(wǎng)絡(luò)API,它提供了一種
    的頭像 發(fā)表于 07-05 09:36 ?315次閱讀

    如何在TensorFlow構(gòu)建并訓(xùn)練CNN模型

    TensorFlow構(gòu)建并訓(xùn)練一卷積神經(jīng)網(wǎng)絡(luò)(CNN)模型是一涉及多個步驟的過程,包括數(shù)據(jù)預(yù)處理、模型設(shè)計、編譯、訓(xùn)練以及評估。下面
    的頭像 發(fā)表于 07-04 11:47 ?387次閱讀

    變頻器快慢調(diào)速最簡單步驟

    調(diào)速的三簡單步驟。 一、變頻器的基本原理 在了解變頻器快慢調(diào)速的步驟之前,我們首先需要了解變頻器的基本原理。變頻器是一種將工頻電源轉(zhuǎn)換為可調(diào)頻率電源的電氣設(shè)備,通過改變輸出頻率的大小,實現(xiàn)對電動機轉(zhuǎn)速的控
    的頭像 發(fā)表于 06-17 15:17 ?1277次閱讀

    研控8線步進(jìn)電機最簡單步驟

    步進(jìn)電機是一種將電脈沖信號轉(zhuǎn)換為機械角位移的電機,廣泛應(yīng)用于各種自動化設(shè)備和機器人中。研控8線步進(jìn)電機是一種常見的步進(jìn)電機類型,具有較高的精度和穩(wěn)定性。本文將詳細(xì)介紹研控8線步進(jìn)電機的三簡單步驟
    的頭像 發(fā)表于 06-12 09:16 ?726次閱讀

    如何使用TensorFlow構(gòu)建機器學(xué)習(xí)模型

    在這篇文章,我將逐步講解如何使用 TensorFlow 創(chuàng)建一簡單的機器學(xué)習(xí)模型。
    的頭像 發(fā)表于 01-08 09:25 ?803次閱讀
    如何使用<b class='flag-5'>TensorFlow</b>構(gòu)建機器學(xué)習(xí)模型

    【飛騰派4G版免費試用】第章:使用C++部署tflite模型到飛騰派

    Tensor 的維度,是 TfLiteTensor 的 TfLiteIntArray* dims 成員,這里 TfLiteIntArray 中含有維度,和具體每一維的形狀 關(guān)鍵步驟 我在實際開發(fā)的過程
    發(fā)表于 12-27 21:17

    準(zhǔn)確測量絕緣電阻的步驟

    準(zhǔn)確測量絕緣電阻的步驟? 準(zhǔn)確測量絕緣電阻是電氣工程領(lǐng)域中的一項基本任務(wù)。在電氣設(shè)備和系統(tǒng),絕緣電阻測量是確保電器設(shè)備安全可靠運行的重要步驟
    的頭像 發(fā)表于 12-25 11:31 ?1473次閱讀

    變壓器維護的簡單步驟

    有計劃的維修或更換。緊急維修或更換的成本要高得多,并導(dǎo)致生產(chǎn)損失。 日常變壓器維護的簡單步驟 日常維護對于延長變壓器壽命至關(guān)重要,涉及一些基本步驟。 對于較小的封裝變壓器,定期清潔變壓器外殼對于防止灰塵和污垢積聚會阻礙
    的頭像 發(fā)表于 10-24 16:26 ?1766次閱讀