public BootstrapResult Compute()
{
if (Fitting == null)
throw new InvalidOperationException("Fitting function must have been previously defined.");
var models = new BootstrapValues[Subsamples.Length];
if (RunInParallel)
{
Parallel.For(0, Subsamples.Length, i =>
{
int[] trainingSet, validationSet;
// Create training and validation sets
CreatePartitions(i, out trainingSet, out validationSet);
// Fit and evaluate the model
models[i] = fitting(trainingSet, validationSet);
});
}
else
{
for (int i = 0; i < Subsamples.Length; i++)
{
int[] trainingSet, validationSet;
// Create training and validation sets
CreatePartitions(i, out trainingSet, out validationSet);
// Fit and evaluate the model
models[i] = fitting(trainingSet, validationSet);
}
}
// Return cross-validation statistics
return new BootstrapResult(this, models);
}
public void BootstrapConstructorTest2() { // Example from Masters, 1995 // Assume a small dataset double[] data = { 3, 5, 2, 1, 7 }; // indices { 0, 1, 2, 3, 4 } int[][] resamplings = { new [] { 4, 0, 2, 0, 3 }, // indices of { 7, 3, 2, 3, 1 } new [] { 1, 3, 3, 0, 4 }, // indices of { 5, 1, 1, 3, 7 } new [] { 2, 2, 4, 3, 0 }, // indices of { 2, 2, 7, 1, 3 } }; Bootstrap target = new Bootstrap(data.Length, resamplings); target.Fitting = (int[] trainingSamples, int[] validationSamples) => { double[] subsample = data.Submatrix(trainingSamples); double mean = subsample.Mean(); return new BootstrapValues(mean, 0); }; var result = target.Compute(); double actualMean = result.Training.Mean; double actualVar = result.Training.Variance; Assert.AreEqual(3.2, actualMean, 1e-10); Assert.AreEqual(0.04, actualVar, 1e-10); }