We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Cannot report int value
I couldn't report int value. We need to check type of an input value here:
https://github.com/pfnet/chainer/blob/master/chainer/reporter.py#L244


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `chainer/reporter.py`
Content:
```
1 import collections
2 import contextlib
3 
4 import numpy
5 import six
6 
7 from chainer import cuda
8 from chainer import variable
9 
10 
11 class Reporter(object):
12 
13     """Object to which observed values are reported.
14 
15     Reporter is used to collect values that users want to watch. The reporter
16     object holds a mapping from value names to the actually observed values.
17     We call this mapping `observations`.
18 
19     When a value is passed to the reporter, an object called `observer` can be
20     optionally attached. In this case, the name of the observer is added as the
21     prefix of the value name. The observer name should be registered
22     beforehand.
23 
24     See the following example::
25 
26        >>> from chainer import Reporter, report, report_scope
27        >>>
28        >>> reporter = Reporter()
29        >>> observer = object()  # it can be an arbitrary (reference) object
30        >>> reporter.add_observer('my_observer:', observer)
31        >>> observation = {}
32        >>> with reporter.scope(observation):
33        ...     reporter.report({'x': 1}, observer)
34        ...
35        >>> observation
36        {'my_observer:x': 1}
37 
38     There are also a global API to add values::
39 
40        >>> observation = {}
41        >>> with report_scope(observation):
42        ...     report({'x': 1}, observer)
43        ...
44        >>> observation
45        {'my_observer:x': 1}
46 
47     The most important application of Reporter is to report observed values
48     from each link or chain in the training and validation procedures.
49     :class:`~chainer.training.Trainer` and some extensions prepare their own
50     Reporter object with the hierarchy of the target link registered as
51     observers. We can use :func:`report` function inside any links and chains
52     to report the observed values (e.g., training loss, accuracy, activation
53     statistics, etc.).
54 
55     Attributes:
56         observation: Dictionary of observed values.
57 
58     """
59     def __init__(self):
60         self._observer_names = {}
61         self.observation = {}
62 
63     def __enter__(self):
64         """Makes this reporter object current."""
65         _reporters.append(self)
66 
67     def __exit__(self, exc_type, exc_value, traceback):
68         """Recovers the previous reporter object to the current."""
69         _reporters.pop()
70 
71     @contextlib.contextmanager
72     def scope(self, observation):
73         """Creates a scope to report observed values to ``observation``.
74 
75         This is a context manager to be passed to ``with`` statements. In this
76         scope, the observation dictionary is changed to the given one.
77 
78         It also makes this reporter object current.
79 
80         Args:
81             observation (dict): Observation dictionary. All observations
82                 reported inside of the ``with`` statement are written to this
83                 dictionary.
84 
85         """
86         old = self.observation
87         self.observation = observation
88         self.__enter__()
89         yield
90         self.__exit__(None, None, None)
91         self.observation = old
92 
93     def add_observer(self, name, observer):
94         """Registers an observer of values.
95 
96         Observer defines a scope of names for observed values. Values observed
97         with the observer are registered with names prefixed by the observer
98         name.
99 
100         Args:
101             name (str): Name of the observer.
102             observer: The observer object. Note that the reporter distinguishes
103                 the observers by their object ids (i.e., ``id(owner)``), rather
104                 than the object equality.
105 
106         """
107         self._observer_names[id(observer)] = name
108 
109     def add_observers(self, prefix, observers):
110         """Registers multiple observers at once.
111 
112         This is a convenient method to register multiple objects at once.
113 
114         Args:
115             prefix (str): Prefix of each name of observers.
116             observers: Iterator of name and observer pairs.
117 
118         """
119         for name, observer in observers:
120             self._observer_names[id(observer)] = prefix + name
121 
122     def report(self, values, observer=None):
123         """Reports observed values.
124 
125         The values are written with the key, prefixed by the name of the
126         observer object if given.
127 
128         Args:
129             values (dict): Dictionary of observed values.
130             observer: Observer object. Its object ID is used to retrieve the
131                 observer name, which is used as the prefix of the registration
132                 name of the observed value.
133 
134         """
135         if observer is not None:
136             observer_id = id(observer)
137             if observer_id not in self._observer_names:
138                 raise KeyError(
139                     'Given observer is not registered to the reporter.')
140             observer_name = self._observer_names[observer_id]
141             for key, value in six.iteritems(values):
142                 name = '%s/%s' % (observer_name, key)
143                 self.observation[name] = value
144         else:
145             self.observation.update(values)
146 
147 
148 _reporters = []
149 
150 
151 def get_current_reporter():
152     """Returns the current reporter object."""
153     return _reporters[-1]
154 
155 
156 def report(values, observer=None):
157     """Reports observed values with the current reporter object.
158 
159     Any reporter object can be set current by the ``with`` statement. This
160     function calls the :meth:`Report.report` method of the current reporter.
161     If no reporter object is current, this function does nothing.
162 
163     .. admonition:: Example
164 
165        The most typical example is a use within links and chains. Suppose that
166        a link is registered to the current reporter as an observer (for
167        example, the target link of the optimizer is automatically registered to
168        the reporter of the :class:`~chainer.training.Trainer`). We can report
169        some values from the link as follows::
170 
171           class MyRegressor(chainer.Chain):
172               def __init__(self, predictor):
173                   super(MyRegressor, self).__init__(predictor=predictor)
174 
175               def __call__(self, x, y):
176                   # This chain just computes the mean absolute and squared
177                   # errors between the prediction and y.
178                   pred = self.predictor(x)
179                   abs_error = F.sum(F.abs(pred - y)) / len(x.data)
180                   loss = F.mean_squared_error(pred, y)
181 
182                   # Report the mean absolute and squared errors.
183                   report({'abs_error': abs_error, 'squared_error': loss}, self)
184 
185                   return loss
186 
187        If the link is named ``'main'`` in the hierarchy (which is the default
188        name of the target link in the
189        :class:`~chainer.training.StandardUpdater`), these reported values are
190        named ``'main/abs_error'`` and ``'main/squared_error'``. If these values
191        are reported inside the :class:`~chainer.training.extension.Evaluator`
192        extension, ``'validation/'`` is added at the head of the link name, thus
193        the item names are changed to ``'validation/main/abs_error'`` and
194        ``'validation/main/squared_error'`` (``'validation'`` is the default
195        name of the Evaluator extension).
196 
197     Args:
198         values (dict): Dictionary of observed values.
199         observer: Observer object. Its object ID is used to retrieve the
200             observer name, which is used as the prefix of the registration name
201             of the observed value.
202 
203     """
204     if _reporters:
205         current = _reporters[-1]
206         current.report(values, observer)
207 
208 
209 @contextlib.contextmanager
210 def report_scope(observation):
211     """Returns a report scope with the current reporter.
212 
213     This is equivalent to ``get_current_reporter().scope(observation)``,
214     except that it does not make the reporter current redundantly.
215 
216     """
217     current = _reporters[-1]
218     old = current.observation
219     current.observation = observation
220     yield
221     current.observation = old
222 
223 
224 class Summary(object):
225 
226     """Online summarization of a sequence of scalars.
227 
228     Summary computes the statistics of given scalars online.
229 
230     """
231     def __init__(self):
232         self._x = 0
233         self._x2 = 0
234         self._n = 0
235 
236     def add(self, value):
237         """Adds a scalar value.
238 
239         Args:
240             value: Scalar value to accumulate. It is either a NumPy scalar or
241                 a zero-dimensional array (on CPU or GPU).
242 
243         """
244         with cuda.get_device(value):
245             self._x += value
246             self._x2 += value * value
247             self._n += 1
248 
249     def compute_mean(self):
250         """Computes the mean."""
251         x, n = self._x, self._n
252         with cuda.get_device(x):
253             return x / n
254 
255     def make_statistics(self):
256         """Computes and returns the mean and standard deviation values.
257 
258         Returns:
259             tuple: Mean and standard deviation values.
260 
261         """
262         x, n = self._x, self._n
263         xp = cuda.get_array_module(x)
264         with cuda.get_device(x):
265             mean = x / n
266             var = self._x2 / n - mean * mean
267             std = xp.sqrt(var, var)
268             return mean, std
269 
270 
271 class DictSummary(object):
272 
273     """Online summarization of a sequence of dictionaries.
274 
275     ``DictSummary`` computes the statistics of a given set of scalars online.
276     It only computes the statistics for scalar values and variables of scalar
277     values in the dictionaries.
278 
279     """
280     def __init__(self):
281         self._summaries = collections.defaultdict(Summary)
282 
283     def add(self, d):
284         """Adds a dictionary of scalars.
285 
286         Args:
287             d (dict): Dictionary of scalars to accumulate. Only elements of
288                scalars, zero-dimensional arrays, and variables of
289                zero-dimensional arrays are accumulated.
290 
291         """
292         summaries = self._summaries
293         for k, v in six.iteritems(d):
294             if isinstance(v, variable.Variable):
295                 v = v.data
296             if numpy.isscalar(v) or getattr(v, 'ndim', -1) == 0:
297                 summaries[k].add(v)
298 
299     def compute_mean(self):
300         """Creates a dictionary of mean values.
301 
302         It returns a single dictionary that holds a mean value for each entry
303         added to the summary.
304 
305         Returns:
306             dict: Dictionary of mean values.
307 
308         """
309         return {name: summary.compute_mean()
310                 for name, summary in six.iteritems(self._summaries)}
311 
312     def make_statistics(self):
313         """Creates a dictionary of statistics.
314 
315         It returns a single dictionary that holds mean and standard deviation
316         values for every entry added to the summary. For an entry of name
317         ``'key'``, these values are added to the dictionary by names ``'key'``
318         and ``'key.std'``, respectively.
319 
320         Returns:
321             dict: Dictionary of statistics of all entries.
322 
323         """
324         stats = {}
325         for name, summary in six.iteritems(self._summaries):
326             mean, std = summary.make_statistics()
327             stats[name] = mean
328             stats[name + '.std'] = std
329 
330         return stats
331
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/chainer/reporter.py b/chainer/reporter.py
--- a/chainer/reporter.py
+++ b/chainer/reporter.py
@@ -221,6 +221,13 @@
     current.observation = old
 
 
+def _get_device(x):
+    if numpy.isscalar(x):
+        return cuda.DummyDevice
+    else:
+        return cuda.get_device(x)
+
+
 class Summary(object):
 
     """Online summarization of a sequence of scalars.
@@ -241,7 +248,7 @@
                 a zero-dimensional array (on CPU or GPU).
 
         """
-        with cuda.get_device(value):
+        with _get_device(value):
             self._x += value
             self._x2 += value * value
             self._n += 1
@@ -249,7 +256,7 @@
     def compute_mean(self):
         """Computes the mean."""
         x, n = self._x, self._n
-        with cuda.get_device(x):
+        with _get_device(x):
             return x / n
 
     def make_statistics(self):
@@ -261,10 +268,10 @@
         """
         x, n = self._x, self._n
         xp = cuda.get_array_module(x)
-        with cuda.get_device(x):
+        with _get_device(x):
             mean = x / n
             var = self._x2 / n - mean * mean
-            std = xp.sqrt(var, var)
+            std = xp.sqrt(var)
             return mean, std

{"golden_diff": "diff --git a/chainer/reporter.py b/chainer/reporter.py\n--- a/chainer/reporter.py\n+++ b/chainer/reporter.py\n@@ -221,6 +221,13 @@\n     current.observation = old\n \n \n+def _get_device(x):\n+    if numpy.isscalar(x):\n+        return cuda.DummyDevice\n+    else:\n+        return cuda.get_device(x)\n+\n+\n class Summary(object):\n \n     \"\"\"Online summarization of a sequence of scalars.\n@@ -241,7 +248,7 @@\n                 a zero-dimensional array (on CPU or GPU).\n \n         \"\"\"\n-        with cuda.get_device(value):\n+        with _get_device(value):\n             self._x += value\n             self._x2 += value * value\n             self._n += 1\n@@ -249,7 +256,7 @@\n     def compute_mean(self):\n         \"\"\"Computes the mean.\"\"\"\n         x, n = self._x, self._n\n-        with cuda.get_device(x):\n+        with _get_device(x):\n             return x / n\n \n     def make_statistics(self):\n@@ -261,10 +268,10 @@\n         \"\"\"\n         x, n = self._x, self._n\n         xp = cuda.get_array_module(x)\n-        with cuda.get_device(x):\n+        with _get_device(x):\n             mean = x / n\n             var = self._x2 / n - mean * mean\n-            std = xp.sqrt(var, var)\n+            std = xp.sqrt(var)\n             return mean, std\n", "issue": "Cannot report int value\nI couldn't report int value. We need to check type of an input value here:\nhttps://github.com/pfnet/chainer/blob/master/chainer/reporter.py#L244\n\n", "before_files": [{"content": "import collections\nimport contextlib\n\nimport numpy\nimport six\n\nfrom chainer import cuda\nfrom chainer import variable\n\n\nclass Reporter(object):\n\n    \"\"\"Object to which observed values are reported.\n\n    Reporter is used to collect values that users want to watch. The reporter\n    object holds a mapping from value names to the actually observed values.\n    We call this mapping `observations`.\n\n    When a value is passed to the reporter, an object called `observer` can be\n    optionally attached. In this case, the name of the observer is added as the\n    prefix of the value name. The observer name should be registered\n    beforehand.\n\n    See the following example::\n\n       >>> from chainer import Reporter, report, report_scope\n       >>>\n       >>> reporter = Reporter()\n       >>> observer = object()  # it can be an arbitrary (reference) object\n       >>> reporter.add_observer('my_observer:', observer)\n       >>> observation = {}\n       >>> with reporter.scope(observation):\n       ...     reporter.report({'x': 1}, observer)\n       ...\n       >>> observation\n       {'my_observer:x': 1}\n\n    There are also a global API to add values::\n\n       >>> observation = {}\n       >>> with report_scope(observation):\n       ...     report({'x': 1}, observer)\n       ...\n       >>> observation\n       {'my_observer:x': 1}\n\n    The most important application of Reporter is to report observed values\n    from each link or chain in the training and validation procedures.\n    :class:`~chainer.training.Trainer` and some extensions prepare their own\n    Reporter object with the hierarchy of the target link registered as\n    observers. We can use :func:`report` function inside any links and chains\n    to report the observed values (e.g., training loss, accuracy, activation\n    statistics, etc.).\n\n    Attributes:\n        observation: Dictionary of observed values.\n\n    \"\"\"\n    def __init__(self):\n        self._observer_names = {}\n        self.observation = {}\n\n    def __enter__(self):\n        \"\"\"Makes this reporter object current.\"\"\"\n        _reporters.append(self)\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        \"\"\"Recovers the previous reporter object to the current.\"\"\"\n        _reporters.pop()\n\n    @contextlib.contextmanager\n    def scope(self, observation):\n        \"\"\"Creates a scope to report observed values to ``observation``.\n\n        This is a context manager to be passed to ``with`` statements. In this\n        scope, the observation dictionary is changed to the given one.\n\n        It also makes this reporter object current.\n\n        Args:\n            observation (dict): Observation dictionary. All observations\n                reported inside of the ``with`` statement are written to this\n                dictionary.\n\n        \"\"\"\n        old = self.observation\n        self.observation = observation\n        self.__enter__()\n        yield\n        self.__exit__(None, None, None)\n        self.observation = old\n\n    def add_observer(self, name, observer):\n        \"\"\"Registers an observer of values.\n\n        Observer defines a scope of names for observed values. Values observed\n        with the observer are registered with names prefixed by the observer\n        name.\n\n        Args:\n            name (str): Name of the observer.\n            observer: The observer object. Note that the reporter distinguishes\n                the observers by their object ids (i.e., ``id(owner)``), rather\n                than the object equality.\n\n        \"\"\"\n        self._observer_names[id(observer)] = name\n\n    def add_observers(self, prefix, observers):\n        \"\"\"Registers multiple observers at once.\n\n        This is a convenient method to register multiple objects at once.\n\n        Args:\n            prefix (str): Prefix of each name of observers.\n            observers: Iterator of name and observer pairs.\n\n        \"\"\"\n        for name, observer in observers:\n            self._observer_names[id(observer)] = prefix + name\n\n    def report(self, values, observer=None):\n        \"\"\"Reports observed values.\n\n        The values are written with the key, prefixed by the name of the\n        observer object if given.\n\n        Args:\n            values (dict): Dictionary of observed values.\n            observer: Observer object. Its object ID is used to retrieve the\n                observer name, which is used as the prefix of the registration\n                name of the observed value.\n\n        \"\"\"\n        if observer is not None:\n            observer_id = id(observer)\n            if observer_id not in self._observer_names:\n                raise KeyError(\n                    'Given observer is not registered to the reporter.')\n            observer_name = self._observer_names[observer_id]\n            for key, value in six.iteritems(values):\n                name = '%s/%s' % (observer_name, key)\n                self.observation[name] = value\n        else:\n            self.observation.update(values)\n\n\n_reporters = []\n\n\ndef get_current_reporter():\n    \"\"\"Returns the current reporter object.\"\"\"\n    return _reporters[-1]\n\n\ndef report(values, observer=None):\n    \"\"\"Reports observed values with the current reporter object.\n\n    Any reporter object can be set current by the ``with`` statement. This\n    function calls the :meth:`Report.report` method of the current reporter.\n    If no reporter object is current, this function does nothing.\n\n    .. admonition:: Example\n\n       The most typical example is a use within links and chains. Suppose that\n       a link is registered to the current reporter as an observer (for\n       example, the target link of the optimizer is automatically registered to\n       the reporter of the :class:`~chainer.training.Trainer`). We can report\n       some values from the link as follows::\n\n          class MyRegressor(chainer.Chain):\n              def __init__(self, predictor):\n                  super(MyRegressor, self).__init__(predictor=predictor)\n\n              def __call__(self, x, y):\n                  # This chain just computes the mean absolute and squared\n                  # errors between the prediction and y.\n                  pred = self.predictor(x)\n                  abs_error = F.sum(F.abs(pred - y)) / len(x.data)\n                  loss = F.mean_squared_error(pred, y)\n\n                  # Report the mean absolute and squared errors.\n                  report({'abs_error': abs_error, 'squared_error': loss}, self)\n\n                  return loss\n\n       If the link is named ``'main'`` in the hierarchy (which is the default\n       name of the target link in the\n       :class:`~chainer.training.StandardUpdater`), these reported values are\n       named ``'main/abs_error'`` and ``'main/squared_error'``. If these values\n       are reported inside the :class:`~chainer.training.extension.Evaluator`\n       extension, ``'validation/'`` is added at the head of the link name, thus\n       the item names are changed to ``'validation/main/abs_error'`` and\n       ``'validation/main/squared_error'`` (``'validation'`` is the default\n       name of the Evaluator extension).\n\n    Args:\n        values (dict): Dictionary of observed values.\n        observer: Observer object. Its object ID is used to retrieve the\n            observer name, which is used as the prefix of the registration name\n            of the observed value.\n\n    \"\"\"\n    if _reporters:\n        current = _reporters[-1]\n        current.report(values, observer)\n\n\n@contextlib.contextmanager\ndef report_scope(observation):\n    \"\"\"Returns a report scope with the current reporter.\n\n    This is equivalent to ``get_current_reporter().scope(observation)``,\n    except that it does not make the reporter current redundantly.\n\n    \"\"\"\n    current = _reporters[-1]\n    old = current.observation\n    current.observation = observation\n    yield\n    current.observation = old\n\n\nclass Summary(object):\n\n    \"\"\"Online summarization of a sequence of scalars.\n\n    Summary computes the statistics of given scalars online.\n\n    \"\"\"\n    def __init__(self):\n        self._x = 0\n        self._x2 = 0\n        self._n = 0\n\n    def add(self, value):\n        \"\"\"Adds a scalar value.\n\n        Args:\n            value: Scalar value to accumulate. It is either a NumPy scalar or\n                a zero-dimensional array (on CPU or GPU).\n\n        \"\"\"\n        with cuda.get_device(value):\n            self._x += value\n            self._x2 += value * value\n            self._n += 1\n\n    def compute_mean(self):\n        \"\"\"Computes the mean.\"\"\"\n        x, n = self._x, self._n\n        with cuda.get_device(x):\n            return x / n\n\n    def make_statistics(self):\n        \"\"\"Computes and returns the mean and standard deviation values.\n\n        Returns:\n            tuple: Mean and standard deviation values.\n\n        \"\"\"\n        x, n = self._x, self._n\n        xp = cuda.get_array_module(x)\n        with cuda.get_device(x):\n            mean = x / n\n            var = self._x2 / n - mean * mean\n            std = xp.sqrt(var, var)\n            return mean, std\n\n\nclass DictSummary(object):\n\n    \"\"\"Online summarization of a sequence of dictionaries.\n\n    ``DictSummary`` computes the statistics of a given set of scalars online.\n    It only computes the statistics for scalar values and variables of scalar\n    values in the dictionaries.\n\n    \"\"\"\n    def __init__(self):\n        self._summaries = collections.defaultdict(Summary)\n\n    def add(self, d):\n        \"\"\"Adds a dictionary of scalars.\n\n        Args:\n            d (dict): Dictionary of scalars to accumulate. Only elements of\n               scalars, zero-dimensional arrays, and variables of\n               zero-dimensional arrays are accumulated.\n\n        \"\"\"\n        summaries = self._summaries\n        for k, v in six.iteritems(d):\n            if isinstance(v, variable.Variable):\n                v = v.data\n            if numpy.isscalar(v) or getattr(v, 'ndim', -1) == 0:\n                summaries[k].add(v)\n\n    def compute_mean(self):\n        \"\"\"Creates a dictionary of mean values.\n\n        It returns a single dictionary that holds a mean value for each entry\n        added to the summary.\n\n        Returns:\n            dict: Dictionary of mean values.\n\n        \"\"\"\n        return {name: summary.compute_mean()\n                for name, summary in six.iteritems(self._summaries)}\n\n    def make_statistics(self):\n        \"\"\"Creates a dictionary of statistics.\n\n        It returns a single dictionary that holds mean and standard deviation\n        values for every entry added to the summary. For an entry of name\n        ``'key'``, these values are added to the dictionary by names ``'key'``\n        and ``'key.std'``, respectively.\n\n        Returns:\n            dict: Dictionary of statistics of all entries.\n\n        \"\"\"\n        stats = {}\n        for name, summary in six.iteritems(self._summaries):\n            mean, std = summary.make_statistics()\n            stats[name] = mean\n            stats[name + '.std'] = std\n\n        return stats\n", "path": "chainer/reporter.py"}], "after_files": [{"content": "import collections\nimport contextlib\n\nimport numpy\nimport six\n\nfrom chainer import cuda\nfrom chainer import variable\n\n\nclass Reporter(object):\n\n    \"\"\"Object to which observed values are reported.\n\n    Reporter is used to collect values that users want to watch. The reporter\n    object holds a mapping from value names to the actually observed values.\n    We call this mapping `observations`.\n\n    When a value is passed to the reporter, an object called `observer` can be\n    optionally attached. In this case, the name of the observer is added as the\n    prefix of the value name. The observer name should be registered\n    beforehand.\n\n    See the following example::\n\n       >>> from chainer import Reporter, report, report_scope\n       >>>\n       >>> reporter = Reporter()\n       >>> observer = object()  # it can be an arbitrary (reference) object\n       >>> reporter.add_observer('my_observer:', observer)\n       >>> observation = {}\n       >>> with reporter.scope(observation):\n       ...     reporter.report({'x': 1}, observer)\n       ...\n       >>> observation\n       {'my_observer:x': 1}\n\n    There are also a global API to add values::\n\n       >>> observation = {}\n       >>> with report_scope(observation):\n       ...     report({'x': 1}, observer)\n       ...\n       >>> observation\n       {'my_observer:x': 1}\n\n    The most important application of Reporter is to report observed values\n    from each link or chain in the training and validation procedures.\n    :class:`~chainer.training.Trainer` and some extensions prepare their own\n    Reporter object with the hierarchy of the target link registered as\n    observers. We can use :func:`report` function inside any links and chains\n    to report the observed values (e.g., training loss, accuracy, activation\n    statistics, etc.).\n\n    Attributes:\n        observation: Dictionary of observed values.\n\n    \"\"\"\n    def __init__(self):\n        self._observer_names = {}\n        self.observation = {}\n\n    def __enter__(self):\n        \"\"\"Makes this reporter object current.\"\"\"\n        _reporters.append(self)\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        \"\"\"Recovers the previous reporter object to the current.\"\"\"\n        _reporters.pop()\n\n    @contextlib.contextmanager\n    def scope(self, observation):\n        \"\"\"Creates a scope to report observed values to ``observation``.\n\n        This is a context manager to be passed to ``with`` statements. In this\n        scope, the observation dictionary is changed to the given one.\n\n        It also makes this reporter object current.\n\n        Args:\n            observation (dict): Observation dictionary. All observations\n                reported inside of the ``with`` statement are written to this\n                dictionary.\n\n        \"\"\"\n        old = self.observation\n        self.observation = observation\n        self.__enter__()\n        yield\n        self.__exit__(None, None, None)\n        self.observation = old\n\n    def add_observer(self, name, observer):\n        \"\"\"Registers an observer of values.\n\n        Observer defines a scope of names for observed values. Values observed\n        with the observer are registered with names prefixed by the observer\n        name.\n\n        Args:\n            name (str): Name of the observer.\n            observer: The observer object. Note that the reporter distinguishes\n                the observers by their object ids (i.e., ``id(owner)``), rather\n                than the object equality.\n\n        \"\"\"\n        self._observer_names[id(observer)] = name\n\n    def add_observers(self, prefix, observers):\n        \"\"\"Registers multiple observers at once.\n\n        This is a convenient method to register multiple objects at once.\n\n        Args:\n            prefix (str): Prefix of each name of observers.\n            observers: Iterator of name and observer pairs.\n\n        \"\"\"\n        for name, observer in observers:\n            self._observer_names[id(observer)] = prefix + name\n\n    def report(self, values, observer=None):\n        \"\"\"Reports observed values.\n\n        The values are written with the key, prefixed by the name of the\n        observer object if given.\n\n        Args:\n            values (dict): Dictionary of observed values.\n            observer: Observer object. Its object ID is used to retrieve the\n                observer name, which is used as the prefix of the registration\n                name of the observed value.\n\n        \"\"\"\n        if observer is not None:\n            observer_id = id(observer)\n            if observer_id not in self._observer_names:\n                raise KeyError(\n                    'Given observer is not registered to the reporter.')\n            observer_name = self._observer_names[observer_id]\n            for key, value in six.iteritems(values):\n                name = '%s/%s' % (observer_name, key)\n                self.observation[name] = value\n        else:\n            self.observation.update(values)\n\n\n_reporters = []\n\n\ndef get_current_reporter():\n    \"\"\"Returns the current reporter object.\"\"\"\n    return _reporters[-1]\n\n\ndef report(values, observer=None):\n    \"\"\"Reports observed values with the current reporter object.\n\n    Any reporter object can be set current by the ``with`` statement. This\n    function calls the :meth:`Report.report` method of the current reporter.\n    If no reporter object is current, this function does nothing.\n\n    .. admonition:: Example\n\n       The most typical example is a use within links and chains. Suppose that\n       a link is registered to the current reporter as an observer (for\n       example, the target link of the optimizer is automatically registered to\n       the reporter of the :class:`~chainer.training.Trainer`). We can report\n       some values from the link as follows::\n\n          class MyRegressor(chainer.Chain):\n              def __init__(self, predictor):\n                  super(MyRegressor, self).__init__(predictor=predictor)\n\n              def __call__(self, x, y):\n                  # This chain just computes the mean absolute and squared\n                  # errors between the prediction and y.\n                  pred = self.predictor(x)\n                  abs_error = F.sum(F.abs(pred - y)) / len(x.data)\n                  loss = F.mean_squared_error(pred, y)\n\n                  # Report the mean absolute and squared errors.\n                  report({'abs_error': abs_error, 'squared_error': loss}, self)\n\n                  return loss\n\n       If the link is named ``'main'`` in the hierarchy (which is the default\n       name of the target link in the\n       :class:`~chainer.training.StandardUpdater`), these reported values are\n       named ``'main/abs_error'`` and ``'main/squared_error'``. If these values\n       are reported inside the :class:`~chainer.training.extension.Evaluator`\n       extension, ``'validation/'`` is added at the head of the link name, thus\n       the item names are changed to ``'validation/main/abs_error'`` and\n       ``'validation/main/squared_error'`` (``'validation'`` is the default\n       name of the Evaluator extension).\n\n    Args:\n        values (dict): Dictionary of observed values.\n        observer: Observer object. Its object ID is used to retrieve the\n            observer name, which is used as the prefix of the registration name\n            of the observed value.\n\n    \"\"\"\n    if _reporters:\n        current = _reporters[-1]\n        current.report(values, observer)\n\n\n@contextlib.contextmanager\ndef report_scope(observation):\n    \"\"\"Returns a report scope with the current reporter.\n\n    This is equivalent to ``get_current_reporter().scope(observation)``,\n    except that it does not make the reporter current redundantly.\n\n    \"\"\"\n    current = _reporters[-1]\n    old = current.observation\n    current.observation = observation\n    yield\n    current.observation = old\n\n\ndef _get_device(x):\n    if numpy.isscalar(x):\n        return cuda.DummyDevice\n    else:\n        return cuda.get_device(x)\n\n\nclass Summary(object):\n\n    \"\"\"Online summarization of a sequence of scalars.\n\n    Summary computes the statistics of given scalars online.\n\n    \"\"\"\n    def __init__(self):\n        self._x = 0\n        self._x2 = 0\n        self._n = 0\n\n    def add(self, value):\n        \"\"\"Adds a scalar value.\n\n        Args:\n            value: Scalar value to accumulate. It is either a NumPy scalar or\n                a zero-dimensional array (on CPU or GPU).\n\n        \"\"\"\n        with _get_device(value):\n            self._x += value\n            self._x2 += value * value\n            self._n += 1\n\n    def compute_mean(self):\n        \"\"\"Computes the mean.\"\"\"\n        x, n = self._x, self._n\n        with _get_device(x):\n            return x / n\n\n    def make_statistics(self):\n        \"\"\"Computes and returns the mean and standard deviation values.\n\n        Returns:\n            tuple: Mean and standard deviation values.\n\n        \"\"\"\n        x, n = self._x, self._n\n        xp = cuda.get_array_module(x)\n        with _get_device(x):\n            mean = x / n\n            var = self._x2 / n - mean * mean\n            std = xp.sqrt(var)\n            return mean, std\n\n\nclass DictSummary(object):\n\n    \"\"\"Online summarization of a sequence of dictionaries.\n\n    ``DictSummary`` computes the statistics of a given set of scalars online.\n    It only computes the statistics for scalar values and variables of scalar\n    values in the dictionaries.\n\n    \"\"\"\n    def __init__(self):\n        self._summaries = collections.defaultdict(Summary)\n\n    def add(self, d):\n        \"\"\"Adds a dictionary of scalars.\n\n        Args:\n            d (dict): Dictionary of scalars to accumulate. Only elements of\n               scalars, zero-dimensional arrays, and variables of\n               zero-dimensional arrays are accumulated.\n\n        \"\"\"\n        summaries = self._summaries\n        for k, v in six.iteritems(d):\n            if isinstance(v, variable.Variable):\n                v = v.data\n            if numpy.isscalar(v) or getattr(v, 'ndim', -1) == 0:\n                summaries[k].add(v)\n\n    def compute_mean(self):\n        \"\"\"Creates a dictionary of mean values.\n\n        It returns a single dictionary that holds a mean value for each entry\n        added to the summary.\n\n        Returns:\n            dict: Dictionary of mean values.\n\n        \"\"\"\n        return {name: summary.compute_mean()\n                for name, summary in six.iteritems(self._summaries)}\n\n    def make_statistics(self):\n        \"\"\"Creates a dictionary of statistics.\n\n        It returns a single dictionary that holds mean and standard deviation\n        values for every entry added to the summary. For an entry of name\n        ``'key'``, these values are added to the dictionary by names ``'key'``\n        and ``'key.std'``, respectively.\n\n        Returns:\n            dict: Dictionary of statistics of all entries.\n\n        \"\"\"\n        stats = {}\n        for name, summary in six.iteritems(self._summaries):\n            mean, std = summary.make_statistics()\n            stats[name] = mean\n            stats[name + '.std'] = std\n\n        return stats\n", "path": "chainer/reporter.py"}]}