加载Keras模型H5未知指标 [英] Load keras model h5 unknown metrics
本文介绍了加载Keras模型H5未知指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经训练了一个监控指标的keras CNN,如下所示:
I have trained a keras CNN monitoring the metrics as follow:
METRICS = [
TruePositives(name='tp'),
FalsePositives(name='fp'),
TrueNegatives(name='tn'),
FalseNegatives(name='fn'),
BinaryAccuracy(name='accuracy'),
Precision(name='precision'),
Recall(name='recall'),
AUC(name='auc'),
]
然后是model.compile:
and then the model.compile:
model.compile(optimizer='nadam', loss='binary_crossentropy',
metrics=METRICS)
它工作正常,我保存了我的h5模型(model.h5)。
it works perfectly and I saved my h5 model (model.h5).
现在我已经下载了模型并且我想在其他脚本中使用它导入模型,
Now I have downloaded the model and I would like to use it in other script importing the model with:
from keras.models import load_model
model = load_model('model.h5')
model.predict(....)
但是在运行期间,编译器返回:
but during the running the compiler returns:
ValueError: Unknown metric function: {'class_name': 'TruePositives', 'config': {'name': 'tp', 'dtype': 'float32', 'thresholds': None}}
我应该如何处理此问题?
How I should manage this issue?
请先谢谢您
推荐答案
自定义指标后,您需要采用略有不同的方法。
When you have custom metrics you need to follow slightly different approach.
- 创建模型,训练并保存模型
- 使用
custom_objects
和<$ c $加载模型c> compile = False - 最后用custom_objects编译模型
- Create model, train and save the model
- Load the model with
custom_objects
andcompile = False
- Finally compile the model with the custom_objects
我在这里展示方法
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Custom Loss1 (for example)
#@tf.function()
def customLoss1(yTrue,yPred):
return tf.reduce_mean(yTrue-yPred)
# Custom Loss2 (for example)
#@tf.function()
def customLoss2(yTrue, yPred):
return tf.reduce_mean(tf.square(tf.subtract(yTrue,yPred)))
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy', customLoss1, customLoss2])
return model
# Create a basic model instance
model=create_model()
# Fit and evaluate model
model.fit(x_train, y_train, epochs=5)
loss, acc,loss1, loss2 = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc)) # Original model, accuracy: 98.11%
# saving the model
model.save('./Mymodel',save_format='tf')
# load the model
loaded_model = tf.keras.models.load_model('./Mymodel',custom_objects={'customLoss1':customLoss1,'customLoss2':customLoss2},compile=False)
# compile the model
loaded_model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy', customLoss1, customLoss2])
# loaded model also has same accuracy, metrics and loss
loss, acc,loss1, loss2 = loaded_model.evaluate(x_test, y_test,verbose=1)
print("Loaded model, accuracy: {:5.2f}%".format(100*acc)) #Loaded model, accuracy: 98.11%
这篇关于加载Keras模型H5未知指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文