【问题标题】:Sparse vectors for training data训练数据的稀疏向量
【发布时间】:2020-03-14 10:50:45
【问题描述】:

我有这样的训练数据:

x_train = np.random.randint(100, size=(1000, 25))

其中每一行都是一个样本,因此我们有 1000 个样本。

现在我需要训练数据,以便每个样本/行在 25 个中最多可以有 3 个非零元素。

你们能建议我如何实现它吗?谢谢!

【问题讨论】:

    标签: python numpy tensorflow machine-learning pytorch


    【解决方案1】:

    我假设您希望将大部分数据变为零,但每行保留(随机)0 到 3 个非零元素。如果是这种情况,可能的方法如下。

    代码

    import numpy as np
    max_ = 3
    nrows = 1000
    ncols = 25
    
    np.random.seed(7)
    
    X = np.zeros((nrows,ncols))
    
    data = np.random.randint(100, size=(nrows, ncols))
    
    # number of max non-zeros to be generated for each column
    vmax = np.random.randint(low=0, high=4, size=(nrows,))
    
    for i in range(nrows):
    
      if vmax[i]>0:
          #index for setting non-zeros
          col = np.random.randint(low=0, high=ncols, size=(1,vmax[i]))
    
          #set non-zeros elements
          X[i][col] = data[i][col]
    
    print(X)
    

    输出

    [[ 0. 68. 25. ...  0.  0.  0.]
     [ 0.  0.  0. ...  0.  0.  0.]
     [ 0.  0.  0. ...  0.  0.  0.]
     ...
     [ 0.  0.  0. ...  0.  0.  0.]
     [88.  0.  0. ...  0.  0.  0.]
     [ 0.  0.  0. ...  0.  0.  0.]]
    

    【讨论】:

    • 谢谢!我现在正在尝试。
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多