Shashank Gupta
Shashank Gupta

Reputation: 315

ValueError: Error when checking target: expected dense_1 to have shape (7, 7) but got array with shape (7, 1)

I am trying to predict the prices of next 7 days using the past values. I am using tensorflow 1.15 and python 2.7 . I know these are old versions but I was having problems installing tensorflow latest version so I am working on these versions. My problem is that I am not able to train my model as it shows error :

ValueError: Error when checking target: expected dense_1 to have shape (7, 7) but got array with shape (7, 1)

This is my code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os

dataset_train = pd.read_excel('C:/Users/Shashank/Desktop/Neural Network/potatoTrainData.xlsx')
training_set = dataset_train.iloc[:,1:2].values

print(len(training_set))

from sklearn.preprocessing import MinMaxScaler
print(training_set)
sc=MinMaxScaler(feature_range = (0,1))
training_set_scale = sc.fit_transform(training_set)

X_train=[]
Y_train=[]

previous=7
next=7


for i in range(previous , len(training_set_scale)-next):
    X_train.append(training_set_scale[i-previous:i,0])
    Y_train.append(training_set_scale[i:i+next,0])

X_train,Y_train = np.array(X_train),np.array(Y_train)

X_train = np.reshape(X_train, (X_train.shape[0],X_train.shape[1],1))
print("X train")
print(X_train)
print("Y train")
print(Y_train)
X_train=X_train.reshape(X_train.shape[0],X_train.shape[1],1)
Y_train = Y_train[:, :, None]

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

regressor = Sequential()
regressor.add(LSTM(units = 200, activation='relu', return_sequences = True, input_shape=(X_train.shape[1:]) ))

regressor.add(Dense(7))

regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

regressor.fit(X_train,Y_train,epochs=200,batch_size=32)

dataset_test= pd.read_excel('C:/Users/Shashank/Desktop/Neural Network/potatoTestData.xlsx')
real_price = dataset_test.iloc[:,1:2].values


dataset_total=pd.concat((dataset_train['price'] , dataset_test['test_price']),axis = 0)
print(len(dataset_total))
print(dataset_total)
inputs=dataset_total[len(dataset_total)-len(dataset_test)-previous:].values
print(inputs)
inputs=inputs.reshape(-1,1)
inputs=sc.transform(inputs)
X_test=[]
Y_test=[]
for i in range(previous,len(inputs)-next):
    X_test.append(inputs[i-previous:i,0])
    Y_test.append(inputs[i:i+next,0])

print(X_test)
X_test=np.array(X_test)
X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
predicted_price=regressor.predict(X_test)
predicted_price=sc.inverse_transform(predicted_price)

print(real_price)

plt.plot(real_price , color='red' , label='Real Price')
plt.plot(predicted_price , color='blue' , label='Predicted Price')
plt.title('Price Prediction')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()

Shape of X_train is(308,7,1) and shape Y_train is (308,7,1). If I need to add any layers in my Y_train, please let me know how to do that.

Upvotes: 0

Views: 63

Answers (1)

Corrado
Corrado

Reputation: 46

You passed return_sequences = True, thus LSTM returns the output for each time step. Because you set 7 outputs, the shape will be 7x7. You have two options:

  1. Set return_sequences = False
  2. Put a Flatten layer between LSTM and the Dense layer

Sorry, I cannot test it right now, so maybe there could be other subtleties.

Upvotes: 1

Related Questions