Search code examples
pythontensorflowkerasrecurrent-neural-network

AttributeError: 'KerasRegressor' object has no attribute 'model'


I have this piece of code. But when I try to run the prediction value code there's an error

# Creating a data structure with n timesteps
X_test = []
for i in range(5, 25):
    X_test.append(inputs[i-5:i, 0])
X_test = np.array(X_test)
# Reshape to a new dimension
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Identify the predicted values
predicted_number = regressor.predict(X_test)
# Inverse the scaling to put them back to the normal values 
predicted_number = sc.inverse_transform(predicted_number)

the error is like this

AttributeError Traceback (most recent call last)
<ipython-input-364-17fa061596c6> in <module>()
      1 # Identify the predicted values
----> 2 predicted_number = regressor.predict(X_test)
      3 # Inverse the scaling to put them back to the normal values
      4 predicted_number = sc.inverse_transform(predicted_number)
      5 KerasRegressor.model
~\Anaconda3\lib\site-packages\keras\wrappers\scikit_learn.py in predict(self, x, **kwargs)
    320         """
    321         kwargs = self.filter_sk_params(Sequential.predict, kwargs)
--> 322         preds = np.array(self.model.predict(x, **kwargs))
    323         if preds.shape[-1] == 1:
    324             return np.squeeze(preds, axis=-1)

AttributeError: 'KerasRegressor' object has no attribute 'model'

in case if needed, below is the full script

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

dataset_train = pd.read_csv('Datatraining.csv')
training_set = dataset_train.iloc[:, 1:2].values

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

X_train = []
y_train = []
for i in range(60, 72):
    X_train.append(training_set_scaled[i-60:i, 0])
    y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)

X_train = np.reshape(X_train, newshape = (X_train.shape[0], X_train.shape[1], 1))

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

regressor = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM( units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1) ))
regressor.add(Dropout(0.2))

# Adding the second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding the third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding the fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))

regressor.add(Dense(units = 1))

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

regressor.fit(X_train, y_train, epochs = 300, batch_size = 32)

dataset_test = pd.read_csv('Datatesting.csv')
real_number_arrivals = dataset_test.iloc[:, 1:2].values

dataset_total = pd.concat( (downloads['China'], dataset_test['China']), axis = 0 )
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 72:].values
inputs = inputs.reshape(-1, 1)
inputs = sc.transform(inputs)

# Creating a data structure with n timesteps
X_test = []
for i in range(5, 25):
    X_test.append(inputs[i-5:i, 0])
X_test = np.array(X_test)
# Reshape to a new dimension
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Identify the predicted values
predicted_number = regressor.predict(X_test)
# Inverse the scaling to put them back to the normal values 
predicted_number = sc.inverse_transform(predicted_number)

any solution would be really helpful. Thanks in advance


Solution

  • You have forgotten to fit the model first.

    You did not share the whole code, but I believe you have some X_train and Y_train somewhere in your code. So try this line:

    regressor.fit(X_train, Y_train)

    And then you can run the prediction.