Path: blob/master/Week 7/Programming Assignment - 6/ex6/svmPredict.m
863 views
function pred = svmPredict(model, X)1%SVMPREDICT returns a vector of predictions using a trained SVM model2%(svmTrain).3% pred = SVMPREDICT(model, X) returns a vector of predictions using a4% trained SVM model (svmTrain). X is a mxn matrix where there each5% example is a row. model is a svm model returned from svmTrain.6% predictions pred is a m x 1 column of predictions of {0, 1} values.7%89% Check if we are getting a column vector, if so, then assume that we only10% need to do prediction for a single example11if (size(X, 2) == 1)12% Examples should be in rows13X = X';14end1516% Dataset17m = size(X, 1);18p = zeros(m, 1);19pred = zeros(m, 1);2021if strcmp(func2str(model.kernelFunction), 'linearKernel')22% We can use the weights and bias directly if working with the23% linear kernel24p = X * model.w + model.b;25elseif strfind(func2str(model.kernelFunction), 'gaussianKernel')26% Vectorized RBF Kernel27% This is equivalent to computing the kernel on every pair of examples28X1 = sum(X.^2, 2);29X2 = sum(model.X.^2, 2)';30K = bsxfun(@plus, X1, bsxfun(@plus, X2, - 2 * X * model.X'));31K = model.kernelFunction(1, 0) .^ K;32K = bsxfun(@times, model.y', K);33K = bsxfun(@times, model.alphas', K);34p = sum(K, 2);35else36% Other Non-linear kernel37for i = 1:m38prediction = 0;39for j = 1:size(model.X, 1)40prediction = prediction + ...41model.alphas(j) * model.y(j) * ...42model.kernelFunction(X(i,:)', model.X(j,:)');43end44p(i) = prediction + model.b;45end46end4748% Convert predictions into 0 / 149pred(p >= 0) = 1;50pred(p < 0) = 0;5152end53545556