AttributeError: 'History' object has no at

2019-07-09 00:19发布

问题:

I am trying a NN model using this example. I am fitting a list of values to a NN model. However, I am getting an AttributeError. This has been asked before and has been answered. Unfortunately, it is not working for me. As shown in the example, I created the following,

from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from keras.layers import Dense

def neuralnetmodel():
    #Crete model
    model = Sequential()
    model.add(Dense(13, input_dim = 13, kernel_initializer = 'normal', activation = 'relu'))

model.add(Dense(1, kernel_initializer = 'normal', activation = 'relu'))
model.add(Dense(1, kernel_initializer = 'normal', activation = 'relu'))
## Output layer
model.add(Dense(1, kernel_initializer = 'normal'))

#Compile model
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
return model

fit training data,

NNmodelList = []

for i,j in zip(X_train_scaled,y_train): 
    nn_model = KerasRegressor(build_fn= neuralnetmodel, nb_epoch = 50, batch_size = 10, verbose = 0)
    NNmodelList.append(nn_model.fit(i,j))

predict from test data,

PredList = []
for val in X_test_scaled:
    for mod in NNmodelList: 
    pred = mod.predict(val)
PredList.append(pred)

Now, I am getting the error:

AttributeError: 'History' object has no attribute 'predict'

In previous threads , it seems to be the train set was not fit to the model before predict. However, in mine, I fit them in the second code snippet. Any ideas what other possible mistakes I am making?

回答1:

model.fit() does not return the Keras model, but a History object containing loss and metric values of your training. So in this code:

NNmodelList.append(nn_model.fit(i,j))

you're creating a list of History objects, not models. A simple fix would be:

NNmodelList.append(nn_model)
nn_model.fit(i,j)