【问题标题】:Divide a sparse matrix into train and test将稀疏矩阵划分为训练和测试
【发布时间】:2019-12-10 21:30:00
【问题描述】:

嗨,我有一个以这种方式构建的稀疏 csr 矩阵:

userid = list(np.sort(matrix.USERID.unique()))  # Get our unique customers
artid = list(matrix.ARTID.unique())  # Get our unique products that were purchased
click = list(matrix.TOTALCLICK)

rows = pd.Categorical(matrix.USERID, categories=userid).codes

# Get the associated row indices
cols = pd.Categorical(matrix.ARTID, categories=artid).codes

# Get the associated column indices
item_sparse = sparse.csr_matrix((click, (rows, cols)), shape=(len(userid), len(artid)))

原始的matrix 包含用户与网站上产品的交互。

我最终得到了这种格式的稀疏矩阵

  (0, 4136) 1
  (0, 5553) 1
  (0, 9089) 1
  (0, 24104) 3
  (0, 28061) 2
  (1, 0)    2
  (1, 224)  1
  (1, 226)  1
  (1, 324)  2
  (1, 341)  1
  (1, 530)  1
  (1, 642)  1
  (1, 658)  1

如何按第一个索引(用户)对这个稀疏矩阵进行分组,然后将前 80% 的行用于训练集,将另外 20% 的行用于测试集。我应该以两个矩阵结束

训练:

  (0, 4136) 1
  (0, 5553) 1
  (0, 9089) 1
  (1, 0)    2
  (1, 224)  1
  (1, 226)  1
  (1, 324)  2
  (1, 341)  1
  (1, 530)  1

测试:

  (0, 24104)    3
  (0, 28061)    2
  (1, 642)      1
  (1, 658)      1

【问题讨论】:

    标签: python sparse-matrix


    【解决方案1】:

    您可以使用StratifiedShuffleSplit(或者如果您不想洗牌,也可以使用StratifiedKFold,但您需要进行 5 次拆分才能获得 80%/20% 的训练/测试拆分,因为您不能以其他方式控制测试大小。) scikit-learn 中的类:

    import sklearn.model_selection
    import numpy as np
    
    # Array similar to your structure
    x = np.asarray([[0,4136,1],[0,5553,1],[0,9089,1],[1,0,2], \
                    [1,224,1],[1,226,1],[1,324,2],[1,341,1],[1,530,1]])
    # Get train and test indices using x[:,0] to define the 'classes'
    cv = sklearn.model_selection.StratifiedShuffleSplit(n_splits=1, test_size=0.2)
    # Note, X isn't actually used in the method, np.zeros(n_samples) would also work
    # Also note that cv.split is an iterator with 1 element (split), 
    # hence getting the first element of the list
    train_idx, test_idx = list(cv.split(X=x, y=x[:,0]))[0]
    
    print("Training")
    for i in train_idx:
        print(x[i,:2], x[i,2])
    print("Test")
    for i in test_idx: 
        print(x[i,:2], x[i,2])
    

    我对稀疏矩阵没有太多经验,所以希望您可以根据我的示例进行必要的调整。

    【讨论】:

    • 如果有人使用稀疏矩阵,您将稀疏矩阵转换为密集矩阵是因为内存限制。我觉得这不能回答问题。
    【解决方案2】:

    使用 sklearn api train_test_split 您将为该方法提供 3 个参数,您的矩阵拆分比率和随机状态。如果您想以相同的结果再次拆分,随机状态非常有用。

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 2017-10-20
      • 1970-01-01
      • 2016-10-25
      • 2018-01-19
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多