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

如何获取scikit-learn交叉验证的X、Y得分及误差数组?

如何在k折交叉验证中获取线性回归的误差数组用于t检验

嘿,我来帮你搞定这个问题!你现在需要结合scikit-learn的线性回归和k折交叉验证,同时收集每次折的误差(y_test - y_pred)来做t检验对吧?下面是完整的实现步骤和代码,我会一步步给你解释清楚:

第一步:导入必要的库

首先得把需要用到的工具库都导入进来,包括数据处理、模型和交叉验证的模块:

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
import numpy as np

第二步:加载并预处理数据

这部分我帮你补全了没写完的reshape代码,确保数据格式符合模型要求:

# 加载数据集
smartphone = pd.read_csv('all-users_w4_filtered.csv')
# 定义自变量(X)和因变量(Y)
x = smartphone[['mood_mean', 'valence_mean', 'app.social_mean', 'app.other_mean']].values
y = smartphone['target'].values
z = smartphone['benchmark'].values  # 保留你定义的benchmark变量

# 重塑数据:把y转成二维数组,和模型输出的维度匹配
x = x.reshape(-1, 4)
y = y.reshape(-1, 1)

第三步:k折交叉验证+收集误差

这是核心部分,我们会遍历每个交叉验证折,训练模型、预测,然后把每一次的误差都收集起来:

# 设置k折交叉验证(这里用5折,你可以根据需求调整n_splits)
kf = KFold(n_splits=5, shuffle=True, random_state=42)  # 开启shuffle让数据划分更随机可靠
all_errors = []  # 用来存储所有折的误差

for train_idx, test_idx in kf.split(x):
    # 划分当前折的训练集和测试集
    X_train, X_test = x[train_idx], x[test_idx]
    y_train, y_test = y[train_idx], y[test_idx]
    
    # 初始化并训练线性回归模型
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 对测试集进行预测
    y_pred = model.predict(X_test)
    
    # 计算误差(真实值 - 预测值),并添加到总误差列表
    errors = y_test - y_pred
    all_errors.extend(errors.flatten())  # flatten把二维数组转成一维,方便后续统一处理

# 把所有误差转成numpy数组,方便后续做t检验
all_errors = np.array(all_errors)

第四步:用误差数组做t检验

拿到完整的误差数组后,你就可以进行t检验了。比如常见的单样本t检验(检验误差的均值是否显著不为0),可以用scipy的统计模块实现:

from scipy.stats import ttest_1samp

# 检验误差均值是否显著不等于0
t_statistic, p_value = ttest_1samp(all_errors, 0)
print(f"t统计量: {round(t_statistic, 4)}, p值: {round(p_value, 4)}")

小提示

  • shuffle=True和random_state的设置是为了让交叉验证的划分可重复,避免因为数据顺序导致的偏差,如果你不需要可重复性,可以去掉random_state
  • 如果你需要的是每个折单独的误差数组,而不是合并成一个大数组,可以把all_errors改成二维列表,比如all_errors.append(errors.flatten())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:00:13