Tensor 陣列

      在〈Tensor 陣列〉中尚無留言

tensorflow 早期 1.0 版本,陣列需使用 tf.placeholder 方法宣告。但到了 2.0後,tf.placeholder就不見了,取而代之的方法如下

a = tf.zeros(shape=(維度))    : 建立數值都為 0 的常數
b = tf.ones(shape=(維度)) : 建立數值都為 1 的常數
c = tf.fill([2,3], 5) : 建立數值都為 5 的常數,維度為 2 列 3 行
d = tf.range(1, 9, 2) : 建立數值由 1~8(不含9),且每次隔2的一維陣列
e = tf.reshape(d, (2,2)) : 改成2列2行的陣列,(2,2) 亦可寫成 [2,2]
f = tf.random.normal((維度)) : 建立值符合常態分佈數列的常數
g = tf.random.uniform((維度)) : 建立值符合均勻分佈數列的常數

維度

TensorFlow的陣列維度,跟 numpy 其實都是一樣的,分別為純量(0維陣列),向量(1維陣列),矩陣(2維矩陣)等等各維的陣列。

純量

就是前面所介紹的 tf.Tensor常數,又稱為 0 維陣列,也就是說,只有一個數字。在底下的代碼中,tf.constant(1)跟tf.ones([], dtype=tf.int32)是一模一樣的。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
a=tf.constant(1)
b=tf.ones([], dtype=tf.int32)
print(a)
print(b)
結果 :
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)

一維一元素陣列

底下產生一維且只有一個元素的陣列。列印出來的結果,有”[]”。

同樣的 tf.ones(shape=(1)) 與 tf.ones((1)) 是一樣的,也可以是 tf.ones([1]) 

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
a=tf.ones(shape=[1], dtype=tf.int32)
print(a.numpy())
結果 : [1]

純量與一維一元素的差異

純量 a 與一維一元素 b 好像看起來差不多,只差在純量印出來沒有 “[]”,但一維一元素有 “[]”。再看一下如下代碼,a 不能指定索引, 如 a[0],但b可以指定索引b[0]。所以嚴格來講,a 不能算是陣列

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
a=tf.ones(shape=[], dtype=tf.int32)
b=tf.ones(shape=[1], dtype=tf.int32)
print(a.numpy()) #不能指定索引 a[0]
print(b[0].numpy())
print(b.numpy())

結果 :
1
1
[1]

一維多元素

一維多元素與一維一元素一樣,都可以指定索引來列印。

同樣的 tf.ones(shape=(5)) 與 tf.ones((5)) 是一樣的,也可以是 tf.ones([5]) 

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
a=tf.ones(shape=[5], dtype=tf.int32)
print(a[2].numpy())
print(a.numpy())
結果 :
1
[1 1 1 1 1]

二維陣列

底下產生二列三行的二維陣列。 tf.ones(shape=(2, 3)) 與 tf.ones((2, 3)) 是一樣的,也可以是 tf.ones([2, 3]) 

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
a = tf.zeros(shape=[2,3])
print(a.numpy())
結果 :
[[0. 0. 0.]
[0. 0. 0.]]

矩陣計算

矩陣計算有 tf.reshape() : 調整矩陣維度, tf.eye(3) : 建立3*3的二維矩陣,對角皆為1,tf.matnul() : 矩陣相乘

a=tf.eye(4)
print(a.numpy())
結果 :
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

矩陣相乘時,是以第一個陣列的列,與第二個陣列的行相乘後總合,所以第一個陣列的 “行”,必需與第二個陣列的 “列” 相同。比如 a 為 [2,3] 的2 維矩陣,b 為 [3, 5]的矩陣,相乘後為 [2, 5]的矩陣。

但如果是a*b,則是各個元素的相乘,所以a及b必需是相同的維度。

a=tf.constant([[1,2,3],[4, 5, 6]])
b=tf.constant([[1,2],[3,4],[5,6]])
print(tf.matmul(a,b))
結果 :
tf.Tensor(
[[22 28]
[49 64]], shape=(2, 2), dtype=int32)

陣列指定值

陣列要指定其值時,需先使用 tf.ones() 或 tf.zeros() 產生常數張量指定陣列的維度,請注意,此時是常數張量,裏面的值當然是不能改變。

所以需使用 tf.Variable 創造另一個變數張量,再使用[x, y].assign(value) 設定其值。

import tensorflow as tf
a = tf.zeros([2,3])
b=tf.Variable(a)
b[0, 0].assign(10)
print(b.numpy())
結果:
[[10. 0. 0.]
[ 0. 0. 0.]]

列印維度

import tensorflow as tf
a = tf.ones([2,3])
print(a.shape[0], a.shape[1])
print(a.shape)
print(tf.shape(a))
print(shape.numpy())
結果: 2 3 (2, 3) tf.Tensor([2 3], shape=(2,), dtype=int32)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *