fht算法c语言源码,sklearn中LinearRegression使用及源码解读

###sklearn中的LinearRegression

函数原型:class sklearn.linear_model.LinearRegression(fit_intercept=True,normalize=False,copy_X=True,n_jobs=1)

fit_intercept:模型是否存在截距

normalize:模型是否对数据进行标准化(在回归之前,对X减去平均值再除以二范数),如果fit_intercept被设置为False时,该参数将忽略。

该函数有属性:coef_可供查看模型训练后得到的估计系数,如果获取的估计系数太大,说明模型有可能过拟合。

使用样例: >>>from sklearn import linear_model

>>>clf = linear_model.LinearRegression()

X = [[0,0],[1,1],[2,2]]

y = [0,1,2]

>>>clf.fit(X,y)

>>>print(clf.coef_)

[ 0.5 0.5]

>>>print(clf.intercept_)

1.11022302463e-16

###源码分析 在github可以找到LinearRegression的源码:LinearRegression

主要思想:sklearn.linear_model.LinearRegression求解线性回归方程参数时,首先判断训练集X是否是稀疏矩阵,如果是,就用Golub&Kanlan双对角线化过程方法来求解;否则调用C库中LAPACK中的用基于分治法的奇异值分解来求解。在sklearn中并不是使用梯度下降法求解线性回归,而是使用最小二乘法求解。 sklearn.LinearRegression的fit()方法: if sp.issparse(X):#如果X是稀疏矩阵

if y.ndim < 2:

out = sparse_lsqr(X, y)

self.coef_ = out[0]

self._residues = out[3]

else:

# sparse_lstsq cannot handle y with shape (M, K)

outs = Parallel(n_jobs=n_jobs_)(

delayed(sparse_lsqr)(X, y[:, j].ravel())

for j in range(y.shape[1]))

self.coef_ = np.vstack(out[0] for out in outs)

self._residues = np.vstack(out[3] for out in outs)

else:

self.coef_, self._residues, self.rank_, self.singular_ = \

linalg.lstsq(X, y)

self.coef_ = self.coef_.T

几个有趣的点:

如果y的维度小于2,并没有并行操作。

如果训练集X是稀疏矩阵,就用sparse_lsqr()求解,否则使用linalg.lstsq()

###linalg.lstsq() scipy.linalg.lstsq()方法就是用来计算X为非稀疏矩阵时的模型系数。这是使用普通的最小二乘OLS法来求解线性回归参数的。

scipy.linalg.lstsq()方法源码 scipy提供了三种方法来求解least-squres problem最小均方问题,即模型优化目标。其提供了三个选项gelsd,gelsy,geless,这些参数传入了get_lapack_funcs()。这三个参数实际上是C函数名,函数是从LAPACK(Linear Algebra PACKage)中获得的。

gelsd:它是用singular value decomposition of A and a divide and conquer method方法来求解线性回归方程参数的。 gelsy:computes the minimum-norm solution to a real/complex linear least squares problem gelss:Computes the minimum-norm solution to a linear least squares problem using the singular value decomposition of A.

scipy.linalg.lstsq()方法使用gelsd求解(并没有为用户提供选项)。

###sparse_lsqr()方法源码 sqarse_lsqr()方法用来计算X是稀疏矩阵时的模型系数。sparse_lsqr()就是不同版本的scipy.sparse.linalg.lsqr(),参考自论文C. C. Paige and M. A. Saunders (1982a). "LSQR: An algorithm for sparse linear equations and sparse least squares", ACM TOMS实现。 相关源码如下:

if sp_version < (0, 15):

# Backport fix for scikit-learn/scikit-learn#2986 / scipy/scipy#4142

from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr

else:

from scipy.sparse.linalg import lsqr as sparse_lsqr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值