scikit-learn/examples/linear_model/plot_bayesian_ridge.py

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

136 lines
3.9 KiB
Python
Raw Normal View History

"""
=========================
Bayesian Ridge Regression
=========================
Computes a Bayesian Ridge Regression on a synthetic dataset.
See :ref:`bayesian_ridge_regression` for more information on the regressor.
Compared to the OLS (ordinary least squares) estimator, the coefficient
weights are slightly shifted toward zeros, which stabilises them.
As the prior on the weights is a Gaussian prior, the histogram of the
estimated weights is Gaussian.
The estimation of the model is done by iteratively maximizing the
marginal log-likelihood of the observations.
We also plot predictions and uncertainties for Bayesian Ridge Regression
for one dimensional regression using polynomial feature expansion.
Note the uncertainty starts going up on the right side of the plot.
This is because these test samples are outside of the range of the training
samples.
"""
# %%
# Generate simulated data with Gaussian weights
# ---------------------------------------------
import numpy as np
from scipy import stats
np.random.seed(0)
n_samples, n_features = 100, 100
X = np.random.randn(n_samples, n_features) # Create Gaussian data
2015-12-08 02:13:40 +08:00
# Create weights with a precision lambda_ of 4.
lambda_ = 4.0
w = np.zeros(n_features)
# Only keep 10 weights of interest
relevant_features = np.random.randint(0, n_features, 10)
for i in relevant_features:
2011-12-20 22:34:17 +08:00
w[i] = stats.norm.rvs(loc=0, scale=1.0 / np.sqrt(lambda_))
# Create noise with a precision alpha of 50.
alpha_ = 50.0
2011-12-20 22:34:17 +08:00
noise = stats.norm.rvs(loc=0, scale=1.0 / np.sqrt(alpha_), size=n_samples)
# Create the target
2010-09-29 22:26:24 +08:00
y = np.dot(X, w) + noise
# %%
# Fit the Bayesian Ridge Regression and an OLS for comparison
# -----------------------------------------------------------
from sklearn.linear_model import BayesianRidge, LinearRegression
clf = BayesianRidge(compute_score=True)
2010-09-29 22:26:24 +08:00
clf.fit(X, y)
ols = LinearRegression()
ols.fit(X, y)
# %%
# Plot true weights and estimated weights
# ---------------------------------------
import matplotlib.pyplot as plt
2015-10-22 20:12:06 +08:00
lw = 2
plt.figure(figsize=(6, 5))
plt.title("Weights of the model")
2015-10-22 20:12:06 +08:00
plt.plot(clf.coef_, color="lightgreen", linewidth=lw, label="Bayesian Ridge estimate")
plt.plot(w, color="gold", linewidth=lw, label="Ground truth")
plt.plot(ols.coef_, color="navy", linestyle="--", label="OLS estimate")
plt.xlabel("Features")
plt.ylabel("Values of the weights")
_ = plt.legend(loc="best", prop=dict(size=12))
# %%
# Plot histogram of the weights
# -----------------------------
plt.figure(figsize=(6, 5))
plt.title("Histogram of the weights")
[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.hist(clf.coef_, bins=n_features, color="gold", log=True, edgecolor="black")
2018-07-23 15:49:01 +08:00
plt.scatter(
clf.coef_[relevant_features],
np.full(len(relevant_features), 5.0),
color="navy",
label="Relevant features",
)
plt.ylabel("Features")
plt.xlabel("Values of the weights")
_ = plt.legend(loc="upper left")
# %%
# Plot marginal log-likelihood
# ----------------------------
plt.figure(figsize=(6, 5))
plt.title("Marginal log-likelihood")
2015-10-22 20:12:06 +08:00
plt.plot(clf.scores_, color="navy", linewidth=lw)
plt.ylabel("Score")
_ = plt.xlabel("Iterations")
# %%
# Plot some predictions for polynomial regression with standard deviations
# ------------------------------------------------------------------------
def f(x, noise_amount):
y = np.sqrt(x) * np.sin(x)
noise = np.random.normal(0, 1, len(x))
return y + noise_amount * noise
degree = 10
X = np.linspace(0, 10, 100)
y = f(X, noise_amount=0.1)
clf_poly = BayesianRidge()
clf_poly.fit(np.vander(X, degree), y)
X_plot = np.linspace(0, 11, 25)
y_plot = f(X_plot, noise_amount=0)
y_mean, y_std = clf_poly.predict(np.vander(X_plot, degree), return_std=True)
plt.figure(figsize=(6, 5))
plt.errorbar(
X_plot,
y_mean,
y_std,
color="navy",
label="Polynomial Bayesian Ridge Regression",
linewidth=lw,
)
plt.plot(X_plot, y_plot, color="gold", linewidth=lw, label="Ground Truth")
plt.ylabel("Output y")
plt.xlabel("Feature X")
_ = plt.legend(loc="lower left")