非负最小平方#

在这个例子中,我们对回归系数进行正约束的线性模型,并将估计的系数与经典线性回归进行比较。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt
import numpy as np

from sklearn.metrics import r2_score

生成一些随机数据

np.random.seed(42)

n_samples, n_features = 200, 50
X = np.random.randn(n_samples, n_features)
true_coef = 3 * np.random.randn(n_features)
# Threshold coefficients to render them non-negative
true_coef[true_coef < 0] = 0
y = np.dot(X, true_coef)

# Add some noise
y += 5 * np.random.normal(size=(n_samples,))

将数据拆分为火车集和测试集

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)

拟合非负最小二乘。

from sklearn.linear_model import LinearRegression

reg_nnls = LinearRegression(positive=True)
y_pred_nnls = reg_nnls.fit(X_train, y_train).predict(X_test)
r2_score_nnls = r2_score(y_test, y_pred_nnls)
print("NNLS R2 score", r2_score_nnls)
NNLS R2 score 0.8225220806196525

适合OLS。

reg_ols = LinearRegression()
y_pred_ols = reg_ols.fit(X_train, y_train).predict(X_test)
r2_score_ols = r2_score(y_test, y_pred_ols)
print("OLS R2 score", r2_score_ols)
OLS R2 score 0.7436926291700353

比较OLS和NNLS之间的回归系数,我们可以观察到它们高度相关(虚线是同一关系),但非负约束收缩一些至0。非负最小平方本质上会产生稀疏结果。

fig, ax = plt.subplots()
ax.plot(reg_ols.coef_, reg_nnls.coef_, linewidth=0, marker=".")

low_x, high_x = ax.get_xlim()
low_y, high_y = ax.get_ylim()
low = max(low_x, low_y)
high = min(high_x, high_y)
ax.plot([low, high], [low, high], ls="--", c=".3", alpha=0.5)
ax.set_xlabel("OLS regression coefficients", fontweight="bold")
ax.set_ylabel("NNLS regression coefficients", fontweight="bold")
plot nnls
Text(55.847222222222214, 0.5, 'NNLS regression coefficients')

Total running time of the script: (0 minutes 0.045 seconds)

相关实例

普通最小二乘和岭回归

Ordinary Least Squares and Ridge Regression

逻辑函数

Logistic function

模型正规化对训练和测试误差的影响

Effect of model regularization on training and test error

机器学习无法推断因果效应

Failure of Machine Learning to infer causal effects

Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io> _