Sigmoid.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.analysis.function;

  22. import java.util.Arrays;

  23. import org.hipparchus.analysis.ParametricUnivariateFunction;
  24. import org.hipparchus.analysis.differentiation.Derivative;
  25. import org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction;
  26. import org.hipparchus.exception.MathIllegalArgumentException;
  27. import org.hipparchus.exception.NullArgumentException;
  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.MathUtils;

  30. /**
  31.  * <a href="http://en.wikipedia.org/wiki/Sigmoid_function">
  32.  *  Sigmoid</a> function.
  33.  * It is the inverse of the {@link Logit logit} function.
  34.  * A more flexible version, the generalised logistic, is implemented
  35.  * by the {@link Logistic} class.
  36.  *
  37.  */
  38. public class Sigmoid implements UnivariateDifferentiableFunction {
  39.     /** Lower asymptote. */
  40.     private final double lo;
  41.     /** Higher asymptote. */
  42.     private final double hi;

  43.     /**
  44.      * Usual sigmoid function, where the lower asymptote is 0 and the higher
  45.      * asymptote is 1.
  46.      */
  47.     public Sigmoid() {
  48.         this(0, 1);
  49.     }

  50.     /**
  51.      * Sigmoid function.
  52.      *
  53.      * @param lo Lower asymptote.
  54.      * @param hi Higher asymptote.
  55.      */
  56.     public Sigmoid(double lo,
  57.                    double hi) {
  58.         this.lo = lo;
  59.         this.hi = hi;
  60.     }

  61.     /** {@inheritDoc} */
  62.     @Override
  63.     public double value(double x) {
  64.         return value(x, lo, hi);
  65.     }

  66.     /**
  67.      * Parametric function where the input array contains the parameters of
  68.      * the {@link Sigmoid#Sigmoid(double,double) sigmoid function}, ordered
  69.      * as follows:
  70.      * <ul>
  71.      *  <li>Lower asymptote</li>
  72.      *  <li>Higher asymptote</li>
  73.      * </ul>
  74.      */
  75.     public static class Parametric implements ParametricUnivariateFunction {

  76.         /** Empty constructor.
  77.          * <p>
  78.          * This constructor is not strictly necessary, but it prevents spurious
  79.          * javadoc warnings with JDK 18 and later.
  80.          * </p>
  81.          * @since 3.0
  82.          */
  83.         public Parametric() { // NOPMD - unnecessary constructor added intentionally to make javadoc happy
  84.             // nothing to do
  85.         }

  86.         /**
  87.          * Computes the value of the sigmoid at {@code x}.
  88.          *
  89.          * @param x Value for which the function must be computed.
  90.          * @param param Values of lower asymptote and higher asymptote.
  91.          * @return the value of the function.
  92.          * @throws NullArgumentException if {@code param} is {@code null}.
  93.          * @throws MathIllegalArgumentException if the size of {@code param} is
  94.          * not 2.
  95.          */
  96.         @Override
  97.         public double value(double x, double ... param)
  98.             throws MathIllegalArgumentException, NullArgumentException {
  99.             validateParameters(param);
  100.             return Sigmoid.value(x, param[0], param[1]);
  101.         }

  102.         /**
  103.          * Computes the value of the gradient at {@code x}.
  104.          * The components of the gradient vector are the partial
  105.          * derivatives of the function with respect to each of the
  106.          * <em>parameters</em> (lower asymptote and higher asymptote).
  107.          *
  108.          * @param x Value at which the gradient must be computed.
  109.          * @param param Values for lower asymptote and higher asymptote.
  110.          * @return the gradient vector at {@code x}.
  111.          * @throws NullArgumentException if {@code param} is {@code null}.
  112.          * @throws MathIllegalArgumentException if the size of {@code param} is
  113.          * not 2.
  114.          */
  115.         @Override
  116.         public double[] gradient(double x, double ... param)
  117.             throws MathIllegalArgumentException, NullArgumentException {
  118.             validateParameters(param);

  119.             final double invExp1 = 1 / (1 + FastMath.exp(-x));

  120.             return new double[] { 1 - invExp1, invExp1 };
  121.         }

  122.         /**
  123.          * Validates parameters to ensure they are appropriate for the evaluation of
  124.          * the {@link #value(double,double[])} and {@link #gradient(double,double[])}
  125.          * methods.
  126.          *
  127.          * @param param Values for lower and higher asymptotes.
  128.          * @throws NullArgumentException if {@code param} is {@code null}.
  129.          * @throws MathIllegalArgumentException if the size of {@code param} is
  130.          * not 2.
  131.          */
  132.         private void validateParameters(double[] param)
  133.             throws MathIllegalArgumentException, NullArgumentException {
  134.             MathUtils.checkNotNull(param);
  135.             MathUtils.checkDimension(param.length, 2);
  136.         }
  137.     }

  138.     /**
  139.      * @param x Value at which to compute the sigmoid.
  140.      * @param lo Lower asymptote.
  141.      * @param hi Higher asymptote.
  142.      * @return the value of the sigmoid function at {@code x}.
  143.      */
  144.     private static double value(double x,
  145.                                 double lo,
  146.                                 double hi) {
  147.         return lo + (hi - lo) / (1 + FastMath.exp(-x));
  148.     }

  149.     /** {@inheritDoc}
  150.      */
  151.     @Override
  152.     public <T extends Derivative<T>> T value(T t)
  153.         throws MathIllegalArgumentException {

  154.         double[] f = new double[t.getOrder() + 1];
  155.         final double exp = FastMath.exp(-t.getValue());
  156.         if (Double.isInfinite(exp)) {

  157.             // special handling near lower boundary, to avoid NaN
  158.             f[0] = lo;
  159.             Arrays.fill(f, 1, f.length, 0.0);

  160.         } else {

  161.             // the nth order derivative of sigmoid has the form:
  162.             // dn(sigmoid(x)/dxn = P_n(exp(-x)) / (1+exp(-x))^(n+1)
  163.             // where P_n(t) is a degree n polynomial with normalized higher term
  164.             // P_0(t) = 1, P_1(t) = t, P_2(t) = t^2 - t, P_3(t) = t^3 - 4 t^2 + t...
  165.             // the general recurrence relation for P_n is:
  166.             // P_n(x) = n t P_(n-1)(t) - t (1 + t) P_(n-1)'(t)
  167.             final double[] p = new double[f.length];

  168.             final double inv   = 1 / (1 + exp);
  169.             double coeff = hi - lo;
  170.             for (int n = 0; n < f.length; ++n) {

  171.                 // update and evaluate polynomial P_n(t)
  172.                 double v = 0;
  173.                 p[n] = 1;
  174.                 for (int k = n; k >= 0; --k) {
  175.                     v = v * exp + p[k];
  176.                     if (k > 1) {
  177.                         p[k - 1] = (n - k + 2) * p[k - 2] - (k - 1) * p[k - 1];
  178.                     } else {
  179.                         p[0] = 0;
  180.                     }
  181.                 }

  182.                 coeff *= inv;
  183.                 f[n]   = coeff * v;

  184.             }

  185.             // fix function value
  186.             f[0] += lo;

  187.         }

  188.         return t.compose(f);

  189.     }

  190. }