AI - TensorFlow - 張量(Tensor)


張量(Tensor)

在Tensorflow中,變量統一稱作張量(Tensor)。

張量(Tensor)是任意維度的數組。

  • 0階張量:純量或標量 (scalar), 也就是一個數值,例如,\'Howdy\' 或 5
  • 1階張量:向量 (vector)或矢量,也就是一維數組(一組有序排列的數),例如,[2, 3, 5, 7, 11] 或 [5]
  • 2階張量:矩陣 (matrix),也就是二維數組(有序排列的向量),例如,[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]
  • 3階張量:三維的矩陣,也就是把矩陣有序地疊加起來,成為一個“立方體”
  • 以此類推,等等。

在大多數情況下,只會使用一個或多個低維張量(2階及以下)。

典型 TensorFlow 程序中的大多數代碼行都是指令,張量也是計算圖中的一種指令。
張量可以作為常量或變量存儲在圖中。

  • 常量是始終會返回同一張量值的指令,存儲的是值不會發生更改的張量。
  • 變量是會返回分配給它的任何張量的指令,存儲的是值會發生更改的張量。 

TensorFlow指南:

 

張量的定義

 1 # coding=utf-8  2 import tensorflow as tf  3 import os  4  5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  6  7 x = tf.constant([5.6], name="x_const") # tf.constant定義標量整數常量並傳入值  8 y = tf.Variable([0], name="y_Variable") # tf.Variable定義變量並傳入默認值  9 y = y.assign([3]) # 分配一個值 10 11 with tf.Session() as sess: # 圖必須在會話中運行,會話存儲了它所運行的圖的狀態 12 initialization = tf.global_variables_initializer() # 使用tf.Variable時,必須在會話開始時明確初始化變量 13 print("x: {}".format(sess.run(x))) 14 print("y: {}".format(sess.run(y)))

運行結果:

x: [5.6]
y: [3]

 

常量相加

 1 # coding=utf-8  2 import tensorflow as tf  3 import os  4  5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  6  7 g = tf.Graph() # 創建圖,雖然TensorFlow提供一個默認圖,仍建議創建自己的Graph,以便跟蹤狀態  8  9 with g.as_default(): # 將定義的圖作為默認 10 x = tf.constant(8, name="x_const") # tf.constant定義標量整數常量並傳入值 11 y = tf.constant(5, name="y_const") 12 z = tf.constant(4, name="z_const") 13 sum1 = tf.add(x, y, name="x_y_sum") # tf.add相加 14 sum2 = tf.add(z, sum1, name="x_y_z_sum") 15 with tf.Session() as sess: # 圖必須在會話中運行 16 print("sum1: {}".format(sum1.eval())) 17 print("sum2: {}".format(sum2.eval()))

 運行結果:

sum1: 13
sum2: 17

 

矢量相加、張量形狀與廣播

 1 # coding=utf-8
 2 import tensorflow as tf
 3 import os
 4 
 5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 6 
 7 try:
 8     tf.contrib.eager.enable_eager_execution()
 9     print("# TF imported with eager execution!")
10 except ValueError:
11     print("# TF already imported with eager execution!")
12 
13 # ### 矢量(一維張量)加法
14 primes = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)  # 包含質數的primes矢量
15 ones = tf.ones([6], dtype=tf.int32)  # 值全為1的ones矢量
16 just_beyond_primes = tf.add(primes, ones)  # 通過對前兩個矢量執行元素級加法而創建的矢量
17 twos = tf.constant([2, 2, 2, 2, 2, 2], dtype=tf.int32)
18 primes_doubled = primes * twos  # 通過將primes矢量中的元素翻倍而創建的矢量
19 print("primes: ", primes)
20 print("ones: ", ones)
21 print("just_beyond_primes: ", just_beyond_primes)
22 print("primes_doubled: ", primes_doubled)
23 
24 some_matrix = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)
25 print("some_matrix: ", some_matrix)  # 輸出張量將返回其值、形狀以及存儲在張量中的值的類型
26 print("value of some_matrix is:\n", some_matrix.numpy())  # 調用張量的numpy方法會返回該張量的值(以NumPy數組形式)
27 
28 # ### 張量形狀
29 scalar = tf.zeros([])  # 標量
30 vector = tf.zeros([3])  # 值全為0的矢量
31 matrix = tf.zeros([2, 3])  # 值全為0的2行3列矩陣
32 print('scalar has shape:', scalar.get_shape(), 'and value:\n', scalar.numpy())
33 print('vector has shape:', vector.get_shape(), 'and value:\n', vector.numpy())
34 print('matrix has shape:', matrix.get_shape(), 'and value:\n', matrix.numpy())
35 
36 # ### 廣播
37 primes2 = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)
38 ones2 = tf.ones(1, dtype=tf.int32)  # 使用的是標量值(不是全包含1矢量)和廣播
39 just_beyond_primes2 = tf.add(primes2, ones2)
40 twos2 = tf.constant(2, dtype=tf.int32)  # 使用的是標量值(不是全包含 2 的矢量)和廣播
41 primes_doubled2 = primes2 * twos2
42 print("primes2: ", primes2)
43 print("ones2: ", ones2)
44 print("just_beyond_primes2: ", just_beyond_primes2)
45 print("primes_doubled2: ", primes_doubled2)
46 
47 # ### 矢量加法
48 # 可以對張量執行很多典型數學運算:https://www.tensorflow.org/api_docs/python/tf/math;
49 # 輸出張量將返回其值、形狀以及存儲在張量中的值的類型;
50 # 調用張量的numpy方法會返回該張量的值(以NumPy數組形式);
51 #
52 # ### 張量形狀(shape)
53 # 形狀(shape)用於描述張量維度的大小和數量;
54 # 張量的形狀表示為list,其中第i個元素表示維度i的大小;
55 # 列表的長度表示張量的階(即維數);
56 #
57 # ### 廣播
58 # TensorFlow支持廣播(一種借鑒自NumPy的概念);
59 # 利用廣播,元素級運算中的較小數組會增大到與較大數組具有相同的形狀;

運行結果:

# TF imported with eager execution!
primes:  tf.Tensor([ 2  3  5  7 11 13], shape=(6,), dtype=int32)
ones:  tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int32)
just_beyond_primes:  tf.Tensor([ 3  4  6  8 12 14], shape=(6,), dtype=int32)
primes_doubled:  tf.Tensor([ 4  6 10 14 22 26], shape=(6,), dtype=int32)
some_matrix:  tf.Tensor(
[[1 2 3]
 [4 5 6]], shape=(2, 3), dtype=int32)
value of some_matrix is:
 [[1 2 3]
 [4 5 6]]
scalar has shape: () and value:
 0.0
vector has shape: (3,) and value:
 [0. 0. 0.]
matrix has shape: (2, 3) and value:
 [[0. 0. 0.]
 [0. 0. 0.]]
primes2:  tf.Tensor([ 2  3  5  7 11 13], shape=(6,), dtype=int32)
ones2:  tf.Tensor([1], shape=(1,), dtype=int32)
just_beyond_primes2:  tf.Tensor([ 3  4  6  8 12 14], shape=(6,), dtype=int32)
primes_doubled2:  tf.Tensor([ 4  6 10 14 22 26], shape=(6,), dtype=int32)

 

矩陣相乘、張量變形

 1 # coding=utf-8
 2 import tensorflow as tf
 3 import os
 4 
 5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 6 
 7 try:
 8     tf.contrib.eager.enable_eager_execution()
 9     print("# TF imported with eager execution!")
10 except ValueError:
11     print("# TF already imported with eager execution!")
12 
13 # ### 矩陣相乘
14 x = tf.constant([[5, 2, 4, 3], [5, 1, 6, -2], [-1, 3, -1, -2]], dtype=tf.int32)  # 3行4列矩陣
15 y = tf.constant([[2, 2], [3, 5], [4, 5], [1, 6]], dtype=tf.int32)  # 4行2列矩陣
16 matrix_multiply_result = tf.matmul(x, y)  # 矩陣相乘的結果是3行2列矩陣
17 print("matrix_multiply_result: ", matrix_multiply_result)
18 
19 # ### 張量變形
20 matrix = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.int32)  # 4行2列的矩陣
21 reshaped_2x4_matrix = tf.reshape(matrix, [2, 4])  # 將4x2張量變形為2x4張量
22 reshaped_1x8_matrix = tf.reshape(matrix, [1, 8])
23 reshaped_2x2x2_tensor = tf.reshape(matrix, [2, 2, 2])  # 將4x2張量變形為三維2x2x2張量
24 one_dimensional_vector = tf.reshape(matrix, [8])  # 將4x2張量變形為一維8元素張量
25 print("Original matrix (4x2):\n", matrix.numpy())
26 print("Reshaped matrix (2x4):\n", reshaped_2x4_matrix.numpy())
27 print("Reshaped matrix (1x8):\n", reshaped_1x8_matrix.numpy())
28 print("reshaped_2x2x2_tensor:\n", reshaped_2x2x2_tensor.numpy())
29 print("one_dimensional_vector:\n", one_dimensional_vector.numpy())
30 
31 # ### 矩陣相乘
32 # 在線性代數中,當兩個矩陣相乘時,第一個矩陣的列數必須等於第二個矩陣的行數,否則是無效的;
33 #
34 # ### 張量變形
35 # 可以使用tf.reshape方法改變張量的形狀和維數(“階”);
36 # 例如,可以將4x2張量變形為2x4張量;
37 # 例如,可以將4x2張量變形為三維2x2x2張量或一維8元素張量;

運行結果:

# TF imported with eager execution!
matrix_multiply_result:  tf.Tensor(
[[35 58]
 [35 33]
 [ 1 -4]], shape=(3, 2), dtype=int32)
Original matrix (4x2):
 [[1 2]
 [3 4]
 [5 6]
 [7 8]]
Reshaped matrix (2x4):
 [[1 2 3 4]
 [5 6 7 8]]
Reshaped matrix (1x8):
 [[1 2 3 4 5 6 7 8]]
reshaped_2x2x2_tensor:
 [[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
one_dimensional_vector:
 [1 2 3 4 5 6 7 8]

 

變量、初始化和賦值

 1 # coding=utf-8
 2 import tensorflow as tf
 3 import os
 4 
 5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 6 
 7 try:
 8     tf.contrib.eager.enable_eager_execution()
 9     print("# TF imported with eager execution!")
10 except ValueError:
11     print("# TF already imported with eager execution!")
12 
13 v1 = tf.contrib.eager.Variable([3])  # 創建一個初始值為3的標量變量
14 v2 = tf.contrib.eager.Variable(
15     tf.random_normal(shape=[1, 4],  # 形狀為1行4列,必選項
16                      mean=1.0,  # 正態分布的均值,默認為0
17                      stddev=0.35,  # 正態分布的標准差,默認為1.0
18                      dtype=tf.float64,  # 輸出的類型,默認為tf.float32
19                      seed=1,  # 每次產生的隨機數結果是否相同,如果固定seed值為一個整數則相同,默認為None(不相同)
20                      name="test")  # 操作的名稱
21 )  # 創建一個初始值為正態分布的1*4矢量變量
22 tf.assign(v1, [7])  # 使用assign更改變量的值
23 
24 print("v1:", v1.numpy())
25 print("v2:", v2.numpy())
26 
27 # ### 變量、初始化和賦值
28 # 在TensorFlow中可以定義Variable對象(變量),其值可以更改;
29 # 創建變量時,可以明確設置一個初始值,也可以使用初始化程序(例如分布);
30 # 使用assign更改變量的值,向變量賦予新值時,其形狀必須和之前的形狀一致;
31 #
32 # ### tf.random_normal()函數
33 # 用於從服從指定正太分布的數值中取出指定個數的值;

運行結果:

# TF imported with eager execution!
v1: [7]
v2: [[1.08498964 0.87645062 0.70722227 0.91475084]]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM