MATLAB File Help: cv.SVM/setCustomKernel Index
cv.SVM/setCustomKernel

Initialize with custom kernel

model.setCustomKernel(kernelFunc)

Input

Note

Parts of cv::ml::SVM implementation are thread-parallelized (for example SVM::predict runs a ParallelLoopBody). By using a custom kernel, we would be calling a MATLAB function from C++ code using the MEX-API (mexCallMATLAB), which is not thread-safe. This can cause MATLAB to crash. It is therefore necessary to tempoararily disable threading in OpenCV when using a custom SVM kernel (see cv.Utils.setNumThreads and cv.Utils.getNumThreads).

Example

The following MATLAB function implements a simple linear kernel. The function must be saved in a separate M-file, and placed on the MATLAB path. It receives an Nxd matrix of samples (each row is a sample vector), and another sample 1xd (row vector), and should return a vector Nx1 of inner products between every sample in "vecs" against "another". It will be called during training and prediction by the SVM class.

function results = my_custom_kernel(vecs, another)
    [vcount,n] = size(vecs);
    results = zeros(vcount, 1, 'single');
    for i=1:vcount
        results(i) = dot(vecs(i,:), another);
    end

    % or computed in a vectorized manner as
    %results = sum(bsxfun(@times, vecs, another), 2);

    % or simply written as matrix-vector product
    %results = vecs * another.';
end

We use the custom kernel in the following manner:

% load some data for classification
load fisheriris
samples = meas;
responses = int32(grp2idx(species));

cv.Utils.setNumThreads(1)  % see above note

model = cv.SVM();
model.setCustomKernel('my_custom_kernel');
model.train(samples, responses)
nnz(model.predict(samples) == responses)

cv.Utils.setNumThreads(cv.Utils.getNumberOfCPUs())
See also
Method Details
Access public
Sealed false
Static false