Skip to main content
 首页 » 编程设计

python之机器学习之使用 sklearn

2025年05月04日21dyllove98

我正在编写一段基本的股票预测代码,但我不断收到以下错误。

AttributeError: 'function' object has no attribute 'train_test_split'

除此之外,我的代码似乎都是正确的,并且在编码过程中已经运行测试。所以我很确定除了 python 的库问题之外没有其他问题导致这个问题。有谁知道这个问题的解决方法,以便项目可以继续进行?如果有帮助的话,这是我的代码。

import quandl, math 
import numpy as np 
import pandas as pd 
from sklearn import preprocessing, svm 
from sklearn.model_selection import cross_validate 
from sklearn.linear_model import LinearRegression 
 
#Getting the data 
df = quandl.get("WIKI/GOOGL") 
 
#Selecting the data we want from the database 
df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']] 
 
#Calculating percentage changes 
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100 
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100 
 
#Refining the data even further 
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]  
 
forecast_col = 'Adj. Close' 
df.fillna(value=-99999, inplace=True) 
forecast_out = int(math.ceil(0.01 * len(df))) 
 
df['label'] = df[forecast_col].shift(-forecast_out) 
 
 
x = np.array(df.drop(['label'],1)) 
y = np.array(df['label']) 
x  = preprocessing.scale(x) 
y = np.array(df['label']) 
 
X_train, X_test, y_train, y_test = cross_validate.train_test_split(X, y, test_size=0.2) 

请您参考如下方法:

问题是 train_test_split 不在 sklearn.crossvalidate 中,而是在 sklearn.model_selection 中。如果你想使用 train_test_split 你应该像这样使用它-

from sklearn.model_selection import train_test_split 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) 

有关更多详细信息,请查看此网址 - https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html