基于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]))

原文地址:https://www.cnblogs.com/zhaop8078/p/9532513.html