NumPy 学习笔记

Undefined443 / 2024-09-25 / 原文

NumPy

import numpy as np

创建向量:

np.zeros(4)                 # [0. 0. 0. 0.]
np.random.random_sample(4)  # [0.13874093 0.76087955 0.17028386 0.10573206]

np.arange(4.)               # [0. 1. 2. 3.] 加 . 号代表浮点数
np.random.rand(4)           # [0.30553381 0.00115535 0.71271101 0.65088795]

np.array([5,4,3,2])         # [5 4 3 2]
np.array([5.,4,3,2])        # [5. 4. 3. 2.],np 矩阵的元素类型必须相同

元素相关的运算:

a = np.array([1,2,3,4])

b = -a
b = a**2

b = np.sum(a)
b = np.mean(a)

点积:

a = np.array([1, 2, 3, 4])
b = np.array([-1, 4, 3, 2])
c = np.dot(a, b)

在使用 np.dot() 函数时 NumPy 会自动利用底层硬件中的可用数据并行机制来加速计算

创建矩阵:

a = np.zeros((1, 5))
# [[0. 0. 0. 0. 0.]]

a = np.zeros((2, 1))
# [[0.]
#  [0.]]

np.zeros_like(a)
# [[0.]
#  [0.]]

np.random.random_sample((1, 1))
# [[0.44236513]]

a = np.array([[5],
              [4],
              [3]]);
# [[5]
#  [4]
#  [3]]

矩阵操作:

a = np.arange(6).reshape(-1, 2)  # -1 表示根据另一项的值自动计算。这里相当于 (3, 2)
# [[0 1]
#  [2 3]
#  [4 5]]

a[2,0]  # 4。相当于 a[2][0]
a = np.arange(20).reshape(-1, 10)
# [[ 0  1  2  3  4  5  6  7  8  9]
#  [10 11 12 13 14 15 16 17 18 19]]

a[0, 2:7:1]
# [2 3 4 5 6]

a[:, 2:7:1]
# [[ 2  3  4  5  6]
#  [12 13 14 15 16]]
# 获取矩阵形状
m = x_train.shape[0]  # 等价于 len(x_train)