Tensorflow 2.0,用1替换张量中的0值

Jai*_*tas 7 python tensorflow

因此,我尝试使用张量流实现居中和缩放,其中我需要将张量中的值==0替换为1.0。

我知道用 numpy 来做到这一点x_std[x_std == 0.0] = 1.0,但无法找出在 TensorFlow 2.0 上做到这一点的最佳方法。

代码是:

def _center_scale_xy(X, Y, scale=True):
    """ Center X, Y and scale if the scale parameter==True
    Returns
    -------
        X, Y, x_mean, y_mean, x_std, y_std
    """
    # center
    x_mean = tf.reduce_mean(X,axis=0)
    X -= x_mean
    y_mean = tf.reduce_mean(Y,axis=0)
    Y -= y_mean
    # scale
    if scale:
        x_std = tf.math.reduce_std(X,axis=0)
        #x_std[x_std == 0.0] = 1.0 #This one I need to implement with tensors
        X /= x_std
        y_std = tf.math.reduce_std(Y,axis=0)
        y_std[y_std == 0.0] = 1.0
        Y /= y_std
    else:
        x_std = np.ones(X.shape[1])
        y_std = np.ones(Y.shape[1])
    return X, Y, x_mean, y_mean, x_std, y_std
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 8

tf.where像这样使用:

x_std = tf.where(tf.equal(x_std, 0), tf.ones_like(x_std), x_std)
Run Code Online (Sandbox Code Playgroud)