numpy简易入门包括矩阵、线性代数模块、随机模块

本篇文章是个人学习后自己体验感悟。

参考链接 我的大学老师刘二大人
刘二大人永远的神


提示:以下是本篇文章正文内容,下面案例可供参考

文章目录

  • 前言
  • 一、NUMPY
    • 1.1基本概念:张量
    • 1.2一维数组
    • 1.3 二维数组
    • 1.4利用Numpy产生数组
    • 1.5 Numpy数组的切片、转置与翻转
    • 1.6Numpy的基础数学运算
    • 1.7 广播
    • 2.线性代数模块(linalg)
    • 3.随机模块
  • 总结


前言


提示:以下是本篇文章正文内容,下面案例可供参考

一、NUMPY

示例:在Numpy中可以非常方便的创建各种不同类型的张量(Tensor),并且执行一些基本操作。


1.1基本概念:张量

提供一个讲解张量的链接:点我!

张量是一种表示物理量的方式,这个方式就是用基向量与分量组合表示物理量(Combination of basis vector and component)

标量是0阶张量(有大小和0个方向),向量是1阶张量(有大小和1个方向)。应力是二阶张量,是有大小和两个方向的量。张量可以粗浅的理解为 是有大小与多个方向的量。


1.2一维数组

# 按照惯例,numpy使用别名np
import numpy as np
# 用列表生成numpy的数组
a = [1, 2, 3, 4]
b = np.array(a)
type(b)

numpy.ndarray

# 输出数组的形状
b.shape

(4,)

# 返回最大的索引值
b.argmax()

3

# 最大值
b.max()

4

# 均值
b.mean()

2.5


1.3 二维数组

[ 1 2 3 4 ] \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} [1324]

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

array([[1, 2],[3, 4]])

d.shape

(2,2)

d.size

4

关于axis参数 点我
简单可以理解为 axis等于0 在哪个纬度塌缩成一维向量 以上边为例 所取的是每列中最大数
axis等于0 即每一列的元素索取最大的组成新向量 (axis 取值最大为纬度数N)

d.max(axis =0) 
# //每一列的最大值

array([3, 4])

d.max(axis=1)  
# //  每一行最大值

array([2, 4])

d.mean(axis=0)
# // 平均值

array([2., 3.]) (注意这里边的是浮点数)

# 将数组展开为一个1维数组
d.flatten()
# c.flatten()

# 返回一个1维的数组
# np.ravel(c)
np.ravel(d)      

以上两段代码一个结果

array([1, 2, 3, 4])


1.4利用Numpy产生数组

Numpy中包含很多用来生成数组的函数。

e = np.ones((3, 3), dtype=np.float)
e

array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

f = np.repeat(3, 4)
f

array([3, 3, 3, 3])

# 创建一个2*2*3的张量
g = np.zeros((2, 2, 3), dtype=np.uint8)
g.shape

(2, 2, 3)

h = g.astype(np.float)
h

array([[[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.]]])

# 类似于range函数
l = np.arange(10)
l

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# 在0到6之间取5个数
m = np.linspace(0, 6, 5)
m

array([0. , 1.5, 3. , 4.5, 6. ])

# save and load
p = np.array(
    [[1, 2, 3, 4],
     [5, 6, 7, 8]]
)

np.save('p.npy', p)
q = np.load('p.npy')
q

array([[1, 2, 3, 4],
[5, 6, 7, 8]])


1.5 Numpy数组的切片、转置与翻转

a = np.arange(24).reshape((2, 3, 4))
a

array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])

# :表示当前维度上所有的下标
a[:, 2, :]

array([[ 8, 9, 10, 11],
[20, 21, 22, 23]])

a[:, 1:, 1:-1]

array([[[ 5, 6],
[ 9, 10]],
[[17, 18],
[21, 22]]])

np.split(np.arange(9), 3)

[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

np.split(np.arange(9),[2, -3])  
# // 以2   -3 为坐标分割

[array([0, 1]), array([2, 3, 4, 5]), array([6, 7, 8])]

l0 = np.arange(6).reshape((2, 3))
l1 = np.arange(6,12).reshape((2,3))
# 沿着垂直方向拼接两个数组
np.vstack((l0, l1))

array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])

l0 = np.arange(6).reshape((2, 3))
l1 = np.arange(6,12).reshape((2,3))
# 沿着水平方向拼接两个数组
np.hstack((l0, l1))

array([[ 0, 1, 2, 6, 7, 8],
[ 3, 4, 5, 9, 10, 11]])

np.concatenate((l0, l1))

array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])

np.concatenate((l0, l1), axis=-1)

array([[ 0, 1, 2, 6, 7, 8],
[ 3, 4, 5, 9, 10, 11]])

# stack直接添加一个维度
s = np.stack((l0, l1))
s

array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])

#  //转置
u = a[0].transpose() 
# a[0]
u

array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])

矩阵反转

# 沿水平轴上下翻转
w = np.flipud(u)
# 沿垂直轴左右翻转
x = np.fliplr(u)
# 按照一维顺序滚动位移
np.roll(u, 1)
# 按照指定轴滚动位移
np.roll(u, 1, axis=1)
#所有元素向右移动1个
np.roll(u, 1)


1.6Numpy的基础数学运算

Numpy的基础数学运算是支持Array的

#绝对值
np.abs(-1)

#三角函数
np.sin(np.pi/2)

a = np.array([0.462884, 0.978545])
np.arctanh(a)

#e^a
np.exp(a)

#幂次方
np.power(a, 3)

#点乘
np.dot([1, 2], [3, 4])

#开方
np.sqrt(a)

#求和与均值
np.sum([1, 2, 3, 4])
np.mean([5, 6, 7, 8])

# 标准差
np.std([1, 2, 3])

1.7 广播

如果两个数组(Array)维度不一致,则在没有对齐的维度上进行扩展。

a = np.arange(1,7).reshape((2, 3))
b = np.array([1, 2, 3, 1, 2 ,3]).reshape((2, 3))

两数组 a + b 加减乘除乘方都是相应元素的计算 最后返回2x3的数组

c = np.arange(1, 13).reshape((4, 3))
c

array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])

d = np.array([2, 2, 2]).reshape((1, 3))
d
#特别注意 d要reshape过 而不是直接np.array()

array([[2, 2, 2]])

c + d

array([[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])

c * d

array([[ 2, 4, 6],
[ 8, 10, 12],
[14, 16, 18],
[20, 22, 24]])

c - 1

array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])


2.线性代数模块(linalg)

Numpy提供了常用的线性代数运算模块。

基本线性函数:

- norm         Vector or matrix norm
- inv          Inverse of a square matrix
- solve         Solve a linear system of equations
- det             Determinant of a square matrix
- lstsq           Solve linear least-squares problem
- pinv            Pseudo-inverse (Moore-Penrose) calculated using a singular value decomposition
- matrix_power    Integer power of a square matrix

Eigenvalues and decompositions:

- eig             Eigenvalues and vectors of a square matrix
- eigh            Eigenvalues and eigenvectors of a Hermitian matrix
- eigvals         Eigenvalues of a square matrix
- eigvalsh        Eigenvalues of a Hermitian matrix
- qr              QR decomposition of a matrix
- svd             Singular value decomposition of a matrix
- cholesky        Cholesky decomposition of a matrix

Tensor operations:

- tensorsolve     Solve a linear tensor equation
- tensorinv       Calculate an inverse of a tensor

Exceptions:

- LinAlgError     Indicates a failed linear algebra operation

在做向量与矩阵的dot乘运算的时候,应将向量reshape成张量进行计算。

#模长
a = np.array([3, 4])
np.linalg.norm(a)

5.0

b = np.arange(1, 10).reshape((3, 3))
b

array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

c = np.array([2, 0, 1]).reshape((3, 1))
c

array([[2],
[0],
[1]])

提示:dot在对不齐时运算不同与点乘

# 2 x 1 + 0 x 2 + 1 x 3   三维
np.dot(b, c)

array([[ 5],
[14],
[23]])

np.trace(b)
# 主对角线上 各个元素的和

15

np.linalg.det(b)
# 行列式

6.6613381477509402e-16

np.linalg.matrix_rank(b)
# 秩

2

d = np.array([2, 1, 1, 2]).reshape((2, 2))
# Cholesky分解  A = LL.T
l = np.linalg.cholesky(d)
l

array([[ 1.41421356, 0. ],
[ 0.70710678, 1.22474487]])

np.dot(l, l.T)

array([[ 2., 1.],
[ 1., 2.]])

# SVD 分解
e = np.array([1, 2, 3, 4, 5, 6]).reshape((2, 3))
e

array([[1, 2, 3],
[4, 5, 6]])

奇异值分解 点我
提及: U 点乘 S 点乘 V = 原矩阵

U, s, V = np.linalg.svd(e)
#这里s是一纬的需要补齐
S = np.hstack((np.diag(s), np.zeros((2, 1))))
S

array([[ 9.508032 , 0. , 0. ],
[ 0. , 0.77286964, 0. ]])

np.dot(U, np.dot(S, V))

array([[ 1., 2., 3.],
[ 4., 5., 6.]])


3.随机模块

随机模块包含了随机数产生和统计分布相关的基本函数,Python本身也有随机模块random,不过功能更丰富。

========================
Random Number Generation
========================

==================== =========================================================
Utility functions
==============================================================================
random_sample        Uniformly distributed floats over ``[0, 1)``.
random               Alias for `random_sample`.
bytes                Uniformly distributed random bytes.
random_integers      Uniformly distributed integers in a given range.
permutation          Randomly permute a sequence / generate a random sequence.
shuffle              Randomly permute a sequence in place.
seed                 Seed the random number generator.
choice               Random sample from 1-D array.

==================== =========================================================

==================== =========================================================
Compatibility functions
==============================================================================
rand                 Uniformly distributed values.
randn                Normally distributed values.
ranf                 Uniformly distributed floating point numbers.
randint              Uniformly distributed integers in a given range.
==================== =========================================================

==================== =========================================================
Univariate distributions
==============================================================================
beta                 Beta distribution over ``[0, 1]``.
binomial             Binomial distribution.
chisquare            :math:`\chi^2` distribution.
exponential          Exponential distribution.
f                    F (Fisher-Snedecor) distribution.
gamma                Gamma distribution.
geometric            Geometric distribution.
gumbel               Gumbel distribution.
hypergeometric       Hypergeometric distribution.
laplace              Laplace distribution.
logistic             Logistic distribution.
lognormal            Log-normal distribution.
logseries            Logarithmic series distribution.
negative_binomial    Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f         Non-central F distribution.
normal               Normal / Gaussian distribution.
pareto               Pareto distribution.
poisson              Poisson distribution.
power                Power distribution.
rayleigh             Rayleigh distribution.
triangular           Triangular distribution.
uniform              Uniform distribution.
vonmises             Von Mises circular distribution.
wald                 Wald (inverse Gaussian) distribution.
weibull              Weibull distribution.
zipf                 Zipf's distribution over ranked data.
==================== =========================================================

==================== =========================================================
Multivariate distributions
==============================================================================
dirichlet            Multivariate generalization of Beta distribution.
multinomial          Multivariate generalization of the binomial distribution.
multivariate_normal  Multivariate generalization of the normal distribution.
==================== =========================================================

==================== =========================================================
Standard distributions
==============================================================================
standard_cauchy      Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma       Standard Gamma distribution.
standard_normal      Standard normal distribution.
standard_t           Standard Student's t-distribution.
==================== =========================================================

==================== =========================================================
Internal functions
==============================================================================
get_state            Get tuple representing internal state of generator.
set_state            Set state of generator.
==================== =========================================================
import numpy.random as random
random.seed(42)
random.rand(1, 3)
# 当函数括号内有两个及以上参数时,则返回对应维度的数组,能表示向量或矩阵;

array([[ 0.37454012, 0.95071431, 0.73199394]])

# 产生一个[0, 1)之间随机数
random.random()

# 以下四个函数是一样的
random.random((3, 3))
random.sample((3, 3))
random.random_sample((3, 3))
random.ranf((3, 3))

# 产生10个[1, 6)之间的浮点随机数
5 * random.random(10) + 1

# 也可以
random.uniform(1, 6, 10)

# 产生10个[1,6)之间的整型随机数
random.randint(1, 6, 10)

# 产生2x5的标准正态分布样本
mu, sigma = 2, 0.5
random.normal(mu, sigma, size=(5, 2))

# 产生20个,n=10,p=0.5的二项分布样本,扔10次硬币正面朝上的次数
random.binomial(n=10, p=0.5, size=20)

a = np.arange(10)
# 有放回的随机采样
random.choice(a, 7)

# 无放回的随机采样
random.choice(a, 7, replace=False)
# 随机乱序
indexes = random.permutation(a)
indexes

array([0, 2, 1, 9, 7, 6, 3, 5, 4, 8])

b = np.arange(10) * 2 + 2
b

array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

b[indexes]

array([ 2, 6, 4, 20, 16, 14, 8, 12, 10, 18])

# 打乱数组
random.shuffle(a)
a

array([1, 2, 7, 4, 8, 5, 0, 3, 6, 9])

# 生成一个长度为9的随机bytes序列并作为str返回
random.bytes(9)

b’\xbd\xefVmx\x1a"\x00s’


总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了numpy的使用。留下学习足迹!

你可能感兴趣的:(numpy,matlab,python,深度学习,机器学习)