Accord.Net_API使用_SVM_的AND範例_使用_資料表示方法_筆記
首先到 Accord.Net 官網 做 API 下載
載點: http://accord-framework.net/index.html
這次要來學習 SVM 的範例
這是一個簡短範例改寫後的的執行畫面
顯示的是 做了 AND 的 結果
程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Accord.Controls;
using Accord.IO;
using Accord.MachineLearning.VectorMachines;
using Accord.MachineLearning.VectorMachines.Learning;
using Accord.Math;
using Accord.Statistics.Analysis;
using Accord.Statistics.Kernels;
using System.Data;
namespace SVM_example_ex
{
class Program
{
static void Main(string[] args)
{
svm_input();
}
private static void svm_input()
{
double[][] problem =
{
// a b a & b
new double[] { 0, 0, 0 },
new double[] { 0, 1, 0 },
new double[] { 1, 0, 0 },
new double[] { 1, 1, 1 },
};
//從矩陣中取得 column vector
//double[][] inputs;
double[][] inputs = problem.GetColumns(0, 1);
//取得double[][] problem 浮點數二維陣列取到第二直行的數值,為一個vector = [0,0,0,1]
int[] outputs = problem.GetColumn(2).ToInt32();
for(int i = 0; i<=3;i++)
Console.WriteLine("第{0}個存在outputs的元素:{1}",i,outputs[i]);
for(int j=0;j<=3;j++)
for(int k=0;k<=2;k++)
{
Console.WriteLine("第({0},{1})個元素為:{2}",j,k,problem[j][k]);
}
ScatterplotBox.Show("AND", inputs, outputs).Hold();
// However, SVMs expect the output value to be
// either -1 or +1. As such, we have to convert
// it so the vector contains { -1, -1, -1, +1 }://資料的分類標記
outputs = outputs.Apply(x => x == 0 ? -1 : 1);
// Create a new linear-SVM for two inputs (a and b)
SupportVectorMachine svm = new SupportVectorMachine(2);
// Create a L2-regularized L2-loss support vector classification
var teacher = new LinearDualCoordinateDescent(svm, inputs, outputs)
{
Loss = Loss.L2, //
Complexity = 1000, //複雜度
Tolerance = 1e-5 //表示10的-5次方
};
// Learn the machine
double error = teacher.Run(computeError: true);
// Compute the machine's answers for the learned inputs
int[] answers = inputs.Apply(x => Math.Sign(svm.Compute(x)));
//Math.Sign
// Plot the results
ScatterplotBox.Show("SVM's answer", inputs, answers).Hold();
}
}
}
留言
張貼留言