保存模型后得到错误的预测

时间:2020-04-07 04:32:05

标签: python tensorflow machine-learning keras deep-learning

我的模型源代码:-

import numpy as np
import pandas as pd

dataset= pd.read_csv("heart900.csv")
X=dataset.iloc[:, :-1].values
Y=dataset.iloc[:, 13].values

from sklearn.impute import SimpleImputer 
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')

imputer= imputer.fit(X)
X= imputer.transform(X)

from sklearn.model_selection import train_test_split
X_Train, X_Test, Y_Train, Y_Test= train_test_split(X,Y, test_size=0.2, random_state=0)

from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
X_Train=sc.fit_transform(X_Train)
X_Test=sc.fit_transform(X_Test) 

import keras
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras import Sequential
from tensorflow.python.keras.models import load_model
import tensorflow as tf
import warnings


model=Sequential()
##First Hidden Layer
model.add(Dense(6, input_dim=13, activation='relu'))
##Second Hidden Layer
model.add(Dense(6, activation='relu'))
##Third Hidden Layer
model.add(Dense(6, activation='relu'))
##Output Layer
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(X_Train, Y_Train, epochs=150, batch_size=10)

new_pred= model.predict(sc.transform(np.array([[62,1,1,120,281,0,0,103,0,1.4,1,1,3]])))

new_pred= (new_pred>0.5)
print(new_pred )

model.save('keras_model.h5')`

此处O / P为:-错误

以及用于访问保存的模型的“我的源代码”:-

from tensorflow.python.keras.models import load_model
import numpy as np


mp = load_model('keras_model.h5')
new_pre = mp.predict((np.array([[62,1,1,120,281,0,0,103,0,1.4,1,1,3]])))
new_pre = (new_pre>0.5)
print(new_pre)

此处O / P为:-正确(应该为False)

我尝试了所有可能的方法来保存h5模型,但是每次结果预测都是错误的。 请帮忙!!!!!

1 个答案:

答案 0 :(得分:1)

您是否忘记了在预测第二次输入时向输入数据添加转换?

mp = load_model('keras_model.h5')
new_pre = mp.predict(sc.transform((np.array([[62,1,1,120,281,0,0,103,0,1.4,1,1,3]]))))
new_pre = (new_pre>0.5)
print(new_pre)