2017-03-26 1 views
1

예상 된 2 변수 gaussian 분포 매개 변수로부터 지상 진리 값 (x, y)을 얻는 부정적인 로그 가능성을 최소화하려고하는 손실 함수를 구현하려고합니다. ,2 변수 가우시안의 로그 우도 (log likelihood)의 음수 값

나는 훈련을하고있는 중이 야
def tf_2d_normal(self, x, y, mux, muy, sx, sy, rho): 
    ''' 
    Function that implements the PDF of a 2D normal distribution 
    params: 
    x : input x points 
    y : input y points 
    mux : mean of the distribution in x 
    muy : mean of the distribution in y 
    sx : std dev of the distribution in x 
    sy : std dev of the distribution in y 
    rho : Correlation factor of the distribution 
    ''' 
    # eq 3 in the paper 
    # and eq 24 & 25 in Graves (2013) 
    # Calculate (x - mux) and (y-muy) 
    normx = tf.sub(x, mux) 
    normy = tf.sub(y, muy) 
    # Calculate sx*sy 
    sxsy = tf.mul(sx, sy) 
    # Calculate the exponential factor 
    z = tf.square(tf.div(normx, sx)) + tf.square(tf.div(normy, sy)) - 2*tf.div(tf.mul(rho, tf.mul(normx, normy)), sxsy) 
    negRho = 1 - tf.square(rho) 
    # Numerator 
    result = tf.exp(tf.div(-z, 2*negRho)) 
    # Normalization constant 
    denom = 2 * np.pi * tf.mul(sxsy, tf.sqrt(negRho)) 
    # Final PDF calculation 
    result = -tf.log(tf.div(result, denom)) 
    return result 

, 나는 손실 값이 감소 볼 수 있지만 그것을 잘 0 아래를지나 나는 그 때문에해야 이해할 수 간다 - 여기 를 코드입니다 - 나는 tensorflow이를 구현하고있다 우리는 '부정'가능성을 최소화하고 있습니다. 손실 값이 감소하더라도 정확한 결과를 얻을 수 없습니다. 내가 잃어버린 기능에 대해 작성한 코드가 맞는지 아닌지를 확인하는 데 도움을 줄 수 있습니까?

또한 신경망 (특히 RNN)을 학습하는 데 바람직한 손실의 성격이 있습니까?

Thankss는

답변

1

나는 비슷한 일하고 있어요, 당신은 마젠타에서 sketch-rnn code을 발견했습니다 참조하십시오. 나는이 코드 조각이 그 자체로 안정적이지 않다는 것을 발견했다. 제약 조건을 사용하여 코드를 안정화해야하므로 tf_2d_normal 코드를 별도로 사용하거나 해석 할 수 없습니다. NaNInf은 데이터가 사전에 제대로 정상화되지 않았거나 손실 기능에 정상적으로 나타나지 않으면 모든 곳에서 나타나기 시작할 것입니다.

다음은 Keras로 구축 할 때보다 안정적인 손실 기능 버전입니다. 여기에 약간의 중복이있을 수 있습니다, 그것은 귀하의 요구에 완벽하지 않을 수도 있지만 작동하고 그것을 테스트/적응할 수있는 것으로 나타났습니다. 큰 음수 로그 값이 발생할 수있는 방법에 대한 몇 가지 인라인 코멘트를 포함했습니다.

def r3_bivariate_gaussian_loss(true, pred): 
    """ 
    Rank 3 bivariate gaussian loss function 
    Returns results of eq # 24 of http://arxiv.org/abs/1308.0850 
    :param true: truth values with at least [mu1, mu2, sigma1, sigma2, rho] 
    :param pred: values predicted from a model with the same shape requirements as truth values 
    :return: the log of the summed max likelihood 
    """ 
    x_coord = true[:, :, 0] 
    y_coord = true[:, :, 1] 
    mu_x = pred[:, :, 0] 
    mu_y = pred[:, :, 1] 

    # exponentiate the sigmas and also make correlative rho between -1 and 1. 
    # eq. # 21 and 22 of http://arxiv.org/abs/1308.0850 
    # analogous to https://github.com/tensorflow/magenta/blob/master/magenta/models/sketch_rnn/model.py#L326 
    sigma_x = K.exp(K.abs(pred[:, :, 2])) 
    sigma_y = K.exp(K.abs(pred[:, :, 3])) 
    rho = K.tanh(pred[:, :, 4]) * 0.1 # avoid drifting to -1 or 1 to prevent NaN, you will have to tweak this multiplier value to suit the shape of your data 

    norm1 = K.log(1 + K.abs(x_coord - mu_x)) 
    norm2 = K.log(1 + K.abs(y_coord - mu_y)) 

    variance_x = K.softplus(K.square(sigma_x)) 
    variance_y = K.softplus(K.square(sigma_y)) 
    s1s2 = K.softplus(sigma_x * sigma_y) # very large if sigma_x and/or sigma_y are very large 

    # eq 25 of http://arxiv.org/abs/1308.0850 
    z = ((K.square(norm1)/variance_x) + 
     (K.square(norm2)/variance_y) - 
     (2 * rho * norm1 * norm2/s1s2)) # z → -∞ if rho * norm1 * norm2 → ∞ and/or s1s2 → 0 
    neg_rho = 1 - K.square(rho) # → 0 if rho → {1, -1} 
    numerator = K.exp(-z/(2 * neg_rho)) # → ∞ if z → -∞ and/or neg_rho → 0 
    denominator = (2 * np.pi * s1s2 * K.sqrt(neg_rho)) + epsilon() # → 0 if s1s2 → 0 and/or neg_rho → 0 
    pdf = numerator/denominator # → ∞ if denominator → 0 and/or if numerator → ∞ 
    return K.log(K.sum(-K.log(pdf + epsilon()))) # → -∞ if pdf → ∞ 

희망 사항을 찾으십시오.