Introduction
We check how well a model works to trust its decisions and improve it if needed.
Jump into concepts and practice - no test required
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Example: Calculate accuracy accuracy = accuracy_score(true_labels, predicted_labels) # Other metrics precision = precision_score(true_labels, predicted_labels, average='weighted') recall = recall_score(true_labels, predicted_labels, average='weighted') f1 = f1_score(true_labels, predicted_labels, average='weighted')
accuracy = accuracy_score([0,1,1,0], [0,1,0,0]) print(f"Accuracy: {accuracy}")
precision = precision_score([0,1,1,0], [0,1,0,0], average='weighted') print(f"Precision: {precision}")
recall = recall_score([0,1,1,0], [0,1,0,0], average='weighted') f1 = f1_score([0,1,1,0], [0,1,0,0], average='weighted') print(f"Recall: {recall}, F1 Score: {f1}")
from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Load sample image data (digits) digits = load_digits() X = digits.images.reshape((len(digits.images), -1)) y = digits.target # Split data into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train a simple model model = RandomForestClassifier(random_state=42) model.fit(X_train, y_train) # Predict on test data predictions = model.predict(X_test) # Evaluate model accuracy = accuracy_score(y_test, predictions) precision = precision_score(y_test, predictions, average='weighted') recall = recall_score(y_test, predictions, average='weighted') f1 = f1_score(y_test, predictions, average='weighted') print(f"Accuracy: {accuracy:.3f}") print(f"Precision: {precision:.3f}") print(f"Recall: {recall:.3f}") print(f"F1 Score: {f1:.3f}")
train_test_split with parameters like test_size and random_state.from sklearn.metrics import accuracy_score
true_labels = [1, 0, 1, 1, 0]
pred_labels = [1, 0, 0, 1, 0]
accuracy = accuracy_score(true_labels, pred_labels)
print("{:.2f}".format(round(accuracy, 2)))