• 基于python的感知机


    一、

    1、感知机可以描述为一个线性方程,用python的伪代码可表示为:

    sum(weight_i * x_i) + bias -> activation  #activation表示激活函数,x_i和weight_i是分别为与当前神经元连接的其它神经元的输入以及连接的权重。bias表示当前神经元的输出阀值(或称偏置)。箭头(->)左边的数据,就是激活函数的输入

    2、定义激活函数f:

    def func_activator(input_value):

        return 1.0 if input_value >= 0.0 else 0.0

    二、感知机的构建

    class Perceptron(object):

      def __init__(self, input_para_num, acti_func):

        self.activator = acti_func

        self.weights = [0.0 for _ in range(input_para_num)]

      def __str__(self):

        return 'final weights w0 = {:.2f} w1 = {:.2f} w2 = {:.2f}'

          .format(self.weights[0],self.weights[1],self.weights[2])

      def predict(self, row_vec):

        act_values = 0.0

        for i in range(len(self.weights)):

          act_values += self.weights [ i ] * row_vec [ i ]

        return self.activator(act_values)

      def train(self, dataset, iteration, rate):

        for i in range(iteration):

          for input_vec_label in dataset:

            prediction = self.predict(input_vec_label)

            self._update_weights(input_vec_label,prediction, rate)

      def _update_weights(self, input_vec_label, prediction, rate):

        delta = input_vec_label[-1] - prediction

        for i in range(len(self.weights):

          self.weights[ i ] += rate * delta * input_vec_label[ i ]

    def func_activator(input_value):
    return 1.0 if input_value >= 0.0 else 0.0

    def get_training_dataset():
    dataset = [[-1, 1, 1, 1], [-1, 0, 0, 0], [-1, 1, 0, 0], [-1, 0, 1, 0]]
    return dataset

    def train_and_perceptron():
    p = Perceptron(3, func_activator)
    dataset = get_training_dataset()
    return p

    if __name__ == '__main__':
    and_prerception = train_and_perceptron
    print(and_prerception)
    print('1 and 1 = %d' % and_perception.predict([-1, 1, 1]))
    print('0 and 0 = %d' % and_perception.predict([-1, 1, 1]))
    print('1 and 0 = %d' % and_perception.predict([-1, 1, 1]))
    print('0 and 1 = %d' % and_perception.predict([-1, 1, 1]))

  • 相关阅读:
    Windows10远程桌面连接提示:出现身份验证错误,要求的函数不受支持
    mybatis 中 if-test 判断大坑
    hutool的DateUtil工具类
    SpringBoot启动过程
    数据库事务的隔离级别
    EasyUI管理后台模板(附源码)
    springmvc中自定义拦截器以及拦截器的执行过程
    文件上传(MultipartFile)
    文件下载(使用springmvc框架中ResponseEntity对象)
    json格式实现数据传输
  • 原文地址:https://www.cnblogs.com/zhaop8078/p/9532513.html
Copyright © 2020-2023  润新知