I'm training a denoising autoencoder in Tensorflow 2, one part of the run time is spent on CPU doing masking of a portion of the input data, randomly selecting the indices to be masked, then setting their values to zero. This is my masking function, this masking is repeated on the beginning of each epoch, at different v values:
import numpy as np
def masking_noise(X, v):
X_noise = X.copy()
n_samples = X.shape[0]
n_features = X.shape[1]
v = int(np.round(n_features*v))
for i in range(n_samples):
mask = np.random.choice(n_features, v, replace=False)
for m in mask:
X_noise[i][m] = np.repeat(0.,X.shape[2])
return X_noise
Here is a toy example:
a = np.array([[[1., 0.],
[1., 0.],
[1., 0.],
[1., 0.],
[0., 1.]],
[[1., 0.],
[1., 0.],
[1., 0.],
[1., 1.],
[0., 1.]],
[[1., 0.],
[1., 0.],
[1., 0.],
[1., 0.],
[1., 1.]]])
masking_noise(a, 0.40)
Output:
array([[[1., 0.],
[0., 0.],
[1., 0.],
[1., 0.],
[0., 0.]],
[[0., 0.],
[0., 0.],
[1., 0.],
[1., 1.],
[0., 1.]],
[[1., 0.],
[1., 0.],
[1., 0.],
[0., 0.],
[0., 0.]]])
My question is, how could I do the same masking operation in Tensorflow?