Python 之道

Python 学习笔记之 Numpy 库——数组基础

2018-10-01  本文已影响2人  seniusen

1. 初识数组

import numpy as np
a = np.arange(15)
a = a.reshape(3, 5)
print(a.ndim, a.shape, a.dtype)
# 2 (3, 5) int64
print(a.size, a.itemsize) # 15 8

2. 创建数组

a = np.array([[1, 2, 3], [4, 5, 6]])
a = np.ones((3, 4))
a = np.zeros((3, 4), dtype=np.int32)
a = np.linspace(0, 2, 9)   
# 9 numbers from 0 to 2

3. 基本运算

a = np.array([[1, 2, 3], [4, 5, 6]]) 
                       # (2, 3)
b = np.array([[1, 0, 1], [0, 1, 1],
 [1, 1, 0]])           # (3, 3)

c = np.dot(a, b)       # 矩阵相乘
d = a @ b              # 矩阵相乘
e = np.dot(a[0], a[0]) # 向量内积
f = a * a              # 元素相乘

g = np.sum(a)
h = np.mean(a, axis=0)

4. 维度操作

a = np.zeros((2, 3))
b = np.zeros((3, 3))
np.vstack((a, b)).shape  # (5, 3)
a = np.zeros((2, 1, 5))
b = np.zeros((2, 2, 5))
np.hstack((a, b)).shape  # (2, 3, 5)
a = np.zeros((2, 5, 1))
b = np.zeros((2, 5, 5))
np.concatenate((a, b), axis=2).shape  
# (2, 5, 6)
a = np.zeros((3, ))
b = np.zeros((3, ))
np.stack((a, b), axis=0).shape #(2, 3)
np.stack((a, b), axis=1).shape #(3, 2)

5. 随机数

a = np.random.rand(3, 2)  # (3, 2)
a = np.random.random((2, 3)) # (2, 3)
a = np.random.randn(3, 2)  # (3, 2)
a = sigma * np.random.randn(...) + mu 
a = np.random.randint(1, 5, (3, 2))  
# (3, 2)
a = np.arange(5, 10)
np.random.choice(a, 3, replace=False)
np.random.choice(5, (3,2))
np.random.seed(1)
a = np.random.rand(3, 2)
np.random.seed(1)
b = np.random.rand(3, 2) # a == b

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

获取更多精彩,请关注「seniusen」!


seniusen
上一篇 下一篇

猜你喜欢

热点阅读