티스토리 뷰

반응형

0. logit, sigmoid, softmax

 본격적인 솔실함수를 보기 전에 logit, sigmoid, softmax에 대해 알아보자.

 

0.1 sigmoid함수

sigmoid 함수는 인공신경망에서 ReLU가 등장하기 이전에활발하게 사용되었던 activation function(활성화함수)이고, hiddin 노드 바로 뒤에 부착된다. 클래스가 2개이다.

 

 

 

Sigmoid 함수는 모든 실수 입력 값을 0보다 크고 1보다 작은 미분 가능한 수로 변환한다. 그리고 미분결과가 간결하고 쉬워 초기에 많이 사용되었다.

 

 

0.2 softmax함수

softmax함수는 인공신경망에서 출력된 K개의 클래스 구분 결과를 확률처럼 해석하도록 만들어준다. 따라서 보통은 output 노두 바로 뒤에 부착된다.

코드 사용 시, sigmoid는 activation에서 사용되고 softmax는 classification에서 주로 사용되지만, 수학적으로는 서로 같은 함수이다. 다만 다루는 클래스가 2개냐 K개냐의 차이가 있다.

 

0.3 logit 함수

logit함수는 logistic과 probit의 합성어이다. 그리고 sigmoid 함수와는 서로 역함수 관계이다.

 

0.4 ReLU

 

 

1. binary_crossentropy

def binary_crossentropy(target, output, from_logits=False):
    """Binary crossentropy between an output tensor and a target tensor.

    # Arguments
        target: A tensor with the same shape as `output`.
        output: A tensor.
        from_logits: Whether `output` is expected to be a logits tensor.
            By default, we consider that `output`
            encodes a probability distribution.

    # Returns
        A tensor.
    """
    # Note: tf.nn.sigmoid_cross_entropy_with_logits
    # expects logits, Keras expects probabilities.
    if not from_logits:
        # transform back to logits
        _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
        output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
        output = tf.log(output / (1 - output))

    return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,
                                                   logits=output)

 함수의 두번째 인자가 from_logits=False라는 것을 인지하자. if not form_logits의 구문을 보면 transform back to logits라는 걸 확인 할 수 있다. 즉, binary_crossentropy를 쓰면서 from_logits옵션을 따로 안 넣으면 output layer에 sigmoid를 추가해야한다. from_logits=True를 추가 했다면, 마지막에 sigmoid activation을 하지 않아도 된다.

 

 

1-2. 위의 binary_crossentropy와 아래의 categorical_crossentropy 비교.

 결론적으로 둘의 차이는 output layer가 sigmoid이냐 softmax이냐이다. 즉,

  • 내가 가진 label 값이 0 or 1 이면서 sigmoid_cross_entropy를 loss로 하고 싶으면 binary_crossentropy 를 쓰면 된다.
  • 내가 가진 라벨이 [0,1] or [1,0] 의 형태이면서 softmax_cross_entropy를 loss로 하고자 할 때는 categorical_crossentropy를 쓰면 된다.
  • label 이 0 or 1 인데 softmax_cross_entropy를 쓰고싶으면 sparse_categorical_crossentropy를 쓰면 된다.

binary_crossentropy는 logistic regression 아니면 별로 쓸일이 없을 거 같고 categorical_crossentropy나 sparse_categorical_crossentropy를 주로 쓸 듯하다.

2. categorical_crossentropy

def categorical_crossentropy(target, output, from_logits=False, axis=-1):
    """Categorical crossentropy between an output tensor and a target tensor.

    # Arguments
        target: A tensor of the same shape as `output`.
        output: A tensor resulting from a softmax
            (unless `from_logits` is True, in which
            case `output` is expected to be the logits).
        from_logits: Boolean, whether `output` is the
            result of a softmax, or is a tensor of logits.
        axis: Int specifying the channels axis. `axis=-1`
            corresponds to data format `channels_last`,
            and `axis=1` corresponds to data format
            `channels_first`.

    # Returns
        Output tensor.

    # Raises
        ValueError: if `axis` is neither -1 nor one of
            the axes of `output`.
    """
    output_dimensions = list(range(len(output.get_shape())))
    if axis != -1 and axis not in output_dimensions:
        raise ValueError(
            '{}{}{}'.format(
                'Unexpected channels axis {}. '.format(axis),
                'Expected to be -1 or one of the axes of `output`, ',
                'which has {} dimensions.'.format(len(output.get_shape()))))
    # Note: tf.nn.softmax_cross_entropy_with_logits
    # expects logits, Keras expects probabilities.
    if not from_logits:
        # scale preds so that the class probas of each sample sum to 1
        output /= tf.reduce_sum(output, axis, True)
        # manual computation of crossentropy
        _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
        output = tf.clip_by_value(output, _epsilon, 1. - _epsilon)
        return - tf.reduce_sum(target * tf.log(output), axis)
    else:
        return tf.nn.softmax_cross_entropy_with_logits(labels=target,
                                                       logits=output)

 여기도 logit옵션이 기본적으로 False이다. multiclass classification 문제를 해결하고자 한다면 마지막에 softmax를 해주어야한다. from_logits=True로 하면 softmax 가 자동으로 적용된다.

 

 

3. MSE(Mean Squared Error)_평균 제곱 오차

평균제곱오차(MSE)는 Regression 과 같은 실수 기반의 결과에 대한 오차를 판별하는 방식이다. Classification 과 같은 경우 2진 분류로 판별이 가능하지만, 주식 가격 예측과 같은 수치 판단은 애매한 경우가 많다.

 

예시로, 실제 값이 100,000 원인 주식 가격을 내가 만든 모델이 95,000원 이라고 판별한다면, 이 모델이 얼마나 잘 판단한 것인지 애매하다.

 

따라서 실제 값과 예측값의 차이를 기준으로 오차를 판단하는 방식이다.

 

MSE = (실제값 - 예측값)^2 / 크기

 

4. CEE(Cross Entropy Error)_교차 엔트로피 오차

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함