NumPy 是 Python 语言的一个扩充程序库。支持大量高维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。机器学习涉及到大量对数组的变换和运算,NumPy 就成了必不可少的工具之一
知识点
- 创建数组
- 数组运算
- 数学函数
- 数组切片和索引
- 数组形状操作
- 数组排序
- 数组统计
实验环境
Python 3.6
NumPy: 1.14.2
基础部分
导入numpy库
- 导入 NumPy
练习 NumPy 之前,首先需要导入 NumPy 模块,并约定简称为 np
import numpy as np
- 打印numpy的版本信息和配置信息
np.__version__
'1.15.4'
np.show_config()
blas_mkl_info:
NOT AVAILABLE
blis_info:
NOT AVAILABLE
openblas_info:
library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
libraries = ['openblas']
language = f77
define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
libraries = ['openblas']
language = f77
define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
NOT AVAILABLE
openblas_lapack_info:
library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
libraries = ['openblas']
language = f77
define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
libraries = ['openblas']
language = f77
define_macros = [('HAVE_CBLAS', None)]
3.怎么用命令行获取numpy add函数的文档说明
np.info(np.add)
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added. If ``x1.shape != x2.shape``, they must be
broadcastable to a common shape (which may be the shape of one or
the other).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
创建数组
NumPy 的主要对象是多维数组 Ndarray。在 NumPy 中维度(dimensions)叫做轴(axes),轴的个数叫做秩(rank)。
例如,下方数组是一个秩为 1 的数组,因为它只有一个轴,而轴的长度为 3。
[1, 2, 3]
又例如,下方数组的秩为 2。第一个维度长度为 2,第二个维度长度为 3。
[[1., 2., 3.], [4., 5., 6.]]
- 通过列表创建一维数组
注意:numpy.array 和 Python 标准库 array.array 并不相同,前者更为强大,这也就是我们学习 NumPy 的重要原因之一。
np.array([1, 2, 3])
array([1, 2, 3])
- 通过列表创建二维数组
np.array([(1, 2, 3), (4, 5, 6)])
array([[1, 2, 3],
[4, 5, 6]])
- 创建全为1的二维数组&创建全为0的三维数组
np.ones((3,3,))
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
np.zeros((2,3,4))
array([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])
- 创建一维等差数组
np.arange(5)
array([0, 1, 2, 3, 4])
- 创建二维等差数组
np.arange(6).reshape(2,3)
array([[0, 1, 2],
[3, 4, 5]])
- 创建单位矩阵(二维数组)
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
- 创建等间隔一维数组
np.linspace(1,10,num =6)
array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. ])
- 创建二维随机数组
np.random.rand(2,3)
array([[0.73086456, 0.95886953, 0.21075672],
[0.98499111, 0.49895294, 0.57656235]])
- 创建二维随机整数数组(数值小于 5)
np.random.randint(5,size = (2,3))
array([[3, 1, 1],
[1, 4, 2]])
- 依据自定义函数创建数组
np.fromfunction(lambda i,j:i+j,(3,3))
array([[0., 1., 2.],
[1., 2., 3.],
[2., 3., 4.]])
数组运算
生成一维示例数组
a = np.array([10,20,30,40,50])
b = np.arange(1,6)
print(a,b)
[10 20 30 40 50] [1 2 3 4 5]
- 一维数组加法运算
a+b
array([11, 22, 33, 44, 55])
- 一维数组减法运算
a-b
array([ 9, 18, 27, 36, 45])
- 一维数组乘法运算
a * b
array([ 10, 40, 90, 160, 250])
- 一维数组除法运算
a / b
array([10., 10., 10., 10., 10.])
生成二维示例数组(可以看作矩阵)
A = np.array([[1,2],
[3,4]])
B = np.array([[5,6],
[7,8]])
print(A)
print(B)
[[1 2]
[3 4]]
[[5 6]
[7 8]]
- 矩阵加法运算
A + B
array([[ 6, 8],
[10, 12]])
- 矩阵减法运算
A - B
array([[-4, -4],
[-4, -4]])
- 矩阵元素间乘法运算
A * B
array([[ 5, 12],
[21, 32]])
- 矩阵乘法运算(注意与上题的区别)
np.dot(A,B)
array([[19, 22],
[43, 50]])
# 如果使用 np.mat 将二维数组准确定义为矩阵,就可以直接使用 * 完成矩阵乘法计算
np.mat(A) * np.mat(B)
matrix([[19, 22],
[43, 50]])
- 数乘矩阵
2 * A
array([[2, 4],
[6, 8]])
- 矩阵的转置
A.T
array([[1, 3],
[2, 4]])
- 矩阵求逆
np.linalg.inv(A)
array([[-2. , 1. ],
[ 1.5, -0.5]])
数学函数
- 三角函数
print(a)
np.sin(a)
[10 20 30 40 50]
array([-0.54402111, 0.91294525, -0.98803162, 0.74511316, -0.26237485])
- 以自然对数函数为底数的指数函数
np.exp(a)
array([2.20264658e+04, 4.85165195e+08, 1.06864746e+13, 2.35385267e+17,
5.18470553e+21])
- 数组的方根的运算(开平方)
np.sqrt(a)
array([3.16227766, 4.47213595, 5.47722558, 6.32455532, 7.07106781])
- 数组的方根的运算(立方)
np.power(a,3)
array([ 1000, 8000, 27000, 64000, 125000], dtype=int32)
数组切片和索引
- 一维数组索引
a = np.array([1,2,3,4,5])
a[0],a[-1]
(1, 5)
- 一维数组切片
a[0:2],a[:-1]
(array([1, 2]), array([1, 2, 3, 4]))
- 二维数组索引
a = np.array([(1,2,3),(4,5,6),(7,8,9)])
a[0],a[-1]
(array([1, 2, 3]), array([7, 8, 9]))
- 二维数组切片(取第 2 列)
print(a)
[[1 2 3]
[4 5 6]
[7 8 9]]
a[:,1]
array([2, 5, 8])
- 二维数组切片(取第 2,3 行)
a[1:3,:]
array([[4, 5, 6],
[7, 8, 9]])
数组形状操作
生成二维示例数组
a= np.random.random((3,2))
a
array([[0.68619384, 0.61343199],
[0.1416633 , 0.92122214],
[0.3294876 , 0.8636649 ]])
- 查看数组形状
a.shape
(3, 2)
- 更改数组形状(不改变原始数组)
# reshape 并不改变原始数组
a.reshape(2,3)
a
array([[0.68619384, 0.61343199, 0.1416633 ],
[0.92122214, 0.3294876 , 0.8636649 ]])
- 更改数组形状(改变原始数组)
# resize 会改变原始数组
a.resize(2,3)
a
array([[0.68619384, 0.61343199, 0.1416633 ],
[0.92122214, 0.3294876 , 0.8636649 ]])
- 展平数组
# 生成示例数组
a = np.random.randint(10,size= (3,3))
b = np.random.randint(10,size = (3,3))
a,b
(array([[4, 7, 5],
[0, 4, 2],
[2, 9, 4]]), array([[3, 8, 0],
[8, 0, 1],
[6, 6, 9]]))
np.vstack((a,b))
array([[4, 7, 5],
[0, 4, 2],
[2, 9, 4],
[3, 8, 0],
[8, 0, 1],
[6, 6, 9]])
- 水平拼合数组
np.hstack((a, b))
array([[4, 7, 5, 3, 8, 0],
[0, 4, 2, 8, 0, 1],
[2, 9, 4, 6, 6, 9]])
- 沿横轴分割数组
a
array([[4, 7, 5],
[0, 4, 2],
[2, 9, 4]])
np.vsplit(a,3)
[array([[4, 7, 5]]), array([[0, 4, 2]]), array([[2, 9, 4]])]
数组排序
# 生成示例数组
a = np.array(([1, 4, 3], [6, 2, 9], [4, 7, 2]))
a
array([[1, 4, 3],
[6, 2, 9],
[4, 7, 2]])
- 返回每列最大值
np.max(a,axis = 0)
array([6, 7, 9])
- 返回每行最小值
np.min(a,axis = 1)
array([1, 2, 2])
- 返回每列最大值索引
np.argmax(a,axis =0)
array([1, 2, 1], dtype=int64)
- 返回每行最小值索引
np.argmin(a,axis = 1)
array([0, 1, 2], dtype=int64)
数组统计
- 统计数组各列的中位数
# 继续使用上面的 a 数组
np.median(a, axis=0)
array([4., 4., 3.])
- 统计数组各行的算术平均值
np.mean(a,axis =1)
array([2.66666667, 5.66666667, 4.33333333])
- 统计数组各列的加权平均值
np.average(a,axis = 0 )
array([3.66666667, 4.33333333, 4.66666667])
- 统计数组各行的方差
np.var(a,axis =1)
array([1.55555556, 8.22222222, 4.22222222])
- 统计数组各列的标准偏差
np.std(a,axis =0)
array([2.05480467, 2.05480467, 3.09120617])
本文章主要作为学习历程的记录,如有侵权,请联系作者删除,原文地址https://www.shiyanlou.com/courses/