博主只是初学机器学习的新人一枚,这篇博客旨在分享一下吴恩达机器学习课程编程练习6的答案,同时也是相当于自己对这一章的内容做一个回顾,让自己理解的更加的透彻,理性讨论,不喜勿喷
本章的主题是Support Vector Machines(SVM),即支持向量机,SVM是一类按照监督学习方式对数据进行二元分类的广义线性分类器,与前面提到的逻辑回归和神经网络类似,而SVM与二者相比,在学习复杂的非线性方程时,提供了一种更为清晰,更加强大的方法,线性回归、逻辑回归、神经网络和SVM的总结可以参考下列博文(侵删):线性回归、逻辑回归、神经网络、SVM总结
-
SVM with Linear Kernels
采用的是“linear kernel”,也称作No kernel,即没有核函数,简单的执行例如θTx>0时则有y=1的操作。展示了在SVM训练中C的作用,以下三张图依次为数据集、C=1时分类图、C=100时分类图:
从这三张图中我们似乎可以得出一个比较直观的结论—当C的值比较小时,SVM的分类结果更趋向于全局间距最大化,而当C的值较大时,SVM的结果更趋向于局部的最优解,这看起来似乎和练习5中的高方差结果类似。
事实上也正是如此,对于C的值来说,过大的C会导致低偏差、高方差,即过拟合;对于较小的C值来说则会有高偏差、低方差,即欠拟合。因此需要选取一个合适的C值,这在后面会有提到。 -
SVM with Gaussian Kernels
在这一小节提到了Gaussian Kernels(高斯核函数)的概念,上一小节是执行的线性分类,在这里则是非线性分类,因此需要用到高斯核函数,高斯核函数公式如下:
观察这个公式,实际上高斯核函数的作用类似于测量两点之间的距离,其主要作用是将二维坐标的点映射到三维空间进而学习复杂的非线性分类,具体的高斯核函数理解可以参考下列博文(侵删):SVM—通俗易懂图解高斯核函数
理解了高斯核函数,下面直接上matlab源码实现:sim = exp( - sum((x1-x2).^2) / (2*sigma^2) );
理解并实现了高斯核函数,下面我们需要选取合适的σ值以及合适的C值,类似于上一个练习中选取合适的lambda,我们在这里提供一个关于C和σ的步进向量,通过对每个值分别训练一个模型并对模型进行交叉验证,对误差值进行比较,取最小的误差值对应的C和σ的值,具体的matlab代码实现如下:
prediction_error = zeros(len,len); for i = 1:len C = C_vec(i); for j = 1:len sigma = sigma_vec(j); model= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma)); predictions = svmPredict(model,Xval); prediction_error(i,j) = mean(double(predictions ~= yval)); end end min_val = min(min(prediction_error)); [i, j] = find(min_val == prediction_error); C = C_vec(i); sigma = sigma_vec(j);
邮件分类
直接贴上代码部分:
processEmail.m
isExist = ismember(str,vocabList);
if isExist == 1
idx = find(strcmp(str,vocabList));
word_indices = [word_indices;idx];
end
emailFeatures.m
for index = 1:n
x(index) = ismember(index,word_indices);
end