Numpy 基礎

NumPy 是 Python語言的一個擴充程式庫。

支援高階大規模的多維陣列與矩陣運算,
此外也針對陣列運算提供大量的數學函式函式庫。

向量 vector

Vector is ordered arrays of numbers.
In notation, vectors are denoted with lower case bold letters such as x.
The elements of a vector are all the same type (dtype).
The number of elements in the array
is often referred to as the dimension
though mathematicians may prefer rank.

Vector Creation

np.zeros(4) [0. 0. 0. 0.] (float64)
np.arange(4)
np.arange(4.)
[0 1 2 3] (int64)
[0. 1. 2. 3.] (float64)
np.random.rand(4) [0.35838855 0.65743684 0.73020667 0.6198217]
np.array([5, 4, 3, 2])
np.array([5., 4, 3, 2])
[5 4 3 2] (int64)
[5. 4. 3. 2.] (float64)

Slicing and Indexing

Indexing

a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(a[2])       # 2
print(a[-1])      # a[-1] := a[len(a) - 1] = 9

向量運算

 使用 for 迴圈進行向量運算

使用 numpy

向量加減 x + y
Negate elements of x. x
純量乘法 (Scalar Multiplication)
| Scalar Vector operations
w * x

內積 (Dot Product)

np.dot(x, y)

Sum of all elements of x.

a = np.sum(x)

Mean of all elements of x.

a = np.mean(x)

Create a vector y which ith element of y
is ith element of x to the power of a.

y = x ** a

矩陣 Matrix

Matrix, are 2-D (two dimensional) arrays.
Matrices are denoted with capitol, bold letter such as X.
m is often the number of rows and n the number of columns.

$$ \textbf{X} = \left[
\begin{array}
x_{00} & x_{01} & … & x_{0(n-1)} \\
x_{10} & x_{11} & … & x_{1(n-1)} \\
… & … & … & … \\
x_{(m-1)0} & x_{(m-1)1} & … & x_{(m-1)(n-1)}
\end{array}
\right]_{ \ m \times n} $$

陣列 Array

Array Creation

np.zeros(d_0, d_1, …)

np.shape(array)

Return a tuple of ints, 
the elements of the tuple
give the lengths of the corresponding array dimensions.

x = np.zeros(4, 3)
"""
x = [ [0. 0. 0.]
      [0. 0. 0.]
      [0. 0. 0.]
      [0. 0. 0.]]
"""

print(np.shape(x)) # (4, 3)

 

Last Updated on 2023/08/16 by A1go

目錄
Bitnami