Fix conversion to scalar-based metrics.
@@ -2,12 +2,12 @@ import chainer
from chainer.dataset.convert import concat_examples
from chainer import cuda
from chainer import reporter
-
+from chainer.variable import Variable
from chainer_chemistry.models.prediction.base import BaseForwardModel
+import numpy
class Regressor(BaseForwardModel):
-
"""A simple regressor model.
This is an example of chain that wraps another chain. It computes the
@@ -66,6 +66,12 @@ class Regressor(BaseForwardModel):
# `initialize` must be called after `init_scope`.
self.initialize(device)
+ def _convert_to_scalar(self, value):
+ """Converts an input value to a scalar if its type is numpy array,
+ otherwise it returns the value as it is.
+ """
+ return numpy.asscalar(value) if type(value) is numpy.array else value
+
def __call__(self, *args, **kwargs):
"""Computes the loss value for an input and label pair.
@@ -119,12 +125,12 @@ class Regressor(BaseForwardModel):
# same values become arrays instead. This seems to be a bug inside the
# reporter class, which needs to be addressed and fixed. Until then,
# the reported values will be converted to numpy arrays.
- reporter.report({'loss': cuda.to_cpu(self.loss.data)}, self)
+ reporter.report({'loss': Variable(cuda.to_cpu(self.loss.data))}, self)
if self.compute_metrics:
# Note: self.metrics_fun is `dict`,
# which is different from original chainer implementation
- self.metrics = {key: cuda.to_cpu(value(self.y, t))
+ self.metrics = {key: self._convert_to_scalar(value(self.y, t))
for key, value in self.metrics_fun.items()}
reporter.report(self.metrics, self)
return self.loss
