感知机学习算法对偶形式(Matlab代码)

1.函数CreateData 

CreateData.m

%加载数据集
function [ dataset ] = CreateData()
dataset = load('mywine.txt');
end

2.函数DrawPoint

DrawPoint.m

%绘制具有2维特征的数据
function [hp1, hp2] = DrawPoint(dataset)
figure(1);
cols=size(dataset, 2);
positive=[];
negative=[];

for i = 1:cols

    if dataset(1,i) == 1
        positive=[positive dataset(:, i)];
    else
        negative=[negative dataset(:,i)];
    end
end
hp1=plot(positive(2,:), positive(3,:), 'r*');
hold on;
hp2=plot(negative(2,:), negative(3,:), 'bo');

end

3.函数Learing

Learing.m

%根据数据集进行学习得到超平面
function [ w, b ] = Learning(dataset)

G=dataset([2 3], :)'*dataset([2 3], :);

cols=size(dataset, 2);
alpha=zeros(cols, 1);
bias=0;
eta=1;
while 1
    bFlag=0;
    for i=1:cols
        temp=0;
        for j=1:cols
           temp=temp+alpha(j)*dataset(1,j)*G(j, i);
        end
        if dataset(1,i)*(temp+bias) <= 0
            alpha(i)=alpha(i)+eta;
            bias=bias+eta*dataset(1,i);
            bFlag=1;
        end
    end
    if bFlag==0
        break;
    end
end
w=dataset([2 3], :)*(alpha.*dataset(1, :)')
b=bias
end

4.客户端调用

Main.m

dataset=CreateData();
[h1, h2]=DrawPoint(dataset);
[w, b]=Learning(dataset);
hf=figure(1);
set(hf, 'Position', get(0, 'ScreenSize'));
x1=12:15;
if w(2,1) ~= 0
    x2=(-w(1,1)*x1-b)/w(2,1);
elseif w(1, 1) ~= 0
    x1=[-b/w(1,1), -b/w(1,1)];
    x2=[0 1];
end

    
hl=plot(x1,x2, 'LineWidth', 2, 'Color', 'g');
text(13.2, 1.55, 'y=w^{T}x+b');
xlabel('x_{1}:第一维特征');
ylabel('x_{2}:第二维特征');
title('\bf感知机对偶学习算法');

legend([h1,h2, hl],'正例', '负例', '超平面');
grid on

5.以下是我用的测试数据集mywine.txt(线性可分, 文件我保存的每一维数据是列向量,如果你按照下面这种形式保存,load('mywine.txt')后需要转置一下)

    1.0000   14.2300    1.7100
    1.0000   13.2000    1.7800
    1.0000   13.1600    2.3600
    1.0000   14.3700    1.9500
    1.0000   13.2400    2.5900
    1.0000   14.2000    1.7600
    1.0000   14.3900    1.8700
    1.0000   14.0600    2.1500
   -1.0000   12.3700    0.9400
   -1.0000   12.3300    1.1000
   -1.0000   12.6400    1.3600
   -1.0000   13.6700    1.2500
   -1.0000   12.3700    1.1300
   -1.0000   12.1700    1.4500
   -1.0000   12.3700    1.2100
   -1.0000   13.1100    1.0100
   -1.0000   12.3700    1.1700

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值