|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Created on Mon Jan 29 09:20:04 2018 |
| 4 | +
|
| 5 | +@author: liudiwei |
| 6 | +""" |
| 7 | + |
| 8 | +class Perceptron(object): |
| 9 | + def __init__(self, input_num, activation_func): |
| 10 | + """init parameter |
| 11 | + activation_func: this is a function of activation |
| 12 | + input_num: number of sample |
| 13 | + """ |
| 14 | + self.activation_func = activation_func |
| 15 | + self.weights = [0.0 for _ in range(input_num)] |
| 16 | + self.bias = 0.0 |
| 17 | + |
| 18 | + def train(self, input_vecs, labels, iteration, rate): |
| 19 | + """training model |
| 20 | + input_vec: input vetcor, a 2-D list |
| 21 | + labels: class label list |
| 22 | + iteration: |
| 23 | + rate: learning rate |
| 24 | + """ |
| 25 | + for i in range(iteration): |
| 26 | + self._one_iteration(input_vecs, labels, rate) |
| 27 | + |
| 28 | + def _one_iteration(self, input_vecs, labels, rate): |
| 29 | + """training model on input_vecs dataset""" |
| 30 | + samples = zip(input_vecs, labels) |
| 31 | + for (input_vec, class_label) in samples: |
| 32 | + output_val = self.predict(input_vec) |
| 33 | + self._update_weights(input_vec, output_val, class_label, rate) |
| 34 | + |
| 35 | + def _update_weights(self, input_vec, output_val, class_label, rate): |
| 36 | + """update weights for each iteration""" |
| 37 | + delta = class_label - output_val |
| 38 | + self.weights = map(lambda (x, w): w + rate * delta * x, |
| 39 | + zip(input_vec, self.weights)) |
| 40 | + self.bias += rate * delta |
| 41 | + |
| 42 | + def __to_string__(self): |
| 43 | + return 'weights\t: %s\nbias\t: %f\n' % (self.weights, self.bias) |
| 44 | + |
| 45 | + def predict(self, input_vec): |
| 46 | + """input input_vec and return a prediction value""" |
| 47 | + return self.activation_func( |
| 48 | + reduce(lambda a, b: a + b, |
| 49 | + map(lambda (x, w): x * w, zip(input_vec, self.weights)), |
| 50 | + 0.0) + self.bias) |
0 commit comments