Introduction
The bias-variance tradeoff helps us understand how to make a model that learns well from data without making too many mistakes or being too simple.
No specific code syntax; it's a concept about balancing two types of errors:
- Bias: Error from too simple a model.
- Variance: Error from too complex a model.Low bias, high variance: A very deep decision tree that fits training data perfectly but fails on new data.
High bias, low variance: A simple linear model that cannot capture curves in data.Balanced bias and variance: A model with moderate complexity that fits training data well and predicts new data accurately.
from sklearn.datasets import make_regression from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error # Create sample data X, y = make_regression(n_samples=100, n_features=1, noise=10, random_state=42) # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train simple model (high bias) simple_model = DecisionTreeRegressor(max_depth=1, random_state=42) simple_model.fit(X_train, y_train) y_pred_simple = simple_model.predict(X_test) simple_mse = mean_squared_error(y_test, y_pred_simple) # Train complex model (high variance) complex_model = DecisionTreeRegressor(max_depth=20, random_state=42) complex_model.fit(X_train, y_train) y_pred_complex = complex_model.predict(X_test) complex_mse = mean_squared_error(y_test, y_pred_complex) print(f"Simple model MSE (high bias): {simple_mse:.2f}") print(f"Complex model MSE (high variance): {complex_mse:.2f}")
import numpy as np np.random.seed(0) true_pattern = 5 model_predictions = [4, 5, 6, 7, 8] noise = np.random.normal(0, 1, 5) errors = [(pred - true_pattern + n) ** 2 for pred, n in zip(model_predictions, noise)] print(round(np.mean(errors), 2))
import numpy as np
np.random.seed(1)
true_value = 10
predictions = [true_value + np.random.normal(0, 5) for _ in range(5)]
bias = np.mean(predictions) - true_value
variance = np.var(predictions)
print(f"Bias: {bias:.2f}, Variance: {variance:.2f}")Pass the test and this pattern moves unknown