|
| 1 | +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +""" |
| 17 | + Class of all kinds of Average. |
| 18 | +
|
| 19 | + All Averages are accomplished via Python totally. |
| 20 | + They do not change Paddle's Program, nor do anything to |
| 21 | + modify NN model's configuration. They are completely |
| 22 | + wrappers of Python functions. |
| 23 | +""" |
| 24 | + |
| 25 | + |
| 26 | +def _is_number_(var): |
| 27 | + return isinstance(var, int) or isinstance(var, float) or (isinstance( |
| 28 | + var, np.ndarray) and var.shape == (1, )) |
| 29 | + |
| 30 | + |
| 31 | +def _is_number_or_matrix_(var): |
| 32 | + return _is_number_(var) or isinstance(var, np.ndarray) |
| 33 | + |
| 34 | + |
| 35 | +class WeightedAverage(object): |
| 36 | + def __init__(self): |
| 37 | + self.reset() |
| 38 | + |
| 39 | + def reset(self): |
| 40 | + self.numerator = None |
| 41 | + self.denominator = None |
| 42 | + |
| 43 | + def add(self, value, weight): |
| 44 | + if not _is_number_or_matrix_(value): |
| 45 | + raise ValueError( |
| 46 | + "The 'value' must be a number(int, float) or a numpy ndarray.") |
| 47 | + if not _is_number_(weight): |
| 48 | + raise ValueError("The 'weight' must be a number(int, float).") |
| 49 | + |
| 50 | + if self.numerator is None or self.denominator is None: |
| 51 | + self.numerator = value * weight |
| 52 | + self.denominator = weight |
| 53 | + else: |
| 54 | + self.numerator += value * weight |
| 55 | + self.denominator += weight |
| 56 | + |
| 57 | + def eval(self): |
| 58 | + if self.numerator is None or self.denominator is None: |
| 59 | + raise ValueError( |
| 60 | + "There is no data to be averaged in WeightedAverage.") |
| 61 | + return self.numerator / self.denominator |
0 commit comments