a6657266的个人博客分享 http://blog.sciencenet.cn/u/a6657266

博文

python theano的稀疏矩阵

已有 12988 次阅读 2013-7-12 10:16 |系统分类:科研笔记| Python

theano支持两种稀疏矩阵,csc,csr,分别是按照列和行对数据进行存储的。每个稀疏矩阵都有data,indices,indptr和shape四个属性。

data属性:一维ndarray,包含所有非零元素

indices和indptr属性是用来存储稀疏矩阵中数据所在的位置

shape属性与密集矩阵的shape属性是一致的,如果稀疏矩阵的形状不能从前三个属性推断出来的话,需要在创建的时候就说明形状属性

 

对于csc以及csr两种形式的选择

如果矩阵的列数较大,即行数较少,用csr格式

如果矩阵的行数较大,即列数较少,用csc格式

 

import theano

import numpy as np

import scipy.sparse as sp

from theano import sparse

在稀疏矩阵和密集矩阵之间转换的时候,有三个函数属性可以使用,例子如下:

>>> x=sparse.csc_matrix(name='x',dtype='float32')
>>> y=sparse.dense_from_sparse(x)
>>> z=sparse.csc_from_dense(y)

创建稀疏矩阵,可以用已知的属性通过CSR,CSC函数来创建

>>> x=sparse.csc_matrix(name='x',dtype='int64')
>>> data,indices,indptr,shape=sparse.csm_properties(x)
>>> y=sparse.CSR(data,indices,indptr,shape)
>>> f=theano.function([x],y)
>>> a=sp.csc_matrix(np.asarray([[0,1,1],[0,0,0],[1,0,0]]))
>>> print a.toarray()
[[0 1 1]
[0 0 0]
[1 0 0]]
>>> print f(a).toarray()
[[0 0 1]
[1 0 0]
[1 0 0]]

​对稀疏矩阵中非零元素进行加,减,乘,除操作

>>> x=sparse.csc_matrix(name='x',dtype='float32')
>>> y=sparse.structured_add(x,2) ##此处就是将稀疏矩阵中非零元素都加2
>>> f=theano.function([x],y)
>>> a=sp.csc_matrix(np.asarray([[0,0,-1],[0,-2,1],[3,0,0]],dtype='float32'))
>>> printa.toarray()
[[ 0.  0. -1.]
[ 0. -2.  1.]
[ 3.  0.  0.]]
>>> printf(a).toarray()
[[ 0.  0.  1.]
[ 0.  0.  3.]
[ 5.  0.  0.]]




https://wap.sciencenet.cn/blog-571755-707390.html

上一篇:python中的ifelse以及switch
下一篇:deep learning学习推荐网址
收藏 IP: 210.72.26.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-11 13:57

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部