Common Metrics
easy· Machine Learningruns: 0Implement the common regression and classification metrics used to evaluate models: mean squared error, mean absolute error, r-squared, accuracy, and precision/recall/F1 for binary classification.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 818
import numpy as np
def mse(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)
def mae(y_true, y_pred):
return np.mean(np.abs(y_true - y_pred))
def r2_score(y_true, y_pred):
ss_res = np.sum((y_true - y_pred) ** 2)
ss_tot = np.sum((y_true - np.mean(y_true)) ** 2)
return 1 - ss_res / ss_tot
def accuracy(y_true, y_pred):
return np.mean(y_true == y_pred)
def precision_recall_f1(y_true, y_pred):
tp = np.sum((y_true == 1) & (y_pred == 1))
fp = np.sum((y_true == 0) & (y_pred == 1))
fn = np.sum((y_true == 1) & (y_pred == 0))
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if precision + recall
else 0.0
)
return precision, recall, f1
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.