实例一:训练SVM,解决XOR分类问题
异或问题的原理:相同为真,不同为假。
需要使用的包:Accord.MachineLearning、Accord.Controls、Accord.Math、Accord.Statistics。
代码如下:C#、控制台应用程序。
using Accord.Controls;
using Accord.MachineLearning.VectorMachines.Learning;
using Accord.Math.Optimization.Losses;
using Accord.Statistics;
using Accord.Statistics.Kernels;
using System;
namespace Support_Vector_Machines
{
class Program
{
static void Main(string[] args)
{
double[][] inputs =
{
new double[] { 0, 0 },
new double[] { 1, 0 },
new double[] { 0, 1 },
new double[] { 1, 1 },
};
int[] outputs =
{
0,
1,
1,
0,
};
//Create the learning algorithm with the chose kernel
var smo = new SequentialMinimalOptimization<Gaussian>()
{
Complexity = 100
};
//Use the algorithm to learn the svm
var svm = smo.Learn(inputs, outputs);
//Compute the machina`s answer 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();
}
}
}
结果如下: