
程序 = 數(shù)據(jù)結(jié)構(gòu)+算法
TensorFlow程序 = 張量數(shù)據(jù)結(jié)構(gòu) + 計算圖算法語言
TensorFlow中的數(shù)值類型依據(jù)維度數(shù),可以劃分為標(biāo)量(Scalar)、向量(Vector)、矩陣(Matrix)、張量(Tensor)。但是在TensorFlow中為了表達(dá)方便,一般把標(biāo)量、向量、矩陣也統(tǒng)稱為張量,不作區(qū)分。
1.標(biāo)量在 TensorFlow2 上的創(chuàng)建如下:
import tensorflow as tf
a = 1.0 # python語言方式創(chuàng)建標(biāo)量
b = tf.constant(1.0) # TF方式創(chuàng)建標(biāo)量
type(a), type(b)
'''
輸出:
(float, tensorflow.python.framework.ops.EagerTensor)
'''
2.向量在 TensorFlow2 上的創(chuàng)建如下:
import tensorflow as tf
import tensorflow as tf
c = tf.constant([1,2.2,3.3]) # 創(chuàng)建向量
type(c) ,c.shape
'''
輸出:
(tensorflow.python.framework.ops.EagerTensor, TensorShape([3]))
'''
c
'''
輸出:
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([1. , 2.2, 3.3], dtype=float32)>
'''
其中shape 表示張量的形狀, dtype 表示張量的數(shù)值精度,.numpy()方法可以返回 Numpy.array 類型的數(shù)據(jù),代碼如下:
#接上面代碼
c.numpy()
'''
輸出:
array([1. , 2.2, 3.3], dtype=float32)
'''
3.矩陣在 TensorFlow2 上的創(chuàng)建如下:
d = tf.constant([[1,2],[3,4],[5,6]]) # 創(chuàng)建 3 行 2 列的矩陣
d, d.shape
"""
輸出:
(<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4],
[5, 6]])>,
TensorShape([3, 2]))
"""
4.三維張量在 TensorFlow2 上的創(chuàng)建如下:
e = tf.constant([[[1,2],[3,4]],[[5,6],[7,8]]]) # 創(chuàng)建 3 維張量
e
"""
輸出:
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])>
"""