备注
Go to the end 下载完整的示例代码。或者通过浏览器中的MysterLite或Binder运行此示例
L1-逻辑回归的正规化路径#
针对源自Iris数据集的二元分类问题训练l1惩罚逻辑回归模型。
模型的顺序从最强的正规化到最低的正规化。收集模型的4个系数并绘制为“正规化路径”:在图的左侧(强正规化器),所有系数都恰好为0。当正规化变得越来越宽松时,系数可以一个接一个地获得非零值。
在这里,我们选择自由线性求解器,因为它可以有效地优化具有非光滑、稀疏性导致l1罚分的逻辑回归损失。
另请注意,我们为容差设置了一个较低的值,以确保模型在收集系数之前已经收敛。
我们还使用warm_start=True,这意味着模型的系数被重用以初始化下一个模型拟合,以加速全路径的计算。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
加载数据#
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
这里我们删除第三类,使问题成为二元分类
X = X[y != 2]
y = y[y != 2]
计算正规化路径#
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import l1_min_c
cs = l1_min_c(X, y, loss="log") * np.logspace(0, 1, 16)
创建管道, StandardScaler
和 LogisticRegression
,在匹配线性模型之前对数据进行规格化,以加速收敛并使系数具有可比性。此外,作为一个副作用,由于数据现在以0为中心,因此我们不需要适应截取。
clf = make_pipeline(
StandardScaler(),
LogisticRegression(
penalty="l1",
solver="liblinear",
tol=1e-6,
max_iter=int(1e6),
warm_start=True,
fit_intercept=False,
),
)
coefs_ = []
for c in cs:
clf.set_params(logisticregression__C=c)
clf.fit(X, y)
coefs_.append(clf["logisticregression"].coef_.ravel().copy())
coefs_ = np.array(coefs_)
情节规则化路径#
import matplotlib.pyplot as plt
# Colorblind-friendly palette (IBM Color Blind Safe palette)
colors = ["#648FFF", "#785EF0", "#DC267F", "#FE6100"]
plt.figure(figsize=(10, 6))
for i in range(coefs_.shape[1]):
plt.semilogx(cs, coefs_[:, i], marker="o", color=colors[i], label=feature_names[i])
ymin, ymax = plt.ylim()
plt.xlabel("C")
plt.ylabel("Coefficients")
plt.title("Logistic Regression Path")
plt.legend()
plt.axis("tight")
plt.show()

Total running time of the script: (0分0.118秒)
相关实例
Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>
_