训练数据的稀疏向量

时间:2019-11-19 01:04:49

标签: python numpy tensorflow machine-learning pytorch

我有这样的训练数据:

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

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

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

可以请大家提出我该如何实施?谢谢!

1 个答案:

答案 0 :(得分: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.]]