【问题标题】:random split sparse.lil_matrix in pythonpython中的随机拆分sparse.lil_matrix
【发布时间】:2017-02-08 18:48:25
【问题描述】:

我是 Python 新手,我正在使用以下方式以链接列表矩阵格式存储数据。

>>> from scipy import sparse,random
>>> m = 2
>>> X = [sparse.lil_matrix((5,5)) for i in range(m)]
>>> X[0][0,1] = 1 
>>> X[0][2,3] = 1
>>> X[1][0,4] = 1
>>> X[1][1,4] = 1
>>> X[1][2,4] = 1 
>>> X

    [<5x5 sparse matrix of type '<type 'numpy.float64'>'
        with 2 stored elements in LInked List format>, <5x5 sparse matrix of type '<type 'numpy.float64'>'
        with 3 stored elements in LInked List format>]

有没有办法将这个 lil_matrix X 随机划分为训练(75%)和测试集(25%)

【问题讨论】:

    标签: python matrix scipy


    【解决方案1】:

    首先,您的X 是一个包含两个稀疏矩阵的列表。

    但如果我创建一个稀疏矩阵,我可以通过简单的索引从中选择行:

    In [41]: M=sparse.lil_matrix(np.eye(5))
    
    In [42]: M
    Out[42]: 
    <5x5 sparse matrix of type '<class 'numpy.float64'>'
        with 5 stored elements in LInked List format>
    
    In [43]: M.A
    Out[43]: 
    array([[ 1.,  0.,  0.,  0.,  0.],
           [ 0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  1.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  0.,  1.]])
    
    In [44]: M[[0,1,4],:]
    Out[44]: 
    <3x5 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in LInked List format>
    
    In [45]: M[[2,3],:]
    Out[45]: 
    <2x5 sparse matrix of type '<class 'numpy.float64'>'
        with 2 stored elements in LInked List format>
    
    In [46]: M[[2,3],:].A
    Out[46]: 
    array([[ 0.,  0.,  1.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.]])
    

    稀疏矩阵的行索引不如密集数组快,但至少对lilcsr 格式有效。

    scipy.sparse 包中没有什么特别之处可以像这样拆分矩阵。您必须自己制定随机索引。

    sklearn.model_selection.train_test_split 处理Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes. 跟踪代码,实际拆分是用utils.safe_indexing(X, indices) 完成的,可以处理多种X。但就像我演示的那样,它就像一个sparse 矩阵被索引。它可能需要csr 格式而不是lil

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 2013-01-13
      • 2018-08-13
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多