scikit-learn/examples/model_selection/plot_underfitting_overfitti...

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

83 lines
2.7 KiB
Python
Raw Permalink Normal View History

2014-01-24 06:16:05 +08:00
"""
============================
Underfitting vs. Overfitting
============================
2014-01-24 06:16:05 +08:00
This example demonstrates the problems of underfitting and overfitting and
how we can use linear regression with polynomial features to approximate
nonlinear functions. The plot shows the function that we want to approximate,
which is a part of the cosine function. In addition, the samples from the
real function and the approximations of different models are displayed. The
models have polynomial features of different degrees. We can see that a
linear function (polynomial with degree 1) is not sufficient to fit the
training samples. This is called **underfitting**. A polynomial of degree 4
approximates the true function almost perfectly. However, for higher degrees
the model will **overfit** the training data, i.e. it learns the noise of the
training data.
2015-01-16 04:09:35 +08:00
We evaluate quantitatively **overfitting** / **underfitting** by using
2014-11-29 22:14:12 +08:00
cross-validation. We calculate the mean squared error (MSE) on the validation
set, the higher, the less likely the model generalizes correctly from the
training data.
"""
2014-01-24 06:16:05 +08:00
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
2014-01-24 06:16:05 +08:00
import matplotlib.pyplot as plt
import numpy as np
2023-06-21 23:50:07 +08:00
2014-01-24 06:16:05 +08:00
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
2014-01-24 06:16:05 +08:00
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
[MRG + 1] 18 more examples with matplotlib 2.0 updates (#8983) * updated plot_label_propagation_versus_svm_iris.py plot * updated svm/plot_weighted_samples.py plot * made semi_supervised/plot_label_propagation_versus_svm_iris.py pep8 compliant * modified tree/plot_tree_regression.py [size and edgecolor] * updated tree/plot_tree_regression_multioutput.py [size+color] * fixed examples/semi_supervised/plot_label_propagation_versus_svm_iris.py for backward compatibility * neural_networks/plot_mlp_alpha.py - matplotlib2 update * examples/neural_networks/plot_mlp_alpha.py - pep8 fix * examples/neighbors/plot_nearest_centroid.py - matplotlib2.0 + pep8 fix * neighbors/plot_classification.py - matplotlib2.0 + pep8 fix * examples/neighbors/plot_lof.py - matplotlib2.0 update * examples/model_selection/plot_underfitting_overfitting.py - matplotlib2.0 + pep8 * examples/mixture/plot_concentration_prior.py - matplotlib2.0 + pep8 * examples/linear_model/plot_logistic_multinomial.py - matplotlib2.0 update * linear_model/plot_sgd_iris.py - matplotlib2.0 + pep8 fix * examples/linear_model/plot_sgd_weighted_samples.py - matplotlib2.0 + pep8 * examples/linear_model/plot_sgd_separating_hyperplane.py - matplotlib2.0 update * examples/feature_selection/plot_permutation_test_for_classification.py - matplotlib + pe8 * examples/linear_model/plot_bayesian_ridge.py - matplotlib2.0 update * examples/feature_selection/plot_feature_selection.py - matplotlib2.0 update * examples/feature_selection/plot_f_test_vs_mi.py - matplotlib2.0 + pep8 * examples/feature_selection/plot_f_test_vs_mi.py - matplotlib2.0+ pep8 fix * examples/model_selection/plot_underfitting_overfitting.py - error fixed * blue -> black edgecolor fix for 2 examples
2017-06-07 19:23:12 +08:00
def true_fun(X):
return np.cos(1.5 * np.pi * X)
2014-01-24 06:16:05 +08:00
np.random.seed(0)
n_samples = 30
degrees = [1, 4, 15]
X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1
plt.figure(figsize=(14, 5))
2014-01-24 06:16:05 +08:00
for i in range(len(degrees)):
2015-01-16 04:09:35 +08:00
ax = plt.subplot(1, len(degrees), i + 1)
2014-01-24 06:16:05 +08:00
plt.setp(ax, xticks=(), yticks=())
polynomial_features = PolynomialFeatures(degree=degrees[i], include_bias=False)
linear_regression = LinearRegression()
pipeline = Pipeline(
[
2014-01-24 06:16:05 +08:00
("polynomial_features", polynomial_features),
("linear_regression", linear_regression),
]
2014-01-24 06:16:05 +08:00
)
pipeline.fit(X[:, np.newaxis], y)
2014-11-29 22:14:12 +08:00
# Evaluate the models using crossvalidation
scores = cross_val_score(
2016-09-06 17:25:11 +08:00
pipeline, X[:, np.newaxis], y, scoring="neg_mean_squared_error", cv=10
)
2014-11-29 22:14:12 +08:00
2014-01-24 06:16:05 +08:00
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
[MRG + 1] 18 more examples with matplotlib 2.0 updates (#8983) * updated plot_label_propagation_versus_svm_iris.py plot * updated svm/plot_weighted_samples.py plot * made semi_supervised/plot_label_propagation_versus_svm_iris.py pep8 compliant * modified tree/plot_tree_regression.py [size and edgecolor] * updated tree/plot_tree_regression_multioutput.py [size+color] * fixed examples/semi_supervised/plot_label_propagation_versus_svm_iris.py for backward compatibility * neural_networks/plot_mlp_alpha.py - matplotlib2 update * examples/neural_networks/plot_mlp_alpha.py - pep8 fix * examples/neighbors/plot_nearest_centroid.py - matplotlib2.0 + pep8 fix * neighbors/plot_classification.py - matplotlib2.0 + pep8 fix * examples/neighbors/plot_lof.py - matplotlib2.0 update * examples/model_selection/plot_underfitting_overfitting.py - matplotlib2.0 + pep8 * examples/mixture/plot_concentration_prior.py - matplotlib2.0 + pep8 * examples/linear_model/plot_logistic_multinomial.py - matplotlib2.0 update * linear_model/plot_sgd_iris.py - matplotlib2.0 + pep8 fix * examples/linear_model/plot_sgd_weighted_samples.py - matplotlib2.0 + pep8 * examples/linear_model/plot_sgd_separating_hyperplane.py - matplotlib2.0 update * examples/feature_selection/plot_permutation_test_for_classification.py - matplotlib + pe8 * examples/linear_model/plot_bayesian_ridge.py - matplotlib2.0 update * examples/feature_selection/plot_feature_selection.py - matplotlib2.0 update * examples/feature_selection/plot_f_test_vs_mi.py - matplotlib2.0 + pep8 * examples/feature_selection/plot_f_test_vs_mi.py - matplotlib2.0+ pep8 fix * examples/model_selection/plot_underfitting_overfitting.py - error fixed * blue -> black edgecolor fix for 2 examples
2017-06-07 19:23:12 +08:00
plt.scatter(X, y, edgecolor="b", s=20, label="Samples")
2014-01-24 06:16:05 +08:00
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc="best")
2014-11-29 22:14:12 +08:00
plt.title(
"Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
degrees[i], -scores.mean(), scores.std()
)
)
2014-01-24 06:16:05 +08:00
plt.show()