Sparse vectors for training data
I have a training data like this:

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


where each row is a sample and thus we have 1000 samples.

Now I need to have the training data such that for each of the sample/row there can be at max 3 non-zero elements out of 25.

Can you all please suggest how I can implement that? Thanks!

I am assuming that you want to turn a majority of your data into zeros, except that 0 to 3 non-zero elements are retained (randomly) for each row. If this is the case, a possible way to do this is as follows.

Code

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]&gt;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)


Output

[[ 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.]]

