scipy.sparse.lil_matrix

scipy.sparse.lil_matrix

class scipy.sparse.lil_matrix(arg1, shape=None, dtype=None, copy=False)

Row-based LIst of Lists sparse matrix.

This is a structure for constructing sparse matrices incrementally. Note that inserting a single item can take linear time in the worst case; to construct the matrix efficiently, make sure the items are pre-sorted by index, per row.

See https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html

一些测试

python 复制代码
# -*- coding: utf-8 -*-
import numpy as np
from scipy.sparse import csr_matrix, lil_matrix
from scipy.sparse.linalg import spsolve
import scipy.sparse as sp
import scipy.linalg as la

def Compute_Row_Index(indptr):
    row=len(indptr)-1
    l=indptr[1]-indptr[0]
    z=np.zeros(l)
    a=list(z)#行索引,计算如下
    for i in range(1,row):
        l=indptr[i+1]-indptr[i]
        z=np.ones(l)
        a=a+list(z*i)
    a=np.array(a,dtype=np.int64)
    return a
# 创建一个稀疏矩阵
data = np.array([1, 2, 3, 4, 5, 6])
indices = np.array([0, 2, 2, 0, 1, 2])
indptr = np.array([0, 2, 3, 6])
 
# 将数据转换为CSR格式
A = csr_matrix((data, indices, indptr), shape=(3, 3))

# 访问CSR格式的属性
print("CSR格式的数据:", A.data)
print("CSR格式的列索引:", A.indices)
print("CSR格式的行指针:", A.indptr)
#print(A.todense())

data = np.array([1, 2, 3, 4, 5, 6])
indices = np.array([0, 1, 2, 0, 1, 2])
indptr = np.array([0, 1, 3, 6])
 
# 将数据转换为CSR格式
A2 = csr_matrix((data, indices, indptr), shape=(3, 3))
print(A2.todense())


#%%
# 创建一个CSR矩阵
row_ind = np.array([0, 0, 1, 2, 2, 2])
col_ind = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 1, 1, 2, 2, 2])
A1 = csr_matrix((data, (row_ind, col_ind)), shape=(3, 3))
A0 = lil_matrix((3, 3))
A00 = lil_matrix((3, 3))
#row_ind1=Compute_Row_Index(A1.indptr)
A0[row_ind,col_ind]=data
print('+++++++++')
print(A0.rows)
print(A0.rows[0])
#A00[A0.rows]=A0.data
#print(A1.data)
#print(A1.tocsr())
print(A1.todense())
print(A0.todense())
#这里生成矩阵A的方式和前面不一样,这应该是COO存储方式
# 创建右侧向量
b = np.array([1, 1, 1])

# 使用spsolve求解方程组Ax = b
#x = spsolve(A.tocsr(), b)
x1 = spsolve(A1, b)
x0 = spsolve(csr_matrix(A0), b)
print("解向量x:")
print(x1)
print(x0)
print('两个csr矩阵是否可以相加')
print((A2+A1).todense())

# 打印结果


N = 5
A = sp.diags([1, -2, 1], [1, 0, -1], shape=[N, N], format='csc')
b = -np.ones(N)
x = sp.linalg.spsolve(A, b)
print("解向量x:", x)
B = A.todense()#为了对比,我们也使用SciPy提供的稠密矩阵求解器:
x = la.solve(B, b)#上了一万的矩阵储存直接不够,且求解非常慢
print("解向量x:", x)

from scipy.sparse import diags
 
# 假设我们有两个对角线上的1d数组
diag1 = np.array([1, 2, 3, 4])
diag2 = np.array([5, 6, 7, 8])
 
# 创建稀疏对角分块矩阵
# 这里的-1和1分别表示主对角线下方和上方
# 参数(offsets, data, shape, format, dtype)
A = diags([diag1, diag2], [-1, 1], shape=(len(diag1)+1, len(diag1)+1), format='csr', dtype=np.int32)
 
# 打印矩阵
print(A.toarray())

from scipy.sparse import csr_matrix
# 定义矩阵大小N
N = 4
# 创建一个NxN的稀疏矩阵,初始为全零
sparse_matrix = csr_matrix((N, N), dtype=float).toarray()
'''
这段代码首先导入了csr_matrix类,然后定义了矩阵的大小N。接着,
它创建了一个NxN的矩阵,初始化为全零,并通过调用toarray()将稀疏矩阵
转换为普通的二维数组,最后打印出这个矩阵。
如果你不想将稀疏矩阵转换为普通数组,而是想保持稀疏矩阵的结构,
你可以直接操作稀疏矩阵。在稀疏矩阵中,非零元素通常被存储为
一组三元组(row, column, value),这些三元组可以直接用来构造稀疏矩阵。
# 打印矩阵
'''
print('申请一个空数组')
print(sparse_matrix)

 
# 创建一个空的csr_matrix
row = np.array([0, 0, 1, 2, 2])
col = np.array([0, 2, 2, 0, 1])
data = np.array([1, 2, 3, 4, 5])
shape = (3, 3)
 
csr_mat = csr_matrix((data, (row, col)), shape=shape)
print(csr_mat.toarray())
# 通过索引给特定位置赋值
csr_mat.data[0]= 6
 
# 使用update方法给特定行或列赋值
new_data = np.array([7, 8, 9])
#csr_mat.set_value(new_data, (0, slice(None)))  # 赋值给第一行
 
print(csr_mat.toarray())


#python 给csr_matrix添加元素
# 假设我们已经有了一个csr_matrix
A = csr_matrix((3, 3), dtype=int)#创建一个3x3的0元素矩阵
# 添加单个元素
row = 1
col = 1
value = 5
 
# 创建一个新的矩阵,它将是A和新元素的合并
B = csr_matrix(([value], ([row], [col])), shape=A.shape)
 
# 合并两个矩阵
A = A + B
 
print(A.toarray())  # 转换为普通数组以便打印
python 复制代码
import numpy as np
from scipy.sparse import csr_matrix, lil_matrix
from scipy.sparse.linalg import spsolve
import scipy.sparse as sp
import scipy.linalg as la
 
# Create sparse matrix.
graph = csr_matrix((6, 6))
# Change sparse matrix.
#graph[(1, 1)] = 1      # --- SLOW --- ^1
# Do some calculations.
#graph += graph
print(graph.todense())


#修改csr_matrix中元素的值,如果直接使用上面的方式会出现警告
#根据https://stackoverflow.com/questions/38241386/what-is-the-correct-way-to-add-elements-to-a-csr-matrix
#采用先定义lil_matrix,修改其值再转化为csr_matrix
# Create sparse matrix.
graph = lil_matrix((10, 10))
# Change sparse matrix.
graph[(1, 1)] = 1
graph[(2, 1),(4, 3)] = [2,3]
L=np.array([3,4,5],dtype=np.int64)
graph[(L,L)] = [6,7,8]
graph[8, 8] = 2
graph[8, 8]=graph[8, 8]+3
# Done with changes to graph. Convert to csr.
graph = csr_matrix(graph)
print(graph.todense())
# Do some calculations.
graph += graph

##
indptr=[0,2,5,7]#列索引

row=len(indptr)-1
a=[]#行索引,计算如下
for i in range(0,row):
    if(i==0):
        l=indptr[i+1]-indptr[i]
        z=np.zeros(l)
        a=a+list(z)
    else:
        l=indptr[i+1]-indptr[i]
        z=np.ones(l)
        a=a+list(z*i)
a=np.array(a,dtype=np.int64)
print(a)
#%%    
indices=[1,3,0,1,3,0,2]
data=[1,2,1,1,2,2,5]
#创建稀疏矩阵的方式一
B=csr_matrix((data, indices, indptr))
print(B.toarray())
#创建稀疏矩阵的方式二
#C=csr_matrix((data, (a,indices)), shape=(3, 4))
C=csr_matrix((data, (a,indices)))
print(C.toarray())
相关推荐
2401_858120264 小时前
探索sklearn文本向量化:从词袋到深度学习的转变
开发语言·python·机器学习
bigbearxyz6 小时前
Java实现图片的垂直方向拼接
java·windows·python
立秋67896 小时前
使用Python绘制堆积柱形图
开发语言·python
jOkerSdl6 小时前
第三十章 方法大全(Python)
python
小白学大数据6 小时前
HTML内容爬取:使用Objective-C进行网页数据提取
大数据·爬虫·python·html·objective-c·cocoa
逆境清醒7 小时前
开源数据科学平台Anaconda简介
人工智能·python·深度学习·机器学习·anaconda
SleepingBug7 小时前
[python][Anaconda]使用jupyter打开F盘或其他盘文件
开发语言·python·jupyter
mm_exploration7 小时前
torch常用函数
pytorch·python·深度学习
c实例7 小时前
爬虫 属性 方法
爬虫·python
爱煲汤的夏二7 小时前
CI脚本的python基础
java·python·ci/cd