【问题标题】:Finding precision and recall for the tutorial federated learning model on MNIST在 MNIST 上为教程联邦学习模型寻找精度和召回率
【发布时间】:2021-05-29 19:45:36
【问题描述】:

我正在使用本教程尝试通过 TensorFlow 的教程了解联合模型的工作原理:https://colab.research.google.com/github/tensorflow/federated/blob/master/docs/tutorials/federated_learning_for_image_classification.ipynb

目前,模型是这样定义的,它使用准确度作为指标。

def model_fn():
  keras_model = create_keras_model()
  return tff.learning.from_keras_model(
      keras_model,
      input_spec = preprocessed_example_dataset.element_spec,
      loss = tf.keras.losses.SparseCategoricalCrossentropy(),
      metrics = [tf.keras.metrics.SparseTopKCategoricalAccuracy()]
  )

我想使用精确率和召回率作为指标,或者在训练模型后找到它们,但我不知道该怎么做。

我尝试为 metrics = [tf.keras.metrics.SparseTopKCategoricalAccuracy(), tf.keras.metrics.Precision()] 之类的指标添加精度并运行此代码,但它给了我一个错误。

iterative_process = tff.learning.build_federated_averaging_process(
    model_fn,
    client_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=0.01),
    server_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=1.5))

错误输出:

ValueError                                Traceback (most recent call last)

<ipython-input-13-f8ac3534e325> in <module>()
      2     model_fn,
      3     client_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=0.01),
----> 4     server_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=1.5))

ValueError: Shapes (None, 10) and (None, 1) are incompatible

之前,我曾针对常规 centralized model here 提出过类似的问题,但我认为我不能使用相同的方法,因为您无法以与我相同的方式返回预测结果成立。 我还尝试查看其他文档such as this,但它也使用准确性作为指标,所以这没有帮助。如何获得这个联合模型的准确率和召回率?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    由于 Precision 和 Recall 是天然的二元指标,因此您不能将它们用于多类预测。

    错误表明您有 10 个类别进行预测,这与您提供的 1 个类别分类指标不兼容。

    但是,您可以实现一个自定义指标并将其作为参数传递给您的metrics。

    1.定义自定义指标:

    class MulticlassTruePositives(tf.keras.metrics.Metric):
        def __init__(self, name='multiclass_true_positives', **kwargs):
            super(MulticlassTruePositives, self).__init__(name=name, **kwargs)
            self.true_positives = self.add_weight(name='tp', initializer='zeros')
    
        def update_state(self, y_true, y_pred, sample_weight=None):
            y_pred = tf.reshape(tf.argmax(y_pred, axis=1), shape=(-1, 1))
            values = tf.cast(y_true, 'int32') == tf.cast(y_pred, 'int32')
            values = tf.cast(values, 'float32')
            if sample_weight is not None:
                sample_weight = tf.cast(sample_weight, 'float32')
                values = tf.multiply(values, sample_weight)
            self.true_positives.assign_add(tf.reduce_sum(values))
    
        def result(self):
            return self.true_positives
    
        def reset_states(self):
            # The state of the metric will be reset at the start of each epoch.
            self.true_positives.assign(0.)
    

    2。然后将其传递给您的metrics:

    metrics=[tf.keras.metrics.SparseCategoricalAccuracy(), MulticlassTruePositives()]
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 2021-08-16
      • 2016-01-09
      • 2022-01-06
      • 2023-04-07
      • 2023-01-05
      • 2012-11-26
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多