Computes the (weighted) mean of the given values.
| 291 | |
| 292 | |
| 293 | class Mean(Metric): |
| 294 | """Computes the (weighted) mean of the given values.""" |
| 295 | |
| 296 | def __init__(self, name=None, dtype=dtypes.float64, |
| 297 | use_global_variables=False): |
| 298 | super(Mean, self).__init__(name=name, |
| 299 | use_global_variables=use_global_variables) |
| 300 | self.dtype = dtype |
| 301 | |
| 302 | def build(self, *args, **kwargs): |
| 303 | # build() does not use call's arguments, by using *args, **kwargs |
| 304 | # we make it easier to inherit from Mean(). |
| 305 | del args, kwargs |
| 306 | self.numer = self.add_variable(name="numer", shape=(), |
| 307 | dtype=self.dtype, |
| 308 | initializer=init_ops.zeros_initializer) |
| 309 | self.denom = self.add_variable(name="denom", shape=(), |
| 310 | dtype=self.dtype, |
| 311 | initializer=init_ops.zeros_initializer) |
| 312 | |
| 313 | def call(self, values, weights=None): |
| 314 | """Accumulate statistics for computing the mean. |
| 315 | |
| 316 | For example, if values is [1, 3, 5, 7] then the mean is 4. |
| 317 | If the weights were specified as [1, 1, 0, 0] then the mean would be 2. |
| 318 | |
| 319 | Args: |
| 320 | values: Tensor with the per-example value. |
| 321 | weights: Optional weighting of each example. Defaults to 1. |
| 322 | |
| 323 | Returns: |
| 324 | The arguments, for easy chaining. |
| 325 | """ |
| 326 | if weights is None: |
| 327 | self.denom.assign_add( |
| 328 | math_ops.cast(array_ops.identity(array_ops.size(values)), self.dtype)) |
| 329 | values = math_ops.reduce_sum(values) |
| 330 | self.numer.assign_add(math_ops.cast(values, self.dtype)) |
| 331 | else: |
| 332 | weights = math_ops.cast(weights, self.dtype) |
| 333 | self.denom.assign_add(math_ops.reduce_sum(weights)) |
| 334 | values = math_ops.cast(values, self.dtype) * weights |
| 335 | self.numer.assign_add(math_ops.reduce_sum(values)) |
| 336 | if weights is None: |
| 337 | return values |
| 338 | return values, weights |
| 339 | |
| 340 | def result(self, write_summary=True): |
| 341 | """Returns the result of the Metric. |
| 342 | |
| 343 | Args: |
| 344 | write_summary: bool indicating whether to feed the result to the summary |
| 345 | before returning. |
| 346 | Returns: |
| 347 | aggregated metric as float. |
| 348 | Raises: |
| 349 | ValueError: if the optional argument is not bool |
| 350 | """ |
no outgoing calls