समस्या
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)
उदाहरण
इनपुट:
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.
इनपुट:
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.
कैसे हल करें
पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।
संकेत 1
Each loss compares predictions to targets element by element and then averages the per-example errors.
संकेत 2
For cross-entropy, clamp predictions away from 0 and 1 before taking logarithms.
संकेत 3
Remember that absolute value and squaring are different, and cross-entropy uses the target as a weight on each log term.
अपेक्षित जटिलता
O(n) time, O(1) extra space
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।