简体   繁体   中英

Matplotlib Error: x and y must have same first dimension, but have shapes (100,) and (449,)

I'm trying to learn more about Hidden Markov and found this code online. I got through most of it without a problem except for the very end where it turns up ValueError: x and y must have same first dimension, but have shapes (100,) and (449,) referring to this line: ----> 3 plt.plot(predicted_dates,close_val[N+1:-246]) when trying to plot the final results.

You'll have to excuse me, this is literally my 5th day playing around with python and jupyter notebooks, so if you can explain to me like a child (with no programming experience) it would be appreciated.

%matplotlib inline
import datetime
import numpy as np
import pandas as pd
from pandas_datareader import data 
from hmmlearn.hmm import GaussianHMM
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.dates import YearLocator, MonthLocator
import warnings
warnings.filterwarnings('ignore')

ticker = 'EA'
start_date = datetime.date(2019, 1, 1)
end_date = datetime.date.today()
Stocks = data.DataReader(ticker, 'yahoo', start_date, end_date)

Stocks.reset_index(inplace = True, drop=False)
Stocks.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1, inplace=True)
Stocks['Date'] = Stocks['Date'].apply(datetime.datetime.toordinal)
Stocks = list(Stocks.itertuples(index=False, name=None))

dates = np.array([q[0] for q in Stocks], dtype=int)
close_val = np.array([q[1] for q in Stocks])
close = [close_val[j] / close_val[j-1] for j in range(1, len(close_val))]

fig = plt.figure()
fig, ax = plt.subplots(figsize=(12,8))
plt.title('Stock Price over Time (EA)', fontsize=14)
ax.plot_date(dates, close_val, '-', label='Close')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.xlabel('Date', fontsize = 14)
plt.ylabel('Close (price)', fontsize = 14)
plt.legend()
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()

N = 5
train_x = list(map(lambda el:[el], close[:N]))

model = GaussianHMM(n_components=2, covariance_type='diag', n_iter=1000)

predicted_prices = []
predicted_dates = []

for idx in range(100):
    model.fit(train_x)
    state = model.predict(train_x)[-1]
    means = model.means_[state]
    current_price = Stocks[N+idx][1]
    current_date = datetime.date.fromordinal(dates[N+idx])
    predicted_date = current_date + datetime.timedelta(days=1)
    predicted_dates.append(predicted_date)
    train_x.append([means[0]])
    predicted_prices.append(current_price * means[0])
    train_x.pop(0)
    
print('Actual:',close_val[N+1:-246], '\n','Prediction:', predicted_prices)

plt.figure(figsize=(12,8))
plt.title('Close (price)', fontsize=14)
**plt.plot(predicted_dates,close_val[N+1:-246])**
plt.plot(predicted_dates,predicted_prices)
plt.legend(['Actual', 'Predicted'])
plt.grid(True)
plt.show()

I changed the -246 to -595 so that the shape would be 1:1 and it fixed the issue. Not that I fully understand what's going on, but it's the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM