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

Loss Functions: MSE, MAE and Cross-Entropy

Measure how wrong a model's predictions are with mean squared error, mean absolute error or binary cross-entropy.

배우게 될 내용

  • Measure prediction error in three ways
  • Clip probabilities to avoid log(0)
  • Choose a loss for regression or classification

문제

번역본 보기

A loss function turns a model's mistakes into one number to minimize. Implement compute_loss(kind, predictions, targets) for three common losses, where n is the number of predictions:

  • "mse" (mean squared error): average of (p - t)²
  • "mae" (mean absolute error): average of |p - t|
  • "binary_cross_entropy": -average of [t × ln(p) + (1 - t) × ln(1 - p)]. First clip each prediction p to the range [0.0000001, 0.9999999] so the logarithm is never ln(0).

Input

kind: "mse", "mae" or "binary_cross_entropy".

predictions: The model's predictions.

targets: The correct values (same length). For cross-entropy they are 0 or 1 and predictions are between 0 and 1.

Output

Return the loss as a decimal number.

제약 조건

1 ≤ length ≤ 1,000

-1,000 ≤ each value ≤ 1,000 (0 ≤ p ≤ 1 and t ∈ {0, 1} for cross-entropy)

예시

예시 1
입력:
kind = "mse"
targets = [3.0, -0.5, 2.0]
predictions = [2.5, 0.0, 2.0]

예상 출력:
expected = 0.166667
입력:
std::string kind = "mse";
std::vector<double> targets = {3.0, -0.5, 2.0};
std::vector<double> predictions = {2.5, 0.0, 2.0};

예상 출력:
double expected = 0.166667;
입력:
string kind = "mse";
double[] targets = new double[] {3.0, -0.5, 2.0};
double[] predictions = new double[] {2.5, 0.0, 2.0};

예상 출력:
double expected = 0.166667;

설명

Squared errors: 0.5² = 0.25, 0.5² = 0.25 and 0² = 0. Their average is 0.5 / 3 ≈ 0.166667.

예시 2
입력:
kind = "binary_cross_entropy"
targets = [1.0, 0.0]
predictions = [0.9, 0.2]

예상 출력:
expected = 0.164252
입력:
std::string kind = "binary_cross_entropy";
std::vector<double> targets = {1.0, 0.0};
std::vector<double> predictions = {0.9, 0.2};

예상 출력:
double expected = 0.164252;
입력:
string kind = "binary_cross_entropy";
double[] targets = new double[] {1.0, 0.0};
double[] predictions = new double[] {0.9, 0.2};

예상 출력:
double expected = 0.164252;

설명

-(ln(0.9) + ln(1 - 0.2)) / 2 = -(-0.105361 - 0.223144) / 2 ≈ 0.164252. Confident correct predictions give a small loss.

참고 자료

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

다른 사람의 풀이 보기

커뮤니티 솔루션

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