Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created May 14, 2012 12:14
Show Gist options
  • Save sinairv/2693647 to your computer and use it in GitHub Desktop.
Save sinairv/2693647 to your computer and use it in GitHub Desktop.
A Helper Method for Performing K-Fold Cross Validation
private static readonly Random s_rnd = new Random();
/// <summary>
/// Divides numbers from 0 to length - 1 into k random folds.
/// This method is a helper method for K-fold cross validaiton.
/// </summary>
/// <param name="length">The length of the data to fold into k divisions. </param>
/// <param name="k">number of divisions</param>
/// <returns>K arrays of indices. Each of the arrays contain 0-based indices of the
/// data to be put in each division.</returns>
public static int[][] RandomlyFoldIndices(int length, int k)
{
var inds = new int[length];
// initialize indicies
for (int i = 0; i < length; i++)
{
inds[i] = i;
}
// now shuffle indicies for 2 times
for (int st = 0; st < 2; st++)
{
for (int i = 0; i < length - 1; i++)
{
// r is in [i + 1, length)
int r = i + 1 + s_rnd.Next(0, length - i - 1);
int temp = inds[i];
inds[i] = inds[r];
inds[r] = temp;
}
}
// now divide the shuffled indices into folds
var folds = new int[k][];
int foldLength = length / k;
int lastFoldLength = length - ((k - 1) * foldLength);
for (int ki = 0; ki < k; ki++)
{
if (ki < k - 1)
{
folds[ki] = new int[foldLength];
Array.Copy(inds, ki * foldLength, folds[ki], 0, foldLength);
}
else
{
folds[ki] = new int[lastFoldLength];
Array.Copy(inds, ki * foldLength, folds[ki], 0, lastFoldLength);
}
Array.Sort(folds[ki]);
}
return folds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment