AI机器学习(二)让机器学会“异或”(C#)

Support Vector Machine

SVM

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);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值