备注
Go to the end 下载完整的示例代码。或者通过浏览器中的MysterLite或Binder运行此示例
密集和稀疏数据上的套索#
我们表明,linear_mode.Lasso为密集和稀疏数据提供了相同的结果,并且在稀疏数据的情况下,速度得到了提高。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
from time import time
from scipy import linalg, sparse
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso
比较密集数据上的两种Lasso实现#
我们创建了一个适合Lasso的线性回归问题,也就是说,特征多于样本。然后我们以密集(通常)和稀疏格式存储数据矩阵,并在每种格式上训练Lasso。我们计算两者的运行时间,并通过计算他们学习的系数之间的差的欧几里得规范来检查他们是否学习了相同的模型。由于数据很密集,因此我们期望使用密集数据格式获得更好的运行时间。
X, y = make_regression(n_samples=200, n_features=5000, random_state=0)
# create a copy of X in sparse format
X_sp = sparse.coo_matrix(X)
alpha = 1
sparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000)
dense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000)
t0 = time()
sparse_lasso.fit(X_sp, y)
print(f"Sparse Lasso done in {(time() - t0):.3f}s")
t0 = time()
dense_lasso.fit(X, y)
print(f"Dense Lasso done in {(time() - t0):.3f}s")
# compare the regression coefficients
coeff_diff = linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)
print(f"Distance between coefficients : {coeff_diff:.2e}")
#
Sparse Lasso done in 0.095s
Dense Lasso done in 0.031s
Distance between coefficients : 8.19e-14
比较Sparse数据上的两个Lasso实现#
我们通过将所有小值替换为0并运行与上面相同的比较来使前面的问题稀疏。因为数据现在是稀疏的,所以我们希望使用稀疏数据格式的实现更快。
# make a copy of the previous data
Xs = X.copy()
# make Xs sparse by replacing the values lower than 2.5 with 0s
Xs[Xs < 2.5] = 0.0
# create a copy of Xs in sparse format
Xs_sp = sparse.coo_matrix(Xs)
Xs_sp = Xs_sp.tocsc()
# compute the proportion of non-zero coefficient in the data matrix
print(f"Matrix density : {(Xs_sp.nnz / float(X.size) * 100):.3f}%")
alpha = 0.1
sparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000)
dense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000)
t0 = time()
sparse_lasso.fit(Xs_sp, y)
print(f"Sparse Lasso done in {(time() - t0):.3f}s")
t0 = time()
dense_lasso.fit(Xs, y)
print(f"Dense Lasso done in {(time() - t0):.3f}s")
# compare the regression coefficients
coeff_diff = linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)
print(f"Distance between coefficients : {coeff_diff:.2e}")
Matrix density : 0.626%
Sparse Lasso done in 0.138s
Dense Lasso done in 0.635s
Distance between coefficients : 8.90e-12
Total running time of the script: (0分0.962秒)
相关实例
Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>
_