Python ML The Bias-Variance Tradeoff
Bias is the error from a model that is too simple to catch the pattern. Variance is the error from a model that changes too much with the training rows.
A shallow tree has high bias
At depth 1, the training error is 0.079 and the test error is 0.105. Both errors are high, so the tree misses the pattern.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=1, random_state=42)
tree.fit(X_train, y_train)
print(round(1 - tree.score(X_train, y_train), 3))
print(round(1 - tree.score(X_test, y_test), 3))A deep tree has high variance
At depth 8, the training error falls to 0.0. The test error stops falling, so the extra depth only memorises.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=8, random_state=42)
tree.fit(X_train, y_train)
print(round(1 - tree.score(X_train, y_train), 3))
print(round(1 - tree.score(X_test, y_test), 3))Draw the two curves
plt.plot() draws the train error and the test error against depth. savefig() writes the picture to a file.
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
depths = [1, 3, 8]
train_errors = [0.079, 0.022, 0.0]
test_errors = [0.105, 0.053, 0.053]
plt.plot(depths, train_errors, marker='o', label='Train error')
plt.plot(depths, test_errors, marker='o', label='Test error')
plt.xlabel('Tree depth')
plt.ylabel('Error')
plt.legend()
plt.savefig('bias_variance.png')Example
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
depths = [1, 3, 8]
train_errors = []
test_errors = []
for depth in depths:
tree = DecisionTreeClassifier(max_depth=depth, random_state=42)
tree.fit(X_train, y_train)
train_errors.append(round(1 - tree.score(X_train, y_train), 3))
test_errors.append(round(1 - tree.score(X_test, y_test), 3))
print("Depths:", depths)
print("Train errors:", train_errors)
print("Test errors:", test_errors)
plt.plot(depths, train_errors, marker="o", label="Train error")
plt.plot(depths, test_errors, marker="o", label="Test error")
plt.xlabel("Tree depth")
plt.ylabel("Error")
plt.legend()
plt.savefig("bias_variance.png")
print("Figure saved: bias_variance.png")Key points
- Bias: the error from a model that is too simple for the pattern
- Variance: the error from a model that swings with the training rows
- Tradeoff: making one error smaller often makes the other bigger
- A shallow tree has high bias and low variance
- A deep tree has low bias and high variance
- The best depth sits in the middle, where the test error is lowest
- Use error as 1 minus accuracy to plot both curves on one picture
In this example, the same breast cancer measurements are used, with benign or malignant as the label. Testing uses the 20 percent of rows the split set aside. Trees of depth 1, 3, and 8 are fitted, and error is 1 minus accuracy for each. The training errors are 0.079, 0.022, and 0.0, while the test errors are 0.105, 0.053, and 0.053. The training error keeps falling with depth, and the test error stops falling after depth 3. The picture saves as bias_variance.png, and the numbers behind it are printed above.
Note
The tradeoff is a shape to read, not a number to memorise.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens as a decision tree gets deeper?