Support Vector Machine
SVM指的是支持向量机(外文名Support Vector Machine),在机器学习领域,是一个有监督的学习模型,通常用来进行模式识别、分类以及回归分析。
SVM具有以下特征:
⑴SVM学习问题可以表示为凸优化问题,因此可以利用已知的有效算法发现目标函数的全局最小值。而其他分类方法(如基于规则的分类器和人工神经网络)都采用一种基于贪心学习的策略来搜索假设空间,这种方法一般只能获得局部最优解。
⑵SVM通过最大化决策边界的边缘来控制模型的能力。尽管如此,用户必须提供其他参数,如使用核函数类型和引入松弛变量等。
⑶通过对数据中每个分类属性引入一个哑变量,SVM可以应用于分类数据。
⑷SVM一般只能用在二类问题,对于多类问题效果不好。
程序功能实现思路
我们先让机器做一个“异或”功能的学习。
“二类问题”求解方案,输入为二进制的00,01,10,11,像一个老师一样,教会程序结果为0,1,1,0.
验证时,我们期望重新验证一遍我们的输入,是不是机器可以告诉我们结果。
基于SVM学习“异或”的代码
using Accord.Controls;
using Accord.MachineLearning.VectorMachines.Learning;
using Accord.Math.Optimization.Losses;
using Accord.Statistics;
using Accord.Statistics.Kernels;
using System;
namespace GettingStarted
{
class Program
{
[MTAThread]
static void Main(string[] args)
{
double[][] inputs =
{
/* 1.*/ new double[] { 0, 0 },
/* 2.*/ new double[] { 1, 0 },
/* 3.*/ new double[] { 0, 1 },
/* 4.*/ new double[] { 1, 1 },
};
int[] outputs =
{
/* 1. 0 xor 0 = 0: */ 0,
/* 2. 1 xor 0 = 1: */ 1,
/* 3. 0 xor 1 = 1: */ 1,
/* 4. 1 xor 1 = 0: */ 0,
};
// Create the learning algorithm with the chosen kernel
var smo = new SequentialMinimalOptimization<Gaussian>()
{
Complexity = 100 // Create a hard-margin SVM
};
// Use the algorithm to learn the svm
var svm = smo.Learn(inputs, outputs);
// Compute the machine's answers for the given inputs
bool[] prediction = svm.Decide(inputs);
// Compute the classification error between the expected
// values and the values actually predicted by the machine:
double error = new AccuracyLoss(outputs).Loss(prediction);
Console.WriteLine("Error: " + error);
// Show results on screen
ScatterplotBox.Show("Training data", inputs, outputs);
ScatterplotBox.Show("SVM results", inputs, prediction.ToZeroOne());
Console.ReadKey();
}
}
}
运行结果及思考
Error为0,代表都能找的到。
思考:当我们想验证下机器学习中,没有进行训练的数据,预期输出会是什么?
比如,我们拷贝一份输入变量inputs1,设定值为21,10,01,11,修改如下代码运行:
bool[] prediction = svm.Decide(inputs1);