【问题标题】:Load keras model h5 unknown metrics加载 keras 模型 h5 未知指标
【发布时间】:2020-12-11 15:22:40
【问题描述】:

我已经训练了一个监控指标的 keras CNN,如下所示:

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:

 model.compile(optimizer='nadam', loss='binary_crossentropy',
         metrics=METRICS)

它完美运行,我保存了我的 h5 模型 (model.h5)。

现在我已经下载了模型,我想在导入模型的其他脚本中使用它:

 from keras.models import load_model
 model = load_model('model.h5')
 model.predict(....)

但在运行期间编译器返回:

 ValueError: Unknown metric function: {'class_name': 'TruePositives', 'config': {'name': 'tp', 'dtype': 'float32', 'thresholds': None}}

我应该如何处理这个问题?

提前谢谢你

【问题讨论】:

  • 你能展示你的全部进口吗?

标签: python keras conv-neural-network


【解决方案1】:

当您有自定义指标时,您需要采用稍微不同的方法。

  1. 创建模型、训练和保存模型
  2. 使用custom_objectscompile = False 加载模型
  3. 最后用 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%

【讨论】:

    【解决方案2】:

    看起来您正在玩 tensorflow 教程。我也使用了这些确切的指标并且遇到了同样的问题。对我有用的是使用compile = False 加载模型,然后使用自定义指标对其进行编译。然后您应该可以按预期使用model.predict(....)

    import keras
    
    model = keras.models.load_model('model.h5', compile = False)
    
    METRICS = [
          keras.metrics.TruePositives(name='tp'),
          keras.metrics.FalsePositives(name='fp'),
          keras.metrics.TrueNegatives(name='tn'),
          keras.metrics.FalseNegatives(name='fn'), 
          keras.metrics.BinaryAccuracy(name='accuracy'),
          keras.metrics.Precision(name='precision'),
          keras.metrics.Recall(name='recall'),
          keras.metrics.AUC(name='auc'),
    ]
    
    model.compile(optimizer = keras.optimizers.Adam(learning_rate=1e-4),
                  loss = 'binary_crossentropy',
                  metrics = METRICS
                 )
    

    【讨论】:

      【解决方案3】:
      custom_objects['METRICS'] = METRICS
      model = load_model('model.h5', custom_objects=custom_objects)
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 2020-06-24
        • 2021-05-16
        • 2019-06-14
        • 2021-02-18
        • 1970-01-01
        • 2020-09-10
        • 2019-04-10
        相关资源
        最近更新 更多