question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[tune] (KeyError: 'acc'): regression task: mse / mae as metric

See original GitHub issue

System information

  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): CentOS Linux 7
  • Ray installed from (source or binary): source
  • Ray version: 0.7.3
  • Python version: Python 3.6

Describe the problem

With Keras I wrote an neural network for a regression task based on this example (classification):

https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/tune_mnist_keras.py

The following procedure:

  • Train function: neural network replaced
  • Train function: metric: mse or mae specified

If the metric is mse or mae instead of acc, the following error message appears after execution:

self.reporter(keras_info=logs, mean_accuracy=logs[“acc”]) KeyError: ‘acc’

Are there other Keras examples specifically for regression tasks?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
richardliawcommented, Aug 28, 2019

Try using this for the callback:

import keras
from ray.tune import track

class TuneReporterCallback(keras.callbacks.Callback):
    """Tune Callback for Keras."""

    def __init__(self, reporter=None, freq="batch", metrics=None, logs={}):
        """Initializer.
        Args:
            reporter (StatusReporter|tune.track.log|None): Tune object for
                returning results.
            freq (str): Sets the frequency of reporting intermediate results.
                One of ["batch", "epoch"].
        """
        self.reporter = reporter or track.log
        self.iteration = 0
        self.metrics = metrics or None
        if freq not in ["batch", "epoch"]:
            raise ValueError("{} not supported as a frequency.".format(freq))
        self.freq = freq
        super(TuneReporterCallback, self).__init__()

    def on_batch_end(self, batch, logs={}):
        if not self.freq == "batch":
            return
        self.iteration += 1
        for metric in list(logs):
            if "loss" in metric and "neg_" not in metric:
                logs["neg_" + metric] = -logs[metric]
        self.reporter(keras_info=logs, mean_accuracy=logs.get("acc"))

    def on_epoch_end(self, batch, logs={}):
        if not self.freq == "epoch":
            return
        self.iteration += 1
        for metric in list(logs):
            if "loss" in metric and "neg_" not in metric:
                logs["neg_" + metric] = -logs[metric]
        self.reporter(keras_info=logs, mean_accuracy=logs.get("acc"))

And for any place that you want to use a metric to optimize (i.e. AsyncHyperBandScheduler), you should instead replace it with: AsyncHyperBandScheduler(metric="keras_info/mse:, mode="min"..._

I’ll add more examples in upcoming days. Let me know if you run into anything - thanks!

0reactions
krfrickecommented, Sep 16, 2020

The Keras callback got updated in #10509. If the issue persist, please re-open with a reproducible script, and we will try to solve the problem.

Read more comments on GitHub >

github_iconTop Results From Across the Web

'acc' and KeyError: 'val_acc' Errors in Keras 2.3.x or Newer | by ...
What this means is that if you specify metrics=[“accuracy”] in the model.compile(), then the history object will have the keys as 'accuracy' and ......
Read more >
Evaluate the Performance of Deep Learning Models in Keras
The example creates and evaluates 10 models using the 10 splits of the data and collects all the scores. The verbose output for...
Read more >
Regression | EDA, Stacking & Ensembling - Kaggle
Stacking is one of the most popular ensemble machine learning techniques used to predict multiple nodes to build a new model and improve...
Read more >
Keras Metrics: Everything You Need to Know - neptune.ai
The metrics used in regression problems include Mean Squared Error, Mean Absolute Error, and Mean Absolute Percentage Error. These metrics are used when ......
Read more >
Amazon SageMaker - Developer Guide
Monitoring Training Job Metrics (Amazon SageMaker Console) . ... Write down your AWS account ID because you'll need it for the next task....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found