You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用LassoCV指定单个alpha值时触发AxisError问题求助

问题:LassoCV传入单个alpha值触发AxisError错误

背景

尝试用LassoCV训练模型,第一段代码可正常运行并得到最优alpha值,但传入该单个alpha值构建新模型时触发AxisError。

可正常运行的代码

from numpy import arange
from sklearn.linear_model import LassoCV
from sklearn.model_selection import RepeatedKFold
# 定义模型评估方法
cv = RepeatedKFold(n_splits=10, n_repeats=5, random_state=1)
# 定义模型
model = LassoCV(alphas=arange(0, 1, 0.01), cv=cv)
# 拟合模型
model.fit(X_train, y_train)
# 输出最优配置
print('alpha: %f' % model.alpha_)  # 返回最优值0.78
y_pred = model.predict(X_test)

报错代码及错误信息

运行以下代码时触发错误:

# 定义模型
model_new = LassoCV(alphas=0.78)
# 拟合模型
model_new.fit(X_train,pd.DataFrame(y_train))  # 也尝试直接传入X_train和y_train,仍无法运行

错误回溯:

AxisError                                 Traceback (most recent call last) Input In [136], in <cell line: 4>()
      2 model_new = LassoCV(alphas=0.78)
      3 # 拟合模型
----> 4 model_new.fit(X_train,pd.DataFrame(y_train))

File ~\Anaconda3\lib\site-packages\sklearn\linear_model\_coordinate_descent.py:1687, in LinearModelCV.fit(self, X, y, sample_weight)    1685             check_scalar_alpha(alpha, f"alphas[{index}]")    1686     # 确保alphas顺序正确
-> 1687     alphas = np.tile(np.sort(alphas)[::-1], (n_l1_ratio, 1))    1689 # 我们希望n_alphas是每个l1_ratio使用的alpha数量    1690 n_alphas = len(alphas[0])

File <__array_function__ internals>:5, in sort(*args, **kwargs)

File ~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py:998, in sort(a, axis, kind, order)
    996 else:
    997     a = asanyarray(a).copy(order="K")
-> 998 a.sort(axis=axis, kind=kind, order=order)
    999 return a

AxisError: axis -1 is out of bounds for array of dimension 0

数据形状

X_train和y_train的初始形状:
X_train和y_train形状

更新后的形状信息:
更新后的形状信息

解决方法

问题出在LassoCV的alphas参数要求传入数组/列表形式的alpha值集合,而非单个标量。即便只想用单个最优alpha,也要把它放进列表或数组里。

修改后的代码:

# 定义模型,将单个alpha值放入列表
model_new = LassoCV(alphas=[0.78])
# 拟合模型,直接传入y_train即可(无需转DataFrame)
model_new.fit(X_train, y_train)

另外,若只是想使用最优alpha值训练一个普通的Lasso模型,更推荐直接用Lasso类而非LassoCV,避免不必要的交叉验证计算:

from sklearn.linear_model import Lasso
model_new = Lasso(alpha=0.78)
model_new.fit(X_train, y_train)

内容的提问来源于stack exchange,提问作者The Great

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:15:32