文章目录
一、前言
在 Python 中产生稀疏矩阵一般使用的是 scipy
包中的 sprase.rand
方法,但是产生的是 0-1 区间内的均匀分布的数,于是便自己写了个生成高斯分布的随机稀疏矩阵函数。
二、准备工作
安装 numpy
和 scipy
包:
pip install -i https://mirrors.aliyun.com/pypi/simple scipy numpy
三、稀疏均匀分布随机矩阵
对标 MATLAB 中的 sprand
函数,我们使用 scipy 中的 sprase.rand
方法即可:
from scipy.sparse import rand
产生一个
m
m
m 行
n
n
n 列的服从均匀分布的随机稀疏矩阵,其中 p = 0.1
代表非零元素在此矩阵中所占比例为 10%:
m, n, p = 20, 1, 0.1
M = rand(m, n, p)
矩阵 M 如下:
In [8]: print(M)
(1, 0) 0.6736398867550694
(6, 0) 0.990450623569146
注意这里 M 的类型并不是数组,而是 scipy.sparse.coo.coo_matrix
对象,可使用 toarray()
方法或 todense()
方法转换为 matrix 对象或 array 对象。
In [10]: type(M.toarray())
Out[10]: numpy.ndarray
In [11]: type(M.todense())
Out[11]: numpy.matrix
四、稀疏高斯分布随机矩阵
在 scipy 的 sprase 模块中并未看到由此方法,便自己写了个函数,使用了 scipy 包中的 coo_matrix
方法,对标 MATLAB 中的 sprandn
函数:
import numpy as np
from scipy.sparse import coo_matrix
自定义函数如下:
def sprase_rand(m, n, p):
'''
Imports
-------
import numpy as np
from scipy.sparse import coo_matrix
Parameters
----------
m : int
Rows of generate sprase-matrix.
n : int
Columns of generate sprase-matrix.
p : float
Proportion of non-zero elements in sparse-matrix.
Returns
-------
scipy.sparse.coo.coo_matrix
Returns a random generated sprase-matrix(m x n) M,
try print(M) to see it or use M.toarray() for trans
M to an array. (Gaussian distribution)
writen by z.q.feng @2022.03.13
'''
# Counts of non-zero elements in sparse-matrix
count = int(m * n * p)
# Indexs of non-zero elements in sparse-matrix
rows = np.random.randint(0, m, count)
cols = np.random.randint(0, n, count)
# Values of non-zero elements in sparse-matrix
# (Gaussian distribution)
data = np.random.randn(len(rows))
return coo_matrix((data, (rows, cols)), shape=(m, n))
同理,
m
,
n
m, n
m,n 分别为矩阵行数和列数,
p
p
p 为稀疏矩阵中非零元素所占比例,返回的是一个 scipy.sparse.coo.coo_matrix
对象:
m, n, p = 100, 1, 0.1
M = sprase_rand(m, n, p)
生成稀疏矩阵如下:
In [17]: print(M)
(41, 0) 0.5449276858941307
(35, 0) -0.025833278679116962
(92, 0) -0.669275138440353
(4, 0) 0.8758045217206215
(3, 0) 1.989912762888745
(0, 0) 0.11984808162782133
(10, 0) 1.3130062796121102
(31, 0) 0.3581633202721068
(33, 0) 1.0432754388670364
(62, 0) 0.4063437334997744
同理,可使用 toarray()
方法或 todense()
方法填充转换为 matrix 对象或 array 对象。
五、总结
不喜欢写总结。