com.asher_stern.crf.function.optimization.NegatedFunction Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of CRF Show documentation
Show all versions of CRF Show documentation
Implementation of linear-chain Conditional Random Fields (CRF) in pure Java
package com.asher_stern.crf.function.optimization;
import com.asher_stern.crf.function.DerivableFunction;
import com.asher_stern.crf.function.Function;
import com.asher_stern.crf.function.TwiceDerivableFunction;
import com.asher_stern.crf.utilities.CrfException;
/**
* Represent "-f(x)" for a given function "f(x)".
*
* This negated function can be used when maximization of a function is needed, but a minimization algorithm is available.
* Just minimize "-f(x)", and the resulting "x" is the point of the maximum for "f(x)".
*
* @author Asher Stern
* Date: Nov 6, 2014
*
*/
public class NegatedFunction extends TwiceDerivableFunction
{
public static NegatedFunction fromFunction(Function function)
{
return new NegatedFunction(function, null, null);
}
public static NegatedFunction fromDerivableFunction(DerivableFunction derivableFunction)
{
return new NegatedFunction(null,derivableFunction,null);
}
public static NegatedFunction fromTwiceDerivableFunction(TwiceDerivableFunction twiceDerivableFunction)
{
return new NegatedFunction(null,null,twiceDerivableFunction);
}
@Override
public int size()
{
return this.theSize;
}
@Override
public double value(double[] point)
{
if (function!=null){return -function.value(point);}
else if (derivableFunction!=null){return -derivableFunction.value(point);}
else if (twiceDerivableFunction!=null){return -twiceDerivableFunction.value(point);}
else throw new CrfException("BUG");
}
@Override
public double[] gradient(double[] point)
{
if (derivableFunction!=null){return negate(derivableFunction.gradient(point));}
else if (twiceDerivableFunction!=null){return negate(twiceDerivableFunction.gradient(point));}
else throw new CrfException("BUG");
}
@Override
public double[][] hessian(double[] point)
{
if (twiceDerivableFunction!=null)
{
double[][] ret = new double[theSize][theSize];
double[][] originalHessian = twiceDerivableFunction.hessian(point);
for (int i=0;i