参考资料:
Sparse Matrices For Efficient Machine Learning
Introduction to Sparse Matrices in Python with SciPy
- 如何读取大文件
for chunk in pd.read_csv('./data/small_training.txt',sep='\t',header=None,index_col=False, chunksize=11):
proccess(chunk)
参考资料首先介绍了有很多0的矩阵为稀疏矩阵,为了减少稀疏矩阵的存储空间和加快机器学习过程。sklearn很多算法支持稀疏矩阵,下面我们进行实验。
- 准备数据
产生二项分布数据(只有0或者1),其中0.01为产生1的概率,所以产生的矩阵只有1%的1
np.random.seed(seed=12) ## for reproducibility
dataset = np.random.binomial(1, 0.01, 20000000).reshape(2000,10000) ## dummy data
y = np.random.binomial(1, 0.5, 2000) ## dummy target variable
- 用matplotlib.pyplot中的spy来可视化数据稀疏情况
import matplotlib.pyplot as plt
plt.spy(dataset)
plt.title("Sparse Matrix")
plt.show()
下图中我们可以看到数据是非常稀疏的
- 转化为稀疏矩阵
from scipy.sparse import csr_matrix
sparse_dataset = csr_matrix(dataset)
- 对比稀疏矩阵和和原始矩阵
具体通过原作者的其他实验,可以看到大部分情况下会省时很多。
from sklearn.naive_bayes import BernoulliNB
nb = BernoulliNB(binarize=None)
nb.fit(dataset, y)
nb.fit(sparse_dataset, y)
最后作者还讲了稀疏矩阵的存储原理,这里就不仔细讲了。
- scipy.sparse
系数矩阵在库scipy.sparse
中,而且有多种格式,各自有优缺点。各种格式可以互相转化,也可以转化为dense矩阵。
bsr_matrix: Block Sparse Row matrix
coo_matrix: COOrdinate format matrix
csc_matrix: Compressed Sparse Column matrix
csr_matrix: Compressed Sparse Row matrix
dia_matrix: Sparse matrix with DIAgonal storage
dok_matrix: Dictionary Of Keys based sparse matrix.
lil_matrix: Row-based linked list sparse matrix