public void ExampleTest()
{
// Suppose we would like to map the continuous values in the
// second column to the integer values in the first column.
double[,] data =
{
{ -40, -21142.1111111111 },
{ -30, -21330.1111111111 },
{ -20, -12036.1111111111 },
{ -10, 7255.3888888889 },
{ 0, 32474.8888888889 },
{ 10, 32474.8888888889 },
{ 20, 9060.8888888889 },
{ 30, -11628.1111111111 },
{ 40, -15129.6111111111 },
};
// Extract inputs and outputs
double[][] inputs = data.GetColumn(0).ToJagged();
double[] outputs = data.GetColumn(1);
// Create a Nonlinear regression using
var regression = new NonlinearRegression(3,
// Let's assume a quadratic model function: ax² + bx + c
function: (w, x) => w[0] * x[0] * x[0] + w[1] * x[0] + w[2],
// Derivative in respect to the weights:
gradient: (w, x, r) =>
{
r[0] = 2 * w[0]; // w.r.t a: 2a
r[1] = w[1]; // w.r.t b: b
r[2] = w[2]; // w.r.t c: 0
}
);
// Create a non-linear least squares teacher
var nls = new NonlinearLeastSquares(regression);
// Initialize to some random values
regression.Coefficients[0] = 4.2;
regression.Coefficients[1] = 0.3;
regression.Coefficients[2] = 1;
// Run the function estimation algorithm
double error = Double.PositiveInfinity;
for (int i = 0; i < 100; i++)
error = nls.Run(inputs, outputs);
// Use the function to compute the input values
double[] predict = inputs.Apply(regression.Compute);
Assert.IsTrue(nls.Algorithm is LevenbergMarquardt);
Assert.AreEqual(1318374605.8436923d, error);
Assert.AreEqual(-12.025250289329851, regression.Coefficients[0], 1e-3);
Assert.AreEqual(-0.082208180694676766, regression.Coefficients[1], 1e-3);
Assert.AreEqual(-0.27402726898225627, regression.Coefficients[2], 1e-3);
Assert.AreEqual(-19237.386162968953, predict[0]);
Assert.AreEqual(-10820.533042245008, predict[1]);
Assert.AreEqual(-4808.7299793870288, predict[2]);
Assert.AreEqual(-1203.6211380089139, predict[5]);
}