我在今年早些时候重温了一个机器学习教程,由于换了新笔记本电脑,似乎出现了兼容性问题。我查看了Stack Overflow上的几个答案,并根据最新的SKlearn版本中似乎有的新名称要求部分解决了这个问题。以下是代码,当我做教程时运行得很好
import quandl, mathimport numpy as npimport pandas as pdfrom sklearn import preprocessing, cross_validation, svmfrom sklearn.linear_model import LinearRegressionimport matplotlib.pyplot as pltfrom matplotlib import styleimport datetimestyle.use('ggplot')df = quandl.get("WIKI/GOOGL")df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0df = 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))X = preprocessing.scale(X)X_lately = X[-forecast_out:]X = X[:-forecast_out]df.dropna(inplace=True)y = np.array(df['label'])X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)clf = LinearRegression(n_jobs=-1)clf.fit(X_train, y_train)confidence = clf.score(X_test, y_test)forecast_set = clf.predict(X_lately)df['Forecast'] = np.nanlast_date = df.iloc[-1].namelast_unix = last_date.timestamp()one_day = 86400next_unix = last_unix + one_dayfor i in forecast_set: next_date = datetime.datetime.fromtimestamp(next_unix) next_unix += 86400 df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]df['Adj. Close'].plot()df['Forecast'].plot()plt.legend(loc=4)plt.xlabel('Date')plt.ylabel('Price')plt.show()
如果你在3.7版本中运行这段代码,会遇到一些与SKlearn相关的错误,我已经从Stack Overflow上得到了解决方法,但处理这些错误后,我遇到了如下错误
H:\Documents\Python Scripts>py ML_tutorial_vid_5.1.pyTraceback (most recent call last): File "ML_tutorial_vid_5.1.py", line 34, in <module> X_train, X_test, y_train, y_test = cross_validate.train_test_split(X, y, test_size=0.2)AttributeError: 'function' object has no attribute 'train_test_split'
任何帮助都将不胜感激。
回答:
你会遇到这个错误是因为train_test_split
现在位于sklearn
的model_selection
模块中。你可以在这里查看变更日志。
你现在可以这样导入它。
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)