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

构建金融预测训练测试集时遇ValueError:至少需一个数组输入

问题分析与修复方案

错误根源

你触发的ValueError是因为**train_test_split的调用方式完全错误**——这个函数必须先传入要拆分的特征数组X和目标数组y,再指定test_size、random_state这类可选参数。你现在只传了可选参数,没给核心的输入数组,函数自然报错说“至少需要一个输入数组”。

另外还有个隐藏坑:你提取的X是一维数组(比如形状是(n,)),而scikit-learn的所有模型都要求特征矩阵是二维的(比如(n,1)),后续训练时肯定会再报错,得一起处理。

修正后的完整代码

from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np

# 你的DataFrame构建代码保持不变
alldata = pd.DataFrame({'Date':date,
                        'S&P 500 Price':normalised_snp,
                        'S&P 500 Open': normalised_snpopen,
                        '10 Year Bond Price': normalised_tybp,
                        '10 Year Bond Open': normalised_tybpopen,
                        '2 Year Bond Price': normalised_twybp,
                        '2 Year Bond Open': normalised_twybpopen,
                        'US Inflation' : normalised_USInflation,
                        'US GDP' : normalised_USGDP,
                        'US Insterest' : normalised_USInterest,
                        'Global Inflation Rate' : normalised_GlobalInflation,
                        'Global GDP' : normalised_GlobalGDP})

# 修正X的形状:一维转二维,满足sklearn要求
X = alldata['S&P 500 Price'].to_numpy().reshape(-1, 1)
# y的提取逻辑不变
y = alldata.drop(columns=['Date','S&P 500 Price','10 Year Bond Open','2 Year Bond Open']).to_numpy()

# 正确调用train_test_split:先传X、y,再传其他参数
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

print(X_test.shape)
print(X_train.shape)

关键细节说明

  1. 参数顺序不能乱:train_test_split的必填输入是要拆分的数组,可选参数要放在后面,标准格式就是train_test_split(X, y, test_size=..., random_state=...)。
  2. 一维转二维的原因:scikit-learn的模型默认特征是“样本数×特征数”的二维结构,用reshape(-1,1)可以自动计算样本数,把单特征的一维数组转成符合要求的二维矩阵。
  3. 验证效果:运行后你可以打印X.shape,应该会输出类似(xxx, 1)的结果,这就说明特征格式没问题了。

内容的提问来源于stack exchange,提问作者samet.bnc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:15:39