You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2019/03/15 22:24:14 UTC

[GitHub] [incubator-mxnet] roywei commented on a change in pull request #14442: [MXNet-1349][WIP][Fit API]Add validation support and unit tests for fit() API

roywei commented on a change in pull request #14442: [MXNet-1349][WIP][Fit API]Add validation support and unit tests for fit() API
URL: https://github.com/apache/incubator-mxnet/pull/14442#discussion_r266163119
 
 

 ##########
 File path: python/mxnet/gluon/estimator/event_handler.py
 ##########
 @@ -0,0 +1,311 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# coding: utf-8
+# pylint: disable=wildcard-import
+"""Gluon EventHandlers for Estimators"""
+
+__all__ = ['EventHandler', 'LoggingHandler']
+import logging
+import os
+import time
+import warnings
+
+import numpy as np
+
+
+class EventHandler(object):
+    """Basic for event handlers
+
+        :py:class:`EventHandler` can perform user defined functions at
+        different stages of training: train begin, epoch begin, batch begin,
+        batch end, epoch end, train end.
+
+        Parameters
+        ----------
+        estimator : Estimator
+            The :py:class:`Estimator` to get training statistics
+        """
+    def __init__(self, estimator):
+        self._estimator = estimator
+
+    def train_begin(self):
+        pass
+
+    def train_end(self):
+        pass
+
+    def batch_begin(self):
+        pass
+
+    def batch_end(self):
+        pass
+
+    def epoch_begin(self):
+        pass
+
+    def epoch_end(self):
+        pass
+
+
+class LoggingHandler(EventHandler):
+    """Basic Logging Handler that applies to every Gluon estimator by default.
+
+    :py:class:`LoggingHandler` logs hyper-parameters, training statistics,
+    and other useful information during training
+
+    Parameters
+    ----------
+    estimator : Estimator
+        The :py:class:`Estimator` to get training statistics
+    file_name : str
+        file name to save the logs
+    file_location: str
+        file location to save the logs
+    """
+
+    def __init__(self, estimator, file_name=None, file_location=None, ):
+        super(LoggingHandler, self).__init__(estimator)
+        self.logger = logging.getLogger(__name__)
+        self.logger.setLevel(logging.INFO)
+        stream_handler = logging.StreamHandler()
+        self.logger.addHandler(stream_handler)
+        # save logger to file only if file name or location is specified
+        if file_name or file_location:
+            file_name = file_name or 'estimator_log'
+            file_location = file_location or './'
+            file_handler = logging.FileHandler(os.path.join(file_location, file_name))
+            self.logger.addHandler(file_handler)
+
+    def train_begin(self):
+        pass
+
+    def train_end(self):
+        pass
+
+    def batch_begin(self):
+        self.batch_start = time.time()
+
+    def batch_end(self):
+        batch_time = time.time() - self.batch_start
+        epoch = self._estimator.train_stats['epochs'][-1]
+        step = self._estimator.train_stats['step']
+        msg = '[Epoch %d] [Step %s] time/step: %.3fs ' % (epoch, step, batch_time)
+        for key in self._estimator.train_stats.keys():
+            if key.startswith('batch_'):
+                msg += key[6:] + ': ' + '%.4f ' % self._estimator.train_stats[key]
+        self.logger.info(msg)
+
+    def epoch_begin(self):
+        self.epoch_start = time.time()
+
+    def epoch_end(self, do_validation=False):
+        epoch_time = time.time() - self.epoch_start
+        epoch = self._estimator.train_stats['epochs'][-1]
+        msg = '\n[Epoch %d] finished in %.3fs: ' % (epoch, epoch_time)
+        for key in self._estimator.train_stats.keys():
+            if do_validation:
+                if key.startswith('train_') or key.startswith('test_'):
 
 Review comment:
   you can remove the if else and no need to pass `do_validation`.  The logic can simply be if key starts with `train` or `val`, log it, even if no  validation is done

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services