高斯核函数(相似度函数)
function sim = gaussianKernel(x1, x2, sigma)
%相似度函数
sim=exp(-sum((x1-x2).^2)/(2*sigma*sigma));
end
选择最优参数
function [C, sigma] = dataset3Params(X, y, Xval, yval)
C=1;
sigma=0.3;
params = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30];%参数列表
min_error=0;%记录最小错误率
for c=params
for s=params
model=svmTrain(X, y, c, @(x1, x2) gaussianKernel(x1, x2, s));
predictions=svmPredict(model,Xval);
error=mean(double(predictions~=yval));
if min_error==0||error<min_error%保留错误最小的C和sigma
min_error=error;
C=c;
sigma=s;
end
end
end
end
将邮件字符处理为数字(若字典中的字符在邮件中出现,对应的数字编号放入 word_indices中)
for i=1:length(vocabList)
if strcmp(vocabList{i},str)
word_indices = [word_indices; i];
end
end
构建特征矩阵
for i=1:length(word_indices)
x(word_indices(i,1),1)=1
end