1. 程式人生 > >python中scipy學習——隨機稀疏矩陣及操作

python中scipy學習——隨機稀疏矩陣及操作

http 坐標 head num value 可選 https import pan

1.生成隨機稀疏矩陣

scipy中生成隨機稀疏矩陣的函數如下:

scipy.sparse.rand(m,n,density,format,dtype,random_state)
  • 1

參數介紹:

參數含義
m,n 整型;表示矩陣的行和列
density 實數類型;表示矩陣的稀疏度
format str類型;表示矩陣的類型;如format=‘coo’
dtype dtype;表示返回矩陣值的類型
ranom_state {numpy.random.RandomState,int};可選的隨機種子;如果空缺,默認numpy.random

例子

代碼如下:

import
scipy as spy n=4 m=4 density=0.5 matrixformat=coo B=spy.sparse.rand(m,n,density=density,format=matrixformat,dtype=None) print(B) >>> (1, 1) 0.0687198939788 (3, 3) 0.141328654998 (0, 3) 0.944468193258 (2, 3) 0.598652789611 (0, 2) 0.0629165518906 (
2, 0) 0.624087894456 (1, 2) 0.309460820898 (2, 2) 0.731375305002

2.稀疏矩陣的操作:

import scipy as spy

n=4
m=4
row=spy.array([0,0,0,1,1,3,3])
col=spy.array([0,0,1,2,3,2,3])
value=spy.array([1,2,1,8,1,3,5])
print(自定義生成一個csc格式的稀疏矩陣..)#‘coo‘格式的矩陣無法進行以下某些操作
A=spy.sparse.csc_matrix((value,(row,col)),shape=(n,m))
print(稀疏矩陣的非稀疏表示形式...) print(A.todense()) print(稀疏矩陣的非零元素對應坐標...) nonzero=A.nonzero() print(nonzero) print(輸出非零元素對應的行坐標和列坐標...) print(nonzero[0]) print(nonzero[1]) print(輸出第i行非零值...) i=2 print(A[i,:]) print(輸出第j列非零值...) j=2 print(A[:,j]) print(輸出坐標為(i,j)對應的值...) print(A[i,j])

輸出結果如下:

自定義生成一個csc格式的稀疏矩陣..
稀疏矩陣的非稀疏表示形式...
[[3 1 0 0]
 [0 0 8 1]
 [0 0 0 0]
 [0 0 3 5]]
稀疏矩陣的非零元素對應坐標...
(array([0, 0, 1, 1, 3, 3], dtype=int32), array([0, 1, 2, 3, 2, 3], dtype=int32))
輸出非零元素對應的行坐標和列坐標...
[0 0 1 1 3 3]
[0 1 2 3 2 3]
輸出第i行非零值...

輸出第j列非零值...
  (1, 0)        8
  (3, 0)        3
輸出坐標為(i,j)對應的值...
0

註:更多參考請查看docs.scipy.org

python中scipy學習——隨機稀疏矩陣及操作