我用 Keras 训练了一个模型,保存了它,当我尝试将它应用于新数据时,我遇到了一个错误:
ValueError: Error when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)
这是训练和保存训练模型的代码:
# Import necessary modules
import numpy as np # numpy is just used for reading the data
import keras
from keras.layers import Dense
from keras.models import Sequential
from keras.models import load_model # To save and load model
# fix random seed for reproducibility
seed = 7
np.random.seed(seed)
# load the dataset
dataset = np.loadtxt("modiftrain.csv", delimiter=";")
# split into input (X) and output (Y) variables
X = dataset[:,0:5]
Y = dataset[:,5]
# create model
model = Sequential()
# Add the first layer
# input_dim= has to be the number of input variables.
# It represent the number of inputs in the first layer,one per column
model.add(Dense(12, input_dim=5, activation='relu'))
# Add the second layer
model.add(Dense(8, activation='relu'))
# Add the output layer
model.add(Dense(1, activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)
# Evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
# Save the model
model.save('model_file.h5')
这是预测的代码:
import numpy as np
from keras.models import load_model # To save and load model
# Load the model
my_model = load_model('model_file.h5')
# Load the test data file and make predictions on it
predictions = my_model.predict(np.loadtxt("modiftest.csv", delimiter=";"))
print(predictions.shape)
my_predictions=my_model.predict(predictions)
print(my_predictions)
错误来了:
Traceback (most recent call last):
File "predict01.py", line 14, in <module>
my_predictions=my_model.predict(X_predictions)
File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\models.py", line 913, in predict
return self.model.predict(x, batch_size=batch_size, verbose=verbose)
File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1695, in predict
check_batch_axis=False)
File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data
str(array.shape))
ValueError: Error when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)
谢谢您的帮助。