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 * http://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 package org.apache.commons.math4.neuralnet.sofm.util; 19 20 import java.util.function.DoubleUnaryOperator; 21 import java.util.function.LongToDoubleFunction; 22 23 import org.apache.commons.math4.neuralnet.internal.NeuralNetException; 24 25 /** 26 * Decay function whose shape is similar to a sigmoid. 27 * <br> 28 * Class is immutable. 29 * 30 * @since 3.3 31 */ 32 public class QuasiSigmoidDecayFunction implements LongToDoubleFunction { 33 /** Sigmoid. */ 34 private final DoubleUnaryOperator sigmoid; 35 /** See {@link #value(long)}. */ 36 private final double scale; 37 38 /** 39 * Creates an instance. 40 * The function {@code f} will have the following properties: 41 * <ul> 42 * <li>{@code f(0) = initValue}</li> 43 * <li>{@code numCall} is the inflexion point</li> 44 * <li>{@code slope = f'(numCall)}</li> 45 * </ul> 46 * 47 * @param initValue Initial value, i.e. {@link #applyAsDouble(long) applyAsDouble(0)}. 48 * @param slope Value of the function derivative at {@code numCall}. 49 * @param numCall Inflexion point. 50 * @throws IllegalArgumentException if {@code initValue <= 0}, 51 * {@code slope >= 0} or {@code numCall <= 0}. 52 */ 53 public QuasiSigmoidDecayFunction(double initValue, 54 double slope, 55 long numCall) { 56 if (initValue <= 0) { 57 throw new NeuralNetException(NeuralNetException.NOT_STRICTLY_POSITIVE, initValue); 58 } 59 if (slope >= 0) { 60 throw new NeuralNetException(NeuralNetException.TOO_LARGE, slope, 0); 61 } 62 if (numCall <= 1) { 63 throw new NeuralNetException(NeuralNetException.TOO_SMALL, numCall, 1); 64 } 65 66 final double k = initValue; 67 final double m = numCall; 68 final double b = 4 * slope / initValue; 69 sigmoid = x -> k / (1 + Math.exp(b * (m - x))); 70 71 final double y0 = sigmoid.applyAsDouble(0d); 72 scale = k / y0; 73 } 74 75 /** 76 * Computes the value of the learning factor. 77 * 78 * @param numCall Current step of the training task. 79 * @return the value of the function at {@code numCall}. 80 */ 81 @Override 82 public double applyAsDouble(long numCall) { 83 return scale * sigmoid.applyAsDouble((double) numCall); 84 } 85 }