crossval
statistics: results = crossval (f, X, y)
statistics: results = crossval (f, X, y, name, value)
Perform cross validation on given data.
f should be a function that takes 4 inputs xtrain, ytrain,
xtest, ytest, fits a model based on xtrain, ytrain,
applies the fitted model to xtest, and returns a goodness of fit
measure based on comparing the predicted and actual ytest.
crossval returns an array containing the values returned by f
for every cross-validation fold or resampling applied to the given data.
X should be an n by m matrix of predictor values
y should be an n by 1 vector of predicand values
Optional arguments may include name-value pairs as follows:
'KFold''HoldOut''LeaveOut''Partition''Given''stratify''KFold' and
'HoldOut' partitionings attempt to ensure each partition
represents the classes proportionately.'mcreps''HoldOut'. Only one of 'KFold', 'HoldOut', 'LeaveOut',
'Given', 'Partition' should be specified. If none is
specified, the default is 'KFold' with k = 10.
See also: cvpartition
Source Code: crossval
Determine the optimal number of clusters using cross-validation
Declare a function to compute the sum of squared distances between data points and a varying number of clusters.
function D = dist2clusters (X, Y, k)
[Z, Zmu, Zstd] = zscore (X);
[~, C] = kmeans (Z, k);
ZY = (Y - Zmu) ./ Zstd;
d = pdist2 (C, ZY, 'euclidean', 'Smallest', 1);
D = sum (d .^ 2);
endfunction
load fisheriris
for k = 1:8
fcn = @(X, Y) dist2clusters (X, Y, k);
distances = crossval (fcn, meas);
cvdist(k) = sum (distances);
endfor
plot (cvdist)
xlabel ('Number of Clusters')
ylabel ('CV Sum of Squared Distances')
xlim ([1,8]);