Geometric Mean

The geometric mean is another utility function used for calculating compound interest rates and analyzing investment returns. In machine learning, it is often used for averaging ratios or rates, such as in the geometric mean class probability for multi-class classification. The formal definition is provided below.\

GM(x1,x2,,xn)=i=1nxin s.t. xi>0  i\operatorname{GM}(x_1, x_2, \ldots, x_n) = \sqrt[n]{\prod_{i=1}^n x_i} \ \\ s.t. \ x_i > 0 \ \forall \ i

To implement the GeometricMean function, see the method signature below. Precision represents the number of decimal places and can be set between 0 and 18. It is applied to nums, weights and the output.

function GeometricMean(int256[] calldata nums, uint256[] calldata weights, uint8 precision) external returns (int256);

Under the hood, the following functions are utilized directly in the Neural client.

func (con *NeuralMath) GeometricMean(gas *big.Int, nums []*big.Int, weights []*big.Int, precision uint8) (*big.Int, error, *big.Int) {
	mul, err := validatePrecision(precision)
	if err != nil {
		return nil, err, nil
	}
	if len(nums) != len(weights) {
		return nil, errors.New("len(nums) != len(weights)"), nil
	}
	w, err := toFloats(weights, mul)
	if err != nil {
		return nil, err, nil
	}
	floats, err := toFloats(nums, mul)
	if err != nil {
		return nil, err, nil
	}
	var mean big.Int
	big.NewFloat(stat.GeometricMean(floats, w) * mul).Int(&mean)
	return &mean, nil, nil
}

Last updated