接觸numpy不久,一直不太理解裡面的張量還有axis軸究竟是個什麼東西。貌似隨便給我乙個高維的張量都不能描述它的shape是什麼樣的。後來自己仔細研究了一下,有所收穫。
首先,張量不同於向量或者矩陣。一維的張量是沒有行與列之分的。
import numpy as np
a = [1, 2]
b = [[1],[2]]
a = np.array(a)
b = np.array(b)
print(a, a.shape) # >>>[1 2] (2,)
print(b, b.shape) # >>>[[1]
# [2]] (2, 1)
所以這樣輸出的b並不是乙個列向量,而是乙個「矩陣」。
shape輸出的元組裡,每個數字表示的都是什麼意思?下面的**可以說明
import numpy as np
c = [[[1], [2]],
[[3], [4]],
[[4], [2]]]
c = np.array(c)
axis0 = np.sum(c, axis = 0)
axis1 = np.sum(c, axis = 1)
axis2 = np.sum(c, axis = 2)
print(c, c.shape) # >>> [[[1]
# [2]]
# [[3]
# [4]]
# [[4]
# [2]]] (3, 2, 1)
print("-" * 20)
print(axis0, axis0.shape) #>>> (2, 1)
print("-" * 20)
print(axis1, axis1.shape) #>>> (3, 1)
print("-" * 20)
print(axis2, axis2.shape) #>>> (3, 2)
定義了乙個3維的張量c,怎麼判斷c的形狀?這裡最好不要從矩陣的角度來理解,我覺得從list的角度理解反而更好。c.shape的輸出結果為(3, 2, 1),其中每個數字代表的就是中括號裡元素的個數,3就是最外成的中括號裡有3個元素。2和1同理。這樣的話,任意給定乙個高維的張量,也能判斷它的形狀了。
再就是axis的理解。從輸出結果看,axis從小到大指定的就是shape輸出裡從左至右的維度。就sum這個方法而言,就是去掉指定維度的那個中括號就可以了。
張量的維度
張量的階數有時候也稱為維度,或者軸,軸這個詞翻譯自英文axis。理解 沿著某個軸,提取某個軸的所有資料進行計算 乙個tensor的shape,從左到右依次為axis 0,axis 1,axis 2.axis 0時,np.sum a,axis 0 將0階的資料全部加起來,即每列所有行加起來 axis ...
PyTorch中張量 tensor 的維度變換
example in 1 x torch.rand 4,1,28,28 in 2 x.size out 2 torch.size 4,1,28,28 in 3 y x.view 4,28 28 in 4 y.size out 4 torch.size 4,784 in 5 y x.reshape 4...
對numpy中軸與維度的理解
numpy s main object is the homogeneous multidimensional arr程式設計客棧ay.it is a table of elements usually numbers all of the same type,indexed by a tuple ...