如何在python中解决此错误(Jupyter笔记本中代码)

mzillmmw  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(118)

我在三月份创建了这个程序,当时它运行得很好,但是现在它有一个错误,我不知道为什么。
这是目前不工作的代码(我在Jupiter笔记本上编写了此代码)

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import seaborn
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
pd.options.mode.chained_assignment = None  # default='warn'

df = yf.download("spy")
df.to_csv('spy.csv')
df = df[['Adj Close']]
plt.plot(df)

df['Adj Close'].plot(figsize=(15,6), color = 'g')
plt.legend(loc='upper left')
plt.show()

forecast = 70
df['Prediction'] = df[['Adj Close']].shift(-forecast)
X = np.array(df.drop(['Prediction'], 1))
X = preprocessing.scale(X)            
X_forecast = X[-forecast:]
X = X[:-forecast]
y = np.array(df['Prediction'])
y = y[:-forecast]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
confidence
forecast_predicted = clf.predict(X_forecast)
print(forecast_predicted)

plt.plot(X, y)

dates = pd.date_range(start="2021-05-21", end= "2021-06-19")
plt.plot(dates, forecast_predicted, color='b')
df['Adj Close'].plot(color='g')
plt.xlim(xmin = datetime.date(2020,5,1))
plt.xlim(xmax = datetime.date(2021,7,1))

我知道错误在代码的最后一部分。下面是代码的最后一部分在3月15日运行时的样子。

dates = pd.date_range(start="2021-03-16", end= "2021-04-14")
plt.plot(dates, forecast_predicted, color='b')
df['Adj Close'].plot(color='g')
plt.xlim(xmin = datetime.date(2020,3,1))
plt.xlim(xmax = datetime.date(2021,5,1))
bvjxkvbb

bvjxkvbb1#

错误输出中对此进行了解释:您的x和y第一维不匹配。问题是您预测了70天(预测=70),并试图将其绘制到30天期间。
您可以尝试更改预测天数:

forecast=30

或者是时间段,所以它匹配70天,就像这样:

dates = pd.date_range(start="2021-05-21", end= "2021-07-29")

相关问题