speeding up matrix corruption I need to randomly erase 33% of the non-zero elements in each line of a matrix.
Side note: The end goal is to train a denoising autoencoder to remove this noise.
My solution:
import numpy as np

matrix = np.random.rand(1000,3000)

for i in range(matrix.shape[0]):
    clean = matrix[i, :] # original matrix line
    # find non zero elements
    msk = np.nonzero(clean)
    assert sum(msk[0]) != 0
    
    # keep 66% of them
    idx = np.random.randint(0, len(msk[0]), size=max(1, len(msk[0])//3)) #erase at least 1
    msk = np.delete(msk, idx)

    dirty = clean
    dirty = [j if i in msk else 0 for i,j in enumerate(dirty)]
    assert sum(clean-dirty) != 0
    
    #save clean and dirty
    #...

My guess is that the bottleneck is drawing random numbers at each iteration.
Is there an alternative way to do this?
My guess is that the bottleneck is drawing random numbers at each iteration.

Why guess when you can measure? I changed the height to 100 so the whole thing takes me about 8 seconds, reasonable to play around with. Removing the assert line on the bottom makes it a bit faster. Also removing the dirty = [j if...] line makes it a lot faster. As you'd expect from that inefficient line.
Not sure why you're making it so complicated. I think clean[idx] = 0 does the deletions you want, and it's fast.