모든 챌린지
쉬움 0명 해결 정답률 0%

Categorical Cross-Entropy Loss

Measure the loss of a multi-class classifier from its predicted probabilities and the true classes.

배우게 될 내용

  • Score predicted probabilities against true classes
  • Average the loss over samples
  • Avoid log(0) with clipping

문제

번역본 보기

A multi-class classifier outputs one probability per class (for example from softmax). Categorical cross-entropy punishes it for giving the correct class a low probability:

loss = -(ln(p₁) + ln(p₂) + … + ln(pₙ)) / n

where pᵢ is the probability the model gave to the correct class of sample i. To avoid ln(0), first raise any probability below 0.0000001 to 0.0000001.

Implement categorical_cross_entropy(probabilities, labels).

Input

probabilities: One row per sample, with one probability per class.

labels: The index of the correct class for each sample (0-based).

Output

Return the average loss as a decimal number.

제약 조건

1 ≤ samples ≤ 1,000, 2 ≤ classes ≤ 100

0 ≤ each probability ≤ 1

0 ≤ labels[i] < number of classes

예시

예시 1
입력:
labels = [0, 1]
probabilities = [
    [0.7, 0.2, 0.1],
    [0.1, 0.8, 0.1]
]

예상 출력:
expected = 0.289909
입력:
std::vector<long long> labels = {0, 1};
std::vector<std::vector<double>> probabilities = {
    {0.7, 0.2, 0.1},
    {0.1, 0.8, 0.1}
};

예상 출력:
double expected = 0.289909;
입력:
long[] labels = new long[] {0, 1};
double[][] probabilities = new double[][] {
    new double[] {0.7, 0.2, 0.1},
    new double[] {0.1, 0.8, 0.1}
};

예상 출력:
double expected = 0.289909;

설명

The correct classes got 0.7 and 0.8: -(ln(0.7) + ln(0.8)) / 2 = -(-0.356675 - 0.223144) / 2 ≈ 0.289909.

예시 2
입력:
labels = [1]
probabilities = [
    [1.0, 0.0]
]

예상 출력:
expected = 16.118096
입력:
std::vector<long long> labels = {1};
std::vector<std::vector<double>> probabilities = {
    {1.0, 0.0}
};

예상 출력:
double expected = 16.118096;
입력:
long[] labels = new long[] {1};
double[][] probabilities = new double[][] {
    new double[] {1.0, 0.0}
};

예상 출력:
double expected = 16.118096;

설명

The correct class got probability 0, which is raised to 0.0000001, so the loss is -ln(0.0000001) ≈ 16.118096: a confident wrong answer is punished hard.

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.