NumPy 基礎

ndarray 數(shù)據(jù)類型

np.ndarray((3, 5), dtype=np.float32) # 參數(shù)dtype指定

ndarray 設置單一值

shape = (2, 3)
a = np.ndarray(shape) # a is filled in random values
a.fill(100) # set all the values in ndarray to 100

ndarray.shape

# shape 的類型是 python 中的 tuple
a = np.array([1,2,3])
a.shape # (3,)
a = np.array([[1,2,3],[4,5,6]])
a.shape # (2, 3)
# 查看 shape 是幾維的,也就是 tuple 的長度,可以用 len()
a.shape, len(a.shape) # (2, 3) 2

ndarray 小數(shù)組填充大數(shù)組

# gradient_list 中保存了 30 個 shape (100, 1) 的 ndarray
# 最后合成一個 shape (100, 30) 的 ndarray
def convertTrainSamples(gradient_list):
    rows = gradient_list[0].shape[0]
    cols = len(gradient_list)
    samples = np.ndarray((rows, cols), dtype=np.float32)
    for i in range(0, cols):
        samples[:,i:i+1] = gradient_list[i]
    return samples

# 給數(shù)組直接用 ":" 寫法引用一塊空間,直接賦值,需要源數(shù)組和目標數(shù)組形狀相同
# 如果不用 ":",數(shù)組會降維,也可以,但注意形狀要相同
samples[:,i:i+1] = gradient_list[i]

ndarray 數(shù)組合并

# 將兩個數(shù)組拼接起來,對數(shù)組的形狀有要求
# 下面例子是將兩個二維數(shù)組橫向拼接,也就是拼接第2維
label_pos = np.ndarray((1, 33), dtype=np.int32)
label_pos.fill(1)
label_neg = np.ndarray((1, 55), dtype=np.int32)
label_neg.fill(-1)
# 注意除了 axis 指定的維度不需要相同,其他維度必須相同才能拼接上
labels = np.concatenate((label_pos, label_neg), axis=1) # 第二維,axis從0開始,axis=1

ndarray 矩陣相乘

# m1, m2 是二維數(shù)組,滿足矩陣相乘條件
# 例如兩個數(shù)組的 shape 為 (1, 6) x (6, 576),結(jié)果 shape 是 (1, 576)
result = np.matmul(m1, m2)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容