Created
June 17, 2015 20:09
-
-
Save thomasjungblut/624ba7b7f4dc6246659c to your computer and use it in GitHub Desktop.
numerical gradients with fmincg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import de.jungblut.math.DoubleVector; | |
import de.jungblut.math.MathUtils; | |
import de.jungblut.math.dense.DenseDoubleVector; | |
import de.jungblut.math.minimize.CostFunction; | |
import de.jungblut.math.minimize.CostGradientTuple; | |
import de.jungblut.math.minimize.Fmincg; | |
public class FminCGNumericalGradient { | |
static class RealCostFunction implements CostFunction { | |
@Override | |
public CostGradientTuple evaluateCost(DoubleVector input) { | |
// don't set the gradient since it's unknown | |
return new CostGradientTuple(Math.pow(4 - input.get(0), 2) + 10, null); | |
} | |
} | |
static class NumericalGradientCostFunction implements CostFunction { | |
private final CostFunction embeddedFunction; | |
public NumericalGradientCostFunction(CostFunction embeddedFunction) { | |
this.embeddedFunction = embeddedFunction; | |
} | |
@Override | |
public CostGradientTuple evaluateCost(DoubleVector input) { | |
CostGradientTuple cost = embeddedFunction.evaluateCost(input); | |
DoubleVector numericalGradient = MathUtils.numericalGradient(input, | |
embeddedFunction); | |
return new CostGradientTuple(cost.getCost(), numericalGradient); | |
} | |
} | |
public static void main(String[] args) { | |
int startPoint = -5; | |
// start at x=-5 | |
DoubleVector start = new DenseDoubleVector(new double[] { startPoint }); | |
CostFunction func = new NumericalGradientCostFunction( | |
new RealCostFunction()); | |
DoubleVector minimizeFunction = Fmincg.minimizeFunction(func, start, 100, | |
false); | |
System.out.println(minimizeFunction); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment