2016-10-06 3 views
0

두 클래스가 있습니다. 양수 (1)와 음수 (0)입니다.TensorFlow : 이진 분류를위한 클래스 별 손실 함수를 구현하는 방법

데이터 세트가 매우 불균형하기 때문에 현재 내 미니 배치에는 대부분 0이 포함되어 있습니다. 실제로 많은 배치에는 0 만 포함됩니다. 나는 긍정적이고 부정적인 예들에 대해 별도의 비용을 가지고 실험하려고했다. 아래 코드를 참조하십시오.

내 코드의 문제점은 bound_index 목록이 비어 있기 때문에 많은 nan이 발생한다는 것입니다. 이것을 해결하는 우아한 방법은 무엇입니까? 당신이 0과 1 레이블을 가지고 있기 때문에

def calc_loss_debug(logits, labels): 
    logits = tf.reshape(logits, [-1]) 
    labels = tf.reshape(labels, [-1]) 
    index_bound = tf.where(tf.equal(labels, tf.constant(1, dtype=tf.float32))) 
    index_unbound = tf.where(tf.equal(labels, tf.constant(0, dtype=tf.float32))) 
    entropies = tf.nn.sigmoid_cross_entropy_with_logits(logits, labels) 
    entropies_bound = tf.gather(entropies, index_bound) 
    entropies_unbound = tf.gather(entropies, index_unbound) 
    loss_bound = tf.reduce_mean(entropies_bound) 
    loss_unbound = tf.reduce_mean(entropies_unbound) 
+0

나는 빈 목록의 평균을 취하고 있으므로 엔이 발생합니다 (entropies_bound는 비어 있습니다) – Stackd

답변

1

, 당신은 쉽게 평균 손실을 얻으려면이

labels = ... 
entropies = ... 
labels_complement = tf.constant(1.0, dtype=tf.float32) - labels 
entropy_ones = tf.reduce_sum(tf.mul(labels, entropies)) 
entropy_zeros = tf.reduce_sum(tf.mul(labels_complement, entropies)) 

같은 구성으로 tf.where를 방지 할 수 있습니다, 당신은 0과 1의 숫자로 분할해야

num_ones = tf.reduce_sum(labels) 
num_zeros = tf.reduce_sum(labels_complement) 

일괄 처리에 1이없는 경우에도 물론 0으로 나눌 필요가 없습니다. tf.cond(tf.equal(num_ones, 0), ...)을 사용하시기 바랍니다.

+0

고마워요. tf.conf의 0은 tf.constant (0)가 아니어야합니까? – Stackd