Skip to main content
 首页 » 编程设计

python之Tensorflow 2.0,将张量中的 0 值替换为 1s

2024年09月03日25fff_TT

所以我正在尝试使用 tensorflow 实现居中和缩放,我需要用 1.0 替换张量中的 values==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 

请您参考如下方法:

使用tf.where像这样:

x_std = tf.where(tf.equal(x_std, 0), tf.ones_like(x_std), x_std)