tensorflow中,定義張量的方式如下
>>> import tensorflow as tf
>>> rank_0_tensor = tf.constant(4)
>>> rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
>>> rank_2_tensor = tf.constant([[1, 2],[3, 4],[5, 6]], dtype=tf.float16)
>>> rank_3_tensor = tf.constant([[[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]],[[10, 11, 12, 13, 14],[15, 16, 17, 18, 19]],[[20, 21, 22, 23, 24],[25, 26, 27, 28, 29]],])
對(duì)于張量,可以有多種可視化方式來(lái)幫助我們理解其結(jié)構(gòu), 以3階張量為例
>>> rank_3_tensor = tf.constant([[[0,1,2,3,4], [5,6,7,8,9]],[[10,11,12,13,14], [15,16,17,18,19]], [[20,21,22,23,24], [25,26,27,28,29]]])
>>> rank_3_tensor
<tf.Tensor: shape=(3, 2, 5), dtype=int32, numpy=
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])>
張量有以下幾個(gè)基本屬性
1. shape, 形狀,統(tǒng)計(jì)各個(gè)維度的元素?cái)?shù)量
2. rank, 秩,維度的總數(shù)
3. axis, 軸,具體的某一個(gè)維度
>>> rank_4_tensor = tf.zeros([3, 2, 4, 5])
>>> rank_4_tensor.shape
TensorShape([3, 2, 4, 5])
# 張量的秩
>>> rank_4_tensor.ndim
4
# axis 0的元素?cái)?shù)量
>>> rank_4_tensor.shape[0]
3
# axis 1的元素?cái)?shù)量
>>> rank_4_tensor.shape[1]
2
# axis 2的元素?cái)?shù)量
>>> rank_4_tensor.shape[2]
4
# axis 3的元素?cái)?shù)量
>>> rank_4_tensor.shape[3]
5
圖示如下
tensorflow通過張量這一數(shù)據(jù)結(jié)構(gòu)來(lái)存儲(chǔ)待處理的數(shù)據(jù),并再次基礎(chǔ)上定義了一系列的張量操作,來(lái)高效的處理深度學(xué)習(xí)運(yùn)算。
聯(lián)系客服