Sklearn 模型系数并预测 linear_model 中的不匹配

Sklearn model coefficients and predict mismatch in linear_model

我对 ML 和 sklearn 比较陌生,我正在尝试使用 linear_model.Lasso 为具有 6 个不同特征的输入数据训练线性模型 具有不同的正则化参数值。鉴于 Xy 是我的输入参数模型,我不明白为什么我通过执行这两个表达式不断得到不同的值:

sum(model.coef_*X[0])
Out[94]: -0.4895022980752311

model.predict(X[0])
Out[95]: array([ 2.08767122])

理想情况下,我希望模型系数对应于数据集中的给定特征,并且两个表达式将 return 完全相同的值。

这是代码示例:

input_file = 'Spud_startup_analysis.xlsx'
data_input_generic = pd.read_excel(input_file, skiprows = 0, sheetname='DataSet')
data = data_input_generic.as_matrix()
X = data[:, 0:-1]
y = data[:,-1]
model = linear_model.Lasso(alpha = 0.1)
model.fit(X, y)

是否与输入矩阵的维度有关? 提前致谢

您缺少截距项,它是优化的一部分 by default (fit_intercept)。

class sklearn.linear_model.Lasso(alpha=1.0, fit_intercept=True, normalize=False,
    precompute=False, copy_X=True, max_iter=1000, tol=0.0001, warm_start=False,
    positive=False, random_state=None, selection=’cyclic’)[source]

fit_intercept : boolean

whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered).

适配后model.intercept_即可抢到

在内部,预测 does

return safe_sparse_dot(X, self.coef_.T,
                       dense_output=True) + self.intercept_