神经网络 matlab实现 感知器_MLP_,实现简化的 && 运算符

学习神经网络,顺便记个笔记。

若转载,请贴 https://blog.csdn.net/u013271656/article/details/101373902

1. 感知器_MLP

本文参考链接中大佬写的文章,通俗易懂。感知器(MLP介绍以及python代码):

https://www.zybuluo.com/hanbingtao/note/433855

贴一下MLP介绍:

接下来将介绍如何用感知器实现 && 函数

我们设计一个感知器,让它来实现 && 运算。 && 运算符被称为逻辑与运算符。它需要两个表达式作为操作数,并创建一个表达式,只有当两个子表达式都为 true 时,该表达式才为 true。

为了计算方便,此处我们用0表示false,用1表示true。下表是各情景下&&运算符输出结果  output = (x1 && x2)

x1 x2 outPut
0 0 0
0 1 0
1 0 0
1 1 1

 

输入表中第一行数据(即x1=x2=0),那么根据公式(1),计算输出:

其中:

<1>. 激活函数 f 就是前面写出来的阶跃函数 y = f(w*z+b)。

<2>. 因为输入特征的维度为2,我们令其权重相等: w1=w2=0.5;,假设偏置(bias)值为 -0.8

 神经网络模型可以理解为:其就像一个函数模型y = ax + b,通过输入数据得到的结果反馈,来更新模型中的参数a与参数b。

此处,我们训练的目标参数就是y = f(w*z+b) 中的 w、b。接下来介绍如何进行训练。

2.  训练感知机中参数

3.  实现模型的训练、验证

matlab代码如下(MLP类):

classdef PerceptronMLP < handle
    properties
        activator
        weights;
        bias;
    end
    
    methods 
        function obj = PerceptronMLP(input_num, fobj)
            % 初始化感知器,设置输入参数的个数,以及激活函数。
            % 激活函数的类型为 double -> double
            obj.activator = fobj;
            if nargin == 2
                obj.weights = zeros(1, input_num);
                obj.bias = 0.0;
            else
                error('Value must be numeric')
            end
        end
        
        function output = predict(obj, input_vec)
            temp = input_vec.*obj.weights;
            output = obj.activator(sum(sum(temp)) + obj.bias);
                
        end
        
        function train(obj, input_vecs, labels, iteration, rate)
            for i = 1:iteration
                obj.one_iteration(input_vecs, labels, rate);
            end
        end
        
        function one_iteration(obj, input_vecs, labels, rate)
            % 一次迭代,把所有的训练数据过一遍
            for i = 1:max(size(input_vecs))
                input_vec = input_vecs(i,:);
                output = obj.predict(input_vec);
                label = labels(i,:);
                obj.update_weights(input_vec, output, label, rate);
            end
            debug = 1;
        end
        
        function update_weights(obj, input_vec, output, label, rate)
            % 按照感知器规则更新权重
            delta = label - output;
            obj.weights = obj.weights + rate.*delta.*input_vec;
            % 更新bias
            obj.bias = obj.bias + rate * delta;
        end
    end
end

接下来,训练感知器类并输入数据进行计算,看看是否符合预期。

clc
clear all
input_vecs = [1,1; 0,0;1,0; 0,1];
labels = [1, 0, 0, 0]';

fobj = @(x) x> 0;
p = PerceptronMLP(2, fobj);
p.train(input_vecs, labels, 10, 0.1);

p.predict([1,0])
p.predict([1,1])
p.predict([0,1])
p.predict([0,0])

猜你喜欢

转载自blog.csdn.net/u013271656/article/details/101373902