{
  "id": 76509,
  "title": "ModelCheckPoint with AUC(Keras)",
  "url": "/competitions/histopathologic-cancer-detection/discussion/76509",
  "author_name": "Amirreza Mahbod",
  "post_date": "2019-01-03T15:19:48.076000",
  "votes": 2,
  "comment_count": 3,
  "views": 0,
  "content": "<p>Hi,\nWould it possible to use ModelCheckPiont with AUC score  (or define a custom callsback) to save the best model with the highest AUC score on validation data? </p>",
  "messages": [
    {
      "id": 452799,
      "postDate": "2019-01-09T07:01:19.880Z",
      "content": "<p>Yes, you can do it.</p>\n\n<p>But before using ModelCheckpoint, you need to compute the AUC score on your validation data. It can be done by implement your custom callback to help you to compute it. The following is the simple example.</p>\n\n<p>```python\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import roc_auc_score</p>\n\n<p>class RocAucMetric(Callback):</p>\n\n<pre><code>def on_train_begin(self, logs={}):\n    # By default, self.params['metrics'] contains loss and the metric assigned in `model.compile()`\n    if not 'val_roc_auc' in self.params['metrics']:\n        self.params['metrics'].append('val_roc_auc')\n\n    logs['val_roc_auc'] = float('-inf')\n\ndef on_epoch_end(self, epoch, logs={}):\n    y_true = self.validation_data[1]\n    y_pred = self.model.predict(self.validation_data[0])\n    score = roc_auc_score(y_true, y_pred)\n\n    logs['val_roc_auc'] = score\n</code></pre>\n\n<p>```</p>\n\n<p>Then you can set your <code>callbacks</code> and pass it to <code>model.fit()</code>. Remember to put <code>RocAucMetric</code> ahead of <code>ModelCheckpoint</code> so that <code>val_roc_auc</code> exists and <code>ModelCheckpoint</code> can find it.</p>\n\n<p><code>python\ncallbacks = [RocAucMetric(),\n             ModelCheckpoint(path, monitor='val_roc_auc', save_best_only=True, mode='max')\n            ]\nmodel.fit(X, y,\n          batch_size= batch_size,\n          epochs= epochs\n          callbacks= callbacks,\n          validation_data= validation_data)\n</code></p>",
      "rawMarkdown": "Yes, you can do it.\n\nBut before using ModelCheckpoint, you need to compute the AUC score on your validation data. It can be done by implement your custom callback to help you to compute it. The following is the simple example.\n\n```python\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import roc_auc_score\n\nclass RocAucMetric(Callback):\n\n    def on_train_begin(self, logs={}):\n        # By default, self.params['metrics'] contains loss and the metric assigned in `model.compile()`\n        if not 'val_roc_auc' in self.params['metrics']:\n            self.params['metrics'].append('val_roc_auc')\n\n        logs['val_roc_auc'] = float('-inf')\n\n    def on_epoch_end(self, epoch, logs={}):\n        y_true = self.validation_data[1]\n        y_pred = self.model.predict(self.validation_data[0])\n        score = roc_auc_score(y_true, y_pred)\n\n        logs['val_roc_auc'] = score\n```\n\nThen you can set your `callbacks` and pass it to `model.fit()`. Remember to put `RocAucMetric` ahead of `ModelCheckpoint` so that `val_roc_auc` exists and `ModelCheckpoint ` can find it.\n\n```python\ncallbacks = [RocAucMetric(),\n             ModelCheckpoint(path, monitor='val_roc_auc', save_best_only=True, mode='max')\n            ]\nmodel.fit(X, y,\n          batch_size= batch_size,\n          epochs= epochs\n          callbacks= callbacks,\n          validation_data= validation_data)\n```",
      "votes": 4,
      "replies": [
        {
          "id": 462024,
          "postDate": "2019-01-27T14:08:06.490Z",
          "rawMarkdown": "",
          "isDeleted": true
        },
        {
          "id": 494207,
          "postDate": "2019-03-19T15:21:05.587Z",
          "content": "<p>Hi,\nIt seems it doesn't work with <code>model.fit_generator</code> . I got an error as follows: \n```\n14     def on_epoch_end(self, epoch, logs={}):\n---&gt; 15         y_true = self.validation_data[1]'\n     16         y_pred = self.model.predict(self.validation_data[0])\n     17         score = roc_auc_score(y_true, y_pred)</p>\n\n<p>TypeError: 'NoneType' object is not subscriptable\n```</p>\n\n<p>Any idea how to solve this? </p>",
          "rawMarkdown": "Hi,\nIt seems it doesn't work with ` model.fit_generator` . I got an error as follows: \n```\n14     def on_epoch_end(self, epoch, logs={}):\n---&gt; 15         y_true = self.validation_data[1]'\n     16         y_pred = self.model.predict(self.validation_data[0])\n     17         score = roc_auc_score(y_true, y_pred)\n\nTypeError: 'NoneType' object is not subscriptable\n```\n\nAny idea how to solve this? "
        }
      ]
    },
    {
      "id": 449680,
      "postDate": "2019-01-03T15:19:48.077Z",
      "content": "<p>Hi,\nWould it possible to use ModelCheckPiont with AUC score  (or define a custom callsback) to save the best model with the highest AUC score on validation data? </p>",
      "rawMarkdown": "Hi,\nWould it possible to use ModelCheckPiont with AUC score  (or define a custom callsback) to save the best model with the highest AUC score on validation data? ",
      "votes": 2
    }
  ],
  "comments": [
    {
      "id": 452799,
      "author_name": "William Huang",
      "author_url": "",
      "post_date": "2019-01-09T07:01:19.880000",
      "content": "<p>Yes, you can do it.</p>\n\n<p>But before using ModelCheckpoint, you need to compute the AUC score on your validation data. It can be done by implement your custom callback to help you to compute it. The following is the simple example.</p>\n\n<p>```python\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import roc_auc_score</p>\n\n<p>class RocAucMetric(Callback):</p>\n\n<pre><code>def on_train_begin(self, logs={}):\n    # By default, self.params['metrics'] contains loss and the metric assigned in `model.compile()`\n    if not 'val_roc_auc' in self.params['metrics']:\n        self.params['metrics'].append('val_roc_auc')\n\n    logs['val_roc_auc'] = float('-inf')\n\ndef on_epoch_end(self, epoch, logs={}):\n    y_true = self.validation_data[1]\n    y_pred = self.model.predict(self.validation_data[0])\n    score = roc_auc_score(y_true, y_pred)\n\n    logs['val_roc_auc'] = score\n</code></pre>\n\n<p>```</p>\n\n<p>Then you can set your <code>callbacks</code> and pass it to <code>model.fit()</code>. Remember to put <code>RocAucMetric</code> ahead of <code>ModelCheckpoint</code> so that <code>val_roc_auc</code> exists and <code>ModelCheckpoint</code> can find it.</p>\n\n<p><code>python\ncallbacks = [RocAucMetric(),\n             ModelCheckpoint(path, monitor='val_roc_auc', save_best_only=True, mode='max')\n            ]\nmodel.fit(X, y,\n          batch_size= batch_size,\n          epochs= epochs\n          callbacks= callbacks,\n          validation_data= validation_data)\n</code></p>",
      "votes": 4,
      "replies": [
        {
          "id": 462024,
          "author_name": "",
          "author_url": "",
          "post_date": "2019-01-27T14:08:06.490000",
          "content": "",
          "votes": 0,
          "replies": []
        },
        {
          "id": 494207,
          "author_name": "learner",
          "author_url": "",
          "post_date": "2019-03-19T15:21:05.587000",
          "content": "<p>Hi,\nIt seems it doesn't work with <code>model.fit_generator</code> . I got an error as follows: \n```\n14     def on_epoch_end(self, epoch, logs={}):\n---&gt; 15         y_true = self.validation_data[1]'\n     16         y_pred = self.model.predict(self.validation_data[0])\n     17         score = roc_auc_score(y_true, y_pred)</p>\n\n<p>TypeError: 'NoneType' object is not subscriptable\n```</p>\n\n<p>Any idea how to solve this? </p>",
          "votes": 0,
          "replies": []
        }
      ]
    }
  ],
  "raw_markdown_by_id": {
    "452799": "Yes, you can do it.\n\nBut before using ModelCheckpoint, you need to compute the AUC score on your validation data. It can be done by implement your custom callback to help you to compute it. The following is the simple example.\n\n```python\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import roc_auc_score\n\nclass RocAucMetric(Callback):\n\n    def on_train_begin(self, logs={}):\n        # By default, self.params['metrics'] contains loss and the metric assigned in `model.compile()`\n        if not 'val_roc_auc' in self.params['metrics']:\n            self.params['metrics'].append('val_roc_auc')\n\n        logs['val_roc_auc'] = float('-inf')\n\n    def on_epoch_end(self, epoch, logs={}):\n        y_true = self.validation_data[1]\n        y_pred = self.model.predict(self.validation_data[0])\n        score = roc_auc_score(y_true, y_pred)\n\n        logs['val_roc_auc'] = score\n```\n\nThen you can set your `callbacks` and pass it to `model.fit()`. Remember to put `RocAucMetric` ahead of `ModelCheckpoint` so that `val_roc_auc` exists and `ModelCheckpoint ` can find it.\n\n```python\ncallbacks = [RocAucMetric(),\n             ModelCheckpoint(path, monitor='val_roc_auc', save_best_only=True, mode='max')\n            ]\nmodel.fit(X, y,\n          batch_size= batch_size,\n          epochs= epochs\n          callbacks= callbacks,\n          validation_data= validation_data)\n```",
    "449680": "Hi,\nWould it possible to use ModelCheckPiont with AUC score  (or define a custom callsback) to save the best model with the highest AUC score on validation data? "
  }
}