Python机器学习——numpy
文章目录
- Python机器学习——numpy
- 前言
- 一、numpy是什么?
- 二、使用步骤
-
- 1.引入库
- 2.NumPy Ndarray 对象
- 2.NumPy 矩阵对象
-
- 2.1 矩阵转置(T)
- 2.2 矩阵求逆(I)
- 2.3 矩阵乘法(dot)
- 2.4 访问矩阵
-
- 2.4.1 访问第i行第j列的值(i,j从0开始)
- 2.4.2 遍历第i行
- 2.4.3 遍历第j列
- 总结
前言
在机器学习中,我们要面临大量的数学公式,掌握好的工具可以使我们更好的将理论用于实战。接下来我们粗略的了解什么是Numpy。
一、numpy是什么?
NumPy(Numerical Python)是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)),支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。菜鸟教程链接: link.
二、使用步骤
1.引入库
代码如下:
import numpy as np
2.NumPy Ndarray 对象
创建一个 ndarray 只需调用 NumPy 的 array 函数即可:
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
| 名称 | 描述 |
|---|---|
| object | 数组或嵌套的数列 |
| dtype | 数组元素的数据类型,可选 |
| copy | 对象是否需要复制,可选 |
| order | 创建数组的样式,C为行方向,F为列方向,A为任意方向(默认) |
| subok | 默认返回一个与基类类型一致的数组 |
| ndmin | 指定生成数组的最小维度 |
例如:
import numpy as np
a = np.array([1,2,3]) #一维array
b = np.array([[1,2],[3,4]]) #二维array
2.NumPy 矩阵对象
创建一个 ndarray 只需调用 NumPy 的 mat 函数即可,例如:
import numpy as np
a = np.mat([[1,2],[3,4]])
b = np.mat([[1,2,3,4]])
c = np.mat([[1],[2],[3],[4]])
对应于:
a = [ 1 2 3 4 ] , b = [ 1 2 3 4 ] , c = [ 1 2 3 4 ] a = \begin{bmatrix} 1&2 \\ 3&4 \end{bmatrix} ,b=\begin{bmatrix} 1&2 &3 &4 \end{bmatrix} ,c = \begin{bmatrix} 1\\2 \\3 \\4 \end{bmatrix} a=[1324],b=[1234],c=⎣⎢⎢⎡1234⎦⎥⎥⎤
numpy已经为我们实现了对矩阵的各种操作,常见的有:
2.1 矩阵转置(T)
import numpy as np
a = np.mat([[1,2],[3,4]])
a_t = a.T
a _ t = [ 1 3 2 4 ] a\_t = \begin{bmatrix} 1&3 \\ 2&4 \end{bmatrix} a_t=[1234]
2.2 矩阵求逆(I)
import numpy as np
a = np.mat([[1,2],[3,4]])
a_i = a.I
a _ i = [ − 2 1 1.5 − 0.5 ] a\_i = \begin{bmatrix} -2&1 \\ 1.5&-0.5 \end{bmatrix} a_i=[−21.51−0.5]
2.3 矩阵乘法(dot)
import numpy as np
a = np.mat([[1,2],[3,4]])
b = np.mat([[2,3],[4,5]])
c = a.dot(b)
c = [ 10 13 22 29 ] c = \begin{bmatrix} 10&13 \\ 22&29 \end{bmatrix} c=[10221329]
2.4 访问矩阵
2.4.1 访问第i行第j列的值(i,j从0开始)
import numpy as np
a = np.mat([[1,2],[3,4]])
print(a[0,1])
print(type(a[0,1]))
输出:
2
<class 'numpy.int32'>
2.4.2 遍历第i行
import numpy as np
a = np.mat([[1,2],[3,4]])
print(a[0,:])
print(type(a[0,:]))
输出:
[[1 2]]
<class 'numpy.matrix'>
2.4.3 遍历第j列
import numpy as np
a = np.mat([[1,2],[3,4]])
print(a[:,0])
print(type(a[:,0]))
输出:
[[1][3]]
<class 'numpy.matrix'>
总结
Numpy是python中一个强大的数值计算库,熟悉Numpy的操作可以大大简化我们的代码,使其更加整洁高效。Numpy的常见用法可以参考菜鸟教程。菜鸟教程链接: [link](https://www.runoob.com/numpy/numpy-tutorial.html).