【问题标题】:how to fix ''Found input variables with inconsistent numbers of samples: [219, 247]''如何修复“发现样本数量不一致的输入变量:[219, 247]”
【发布时间】:2019-06-29 22:27:23
【问题描述】:

正如标题所说,在运行以下代码时我遇到了问题 发现输入变量的样本数量不一致:[219, 247],我已经读到问题应该出在为 X 和 y 设置的 np.array 上,但是我无法解决这个问题,因为每个日期都有一个价格,所以我不明白为什么会这样,任何帮助将不胜感激!

import pandas as pd
import quandl, math, datetime
import numpy as np
from sklearn import preprocessing, svm, model_selection
from sklearn.linear_model import LinearRegression
import matplotlib as plt
from matplotlib import style

style.use('ggplot')


df = quandl.get("NASDAQOMX/XNDXT25NNR", authtoken='myapikey')   
df = df[['Index Value','High','Low','Total Market Value']]
df['HL_PCT'] = (df['High'] - df['Low']) / df['Index Value'] * 100.0
df = df[['Low','High','HL_PCT']]

forecast_col = 'High'
df.fillna(-99999, inplace=True)

forecast_out = int(math.ceil(0.1*len(df)))

df['label'] = df[forecast_col].shift(-forecast_out)
df.dropna(inplace= True)

X = np.array(df.drop(['label'],1))

X = preprocessing.scale(X)

X_lately = X[-forecast_out:]

X = X[:-forecast_out]

y=np.array(df['label'])
#X= X[:-forecast_out+1]
df.dropna(inplace=True)
y= np.array(df['label'])

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

clf= LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
forecast_set= clf.predict(X_lately)
print(forecast_set, accuracy, forecast_out)
df['Forecast'] = np.nan

last_data= df.iloc[-1].name
last_unix= last_date.timestamp()
one_day=86400 
next_unix= last_unix + one_day

for i in forecast_set:
    next_date= datetime.datetime.fromtimestamp(next_unix)
    next_unix += one_day
    df.loc[next_date]= [np.nan for _ in range(len(df.columns) -1)] + 
[i]

df['High'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

预期结果应该是该股票代码的未来价格预测图,但除此之外,它还会抛出错误“发现样本数量不一致的输入变量:[219, 247]”。

【问题讨论】:

  • 欢迎来到 Stackoverflow!你在哪一行得到错误?

标签: python numpy scikit-learn sklearn-pandas


【解决方案1】:

您的问题在于从您的代码中提取的这两行代码:

X = X[:-forecast_out]
y= np.array(df['label'])

您正在对X 进行子集化,但将y 保留为“原样”。

您可以通过以下方式检查形状是否确实不同:

X.shape, y.shape

将最后一行改为:

y= np.array(df[:-forecast_out]['label'])

你很好。

请注意,不要重复这些行:

y=np.array(df['label'])
#X= X[:-forecast_out+1]
df.dropna(inplace=True) # there is no na at this point
y= np.array(df['label'])

以下行(解决您的问题)就足够了:

y= np.array(df[:-forecast_out]['label'])

【讨论】:

  • 嘿,我试过了,#y=np.array(df['label']) 程序运行了,但结果不太可能是我所期望的,然后我看到了你的评论并尝试了它''y= np.array(df[:-forecast_out]['label'])'',这就是答案,它运行了,但也达到了我的预期,谢谢!
  • 如果这解决了您的错误,您可能会考虑接受答案。
猜你喜欢
  • 2019-11-16
  • 2021-03-25
  • 2021-06-20
  • 2018-06-25
  • 1970-01-01
  • 2021-05-06
  • 2020-11-19
  • 2019-12-11
  • 2020-03-14
相关资源
最近更新 更多