Scipy快速入门

Scipy快速入门

注意事项

图床在国外,配合美区、日区网络使用更佳,如遇图片加载不出来,考虑换个VPN吧。

监修中敬告

本文处于Preview阶段,不对文章内容负任何责任,如有意见探讨欢迎留言。

联系方式------绿泡泡:NeoNexusX

常量

稀疏矩阵 (scipy.sparse)

CSC 压缩稀疏列(csr_matrix()

用于高效的算数,快速列切分。

python 复制代码
    # csr
    csr_arr = np.array([0, 0, 1, 0, 0, 0, 0, 1])
    print(f'csc_matrix(csc_arr) is  : \n{csc_matrix(csr_arr)}\n')

结果如下:

shell 复制代码
csc_matrix(csc_arr) is  : 
  (0, 2)	1
  (0, 7)	1

CSR 压缩稀疏行(csc_matrix())

用于快速行切分,更快的矩阵向量乘积。

python 复制代码
    # csc
    csc_arr = np.array([[0],
                        [1],
                        [0],
                        [0],
                        [0],
                        [0],
                        ])
    print(f'csc_matrix(csc_arr) is  : \n{csc_matrix(csc_arr)}\n')

结果如下:

shell 复制代码
csc_matrix(csc_arr) is  : 
  (1, 0)	1

举一个复杂一点的例子:

python 复制代码
    # 获取对应矩阵
    cm_arr = np.array([[1, 0, 6, 0, 7],
                       [0, 2, 0, 0, 0],
                       [0, 0, 3, 0, 0],
                       [0, 0, 0, 4, 0],
                       [0, 0, 0, 0, 5],
                       ])
    print(f'csr_matrix(cm_arr) is  : \n{csr_matrix(cm_arr)}\n')
    print(f'csc_matrix(cm_arr) is  : \n{csc_matrix(cm_arr)}\n')

输出结果:

shell 复制代码
csr_matrix(cm_arr) is  : 
  (0, 0)	1
  (0, 2)	6
  (0, 4)	7
  (1, 1)	2
  (2, 2)	3
  (3, 3)	4
  (4, 4)	5

csc_matrix(cm_arr) is  : 
  (0, 0)	1
  (1, 1)	2
  (0, 2)	6
  (2, 2)	3
  (3, 3)	4
  (0, 4)	7
  (4, 4)	5

获取非0元素(.data)

代码如下:

python 复制代码
    # 获取非0元素
    print(f'csc_matrix(cm_arr).data is  : \n{csc_matrix(cm_arr).data}\n')
    print(f'csr_matrix(cm_arr).data is  : \n{csr_matrix(cm_arr).data}\n')

输出结果:

shell 复制代码
csc_matrix(cm_arr).data is  : 
[1 2 6 3 4 7 5]

csr_matrix(cm_arr).data is  : 
[1 6 7 2 3 4 5]

获取非0元素个数(.count_nonzero() )

python 复制代码
    # 获取非0元素个数
    print(f'csr_matrix(cm_arr).count_nonzero() is  : \n{csr_matrix(cm_arr).count_nonzero()}\n')
    print(f'csc_matrix(cm_arr).count_nonzero() is  : \n{csc_matrix(cm_arr).count_nonzero()}\n')

输出结果:

shel 复制代码
csr_matrix(cm_arr).count_nonzero() is  : 
7

csc_matrix(cm_arr).count_nonzero() is  : 
7

删除零元素(.eliminate_zeros())

注意这是一个方法,你如果用在已经建立好的矩阵是没有效果的:

举个例子:

python 复制代码
    # 减少对应矩阵的0数目
    c_m = csc_matrix(cm_arr)
    c_m.eliminate_zeros()
    r_m = csr_matrix(cm_arr)
    r_m.eliminate_zeros()
    print(f'csc_matrix(cm_arr).eliminate_zeros() is  : \n{c_m}\n')
    print(f'csr_matrix(cm_arr).eliminate_zeros() is  : \n{r_m}\n')

可以看到这里的输出和上文的内容并没有发生什么变化:

shell 复制代码
csc_matrix(cm_arr).eliminate_zeros() is  : 
  (0, 0)	1
  (1, 1)	2
  (0, 2)	6
  (2, 2)	3
  (3, 3)	4
  (0, 4)	7
  (4, 4)	5

csr_matrix(cm_arr).eliminate_zeros() is  : 
  (0, 0)	1
  (0, 2)	6
  (0, 4)	7
  (1, 1)	2
  (2, 2)	3
  (3, 3)	4
  (4, 4)	5

我们再来举个例子:

python 复制代码
    row = [0, 0, 0, 1, 1, 1, 2, 2, 2]  # 行指标
    col = [0, 1, 2, 0, 1, 2, 0, 1, 2]  # 列指标
    data = [1, 0, 1, 0, 1, 1, 1, 1, 0]  # 在行指标列指标下的数字
    team = csr_matrix((data, (row, col)), shape=(3, 3))

    print(f'team is : \n{team}\n')
    print(f'team type is : \n{type(team)}\n')
    print(f'team.shape is : \n{team.shape}\n')

    team.eliminate_zeros()
    print(f'team.eliminate_zeros is : \n{team}\n')

输出结果如下;

shell 复制代码
team is : 
  (0, 0)	1
  (0, 1)	0
  (0, 2)	1
  (1, 0)	0
  (1, 1)	1
  (1, 2)	1
  (2, 0)	1
  (2, 1)	1
  (2, 2)	0

team type is : 
<class 'scipy.sparse._csr.csr_matrix'>

team.shape is : 
(3, 3)

team.eliminate_zeros is : 
  (0, 0)	1
  (0, 2)	1
  (1, 1)	1
  (1, 2)	1
  (2, 0)	1
  (2, 1)	1

可以看到team转化为另一个非稀疏的矩阵类型。

CSC和CSR的转换 (.tocsr() / .tocsc())

这个就很简单了,没什么可说的:

python 复制代码
    # csr 2 csc
    print(f'csr_matrix is  : \n{r_m}\n')
    print(f'c_m.tocsr() is  : \n{c_m.tocsr()}\n')

将对应的CSC转化成CSR:

复制代码
csr_matrix is  : 
  (0, 0)	1
  (0, 2)	6
  (0, 4)	7
  (1, 1)	2
  (2, 2)	3
  (3, 3)	4
  (4, 4)	5

c_m.tocsr() is  : 
  (0, 0)	1
  (0, 2)	6
  (0, 4)	7
  (1, 1)	2
  (2, 2)	3
  (3, 3)	4
  (4, 4)	5

图 (CSGraph)

使用邻接矩阵来构建一个图如下:

python 复制代码
    # graph part
    # 构建了一个正方形的图

    arr = np.array([
        [0, 2, 0, 4],
        [2, 0, 3, 0],
        [0, 3, 0, 4],
        [4, 0, 4, 0],
    ])
    graph = csr_matrix(arr)
    print(f'graph is  : \n{graph}\n')

示意图如下:
graph LR; A <--2-->B<--3-->C<--4-->D<--4-->A

结果如下:

shell 复制代码
graph is  : 
  (0, 1)	2
  (0, 3)	4
  (1, 0)	2
  (1, 2)	3
  (2, 1)	3
  (2, 3)	4
  (3, 0)	4
  (3, 2)	4

连通性检测 (connected_components())

python 复制代码
    n_components, labels = connected_components(graph, directed=False, connection='weak', return_labels=True)

    print("连通分量数量:", n_components)
    print("节点标签:", labels)

连通性输出结果如下:

shell 复制代码
连通分量数量: 1
节点标签: [0 0 0 0]

由于这里没有设置节点标签,所以输出全是0.

最短路 (Dijkstra()、floyd_warshall() 、bellman_ford() )

三个函数只需要将图输入进去就可以得到对应的到各个节点的最短路径。

python 复制代码
# dijkstra
print(f'dijkstra seq is : \n{dijkstra(graph, indices=0)}\n')

# Floyd warshall
print(f'floyd_warshall matrix is : \n{floyd_warshall(graph)}\n')

# bellman ford
print(f'bellman_ford matrix is : \n{bellman_ford(graph, indices=0)}\n')

结果如下:

shell 复制代码
dijkstra seq is : 
[0. 2. 5. 1.]

floyd_warshall matrix is : 
[[0. 2. 5. 1.]
 [2. 0. 3. 3.]
 [5. 3. 0. 4.]
 [1. 3. 4. 0.]]

bellman_ford matrix is : 
[0. 2. 5. 1.]

广搜与深搜 (depth_first_order(), breadth_first_order())

两个函数的作用都是以某个参数为基点返回对应的顺序和对应节点的前驱序列。

举个例子:

python 复制代码
    # depth first order
    print(f'depth_first_order seq is : \n{depth_first_order(graph, 0)}\n')

    # breadth first order
    print(f'breadth_first_order seq is : \n{breadth_first_order(graph, 0)}\n')

输出结果:

shell 复制代码
depth_first_order seq is : 
(array([0, 1, 2, 3]), array([-9999,     0,     1,     2]))

breadth_first_order seq is : 
(array([0, 1, 3, 2]), array([-9999,     0,     1,     0]))

详见:scipy.sparse.csgraph.depth_first_order --- SciPy v1.11.4 Manual

matlab数据读取与导出( io.savemat()、io.loadmat())

python 复制代码
# matlab part
# 导出matlab 数据 等等
matlab_output = io.savemat('filename.mat', {'data': arr})
print(f'matlab_output is \n {matlab_output} \n')

# 读取 matlab 数据 等等
matlab_intput = io.loadmat('filename.mat')
print(f'matlab_input is \n{matlab_intput}\n')
matlab_intput_data = matlab_intput['data']
print(f'matlab_input \'s data is \n{matlab_intput_data}\n')

输出结果如下:

返回的是字典包含了很多信息,我们可以通过字典的方式来提取内容。

shell 复制代码
matlab_output is 
 None 

matlab_input is 
{'__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Sun Dec 10 21:40:56 2023', '__version__': '1.0', '__globals__': [], 'data': array([[0, 2, 0, 1],
       [2, 0, 3, 0],
       [0, 3, 0, 4],
       [1, 0, 4, 0]])}

matlab_input 's data is 
[[0 2 0 1]
 [2 0 3 0]
 [0 3 0 4]
 [1 0 4 0]]

数据的外围又被包上了一个数组,我们可以通过如下方式来实现读取,将其变为1维的:

python 复制代码
    matlab_intput_without = io.loadmat('filename.mat', squeeze_me=True)
    print(f'matlab_intput_without is \n{matlab_intput_without}\n')
    matlab_intput_data_without = matlab_intput_without['data']
    print(f'matlab_intput_data_without \'s data is \n{matlab_intput_data_without}\n')

输出结果如下:

python 复制代码
matlab_intput_without is 
{'__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Sun Dec 10 21:44:24 2023', '__version__': '1.0', '__globals__': [], 'data': array([[0, 2, 0, 1],
       [2, 0, 3, 0],
       [0, 3, 0, 4],
       [1, 0, 4, 0]])}

参考文献

.eliminate_zeros()函数-CSDN博客

相关推荐
databook1 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar2 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780512 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_2 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机9 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机10 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机10 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机10 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i10 小时前
drf初步梳理
python·django
每日AI新事件10 小时前
python的异步函数
python