1. 程式人生 > >面試例題5—感知器實現and函式

面試例題5—感知器實現and函式

用感知器實現and函式

參考部落格:https://www.zybuluo.com/hanbingtao/note/433855點選開啟連結

and 運算時一個二元運算,它的真值表如下:

x1 x2 y
0 0 0
0 1 0
1 0 0
1 1 1

Python:

class Perceptron(object):
    def __init__(self, input_num, activator):
        self.activator = activator
        self.weights = [0 for i in range(input_num)]
        self.bias = 0.0
    def __str__(self):
        return 'weights\t:%s\nbias\t:%f\n' % (self.weights,self.bias)
    def train(self, input_vecs, labels, iteration, rate): #train
        for i in range(iteration):
            self._one_iteration(input_vecs, labels, rate)
    def _one_iteration(self, input_vecs, labels, rate): # one iteration
        samples = zip(input_vecs, labels)
        for (input_vec, label) in samples:
            output = self.predict(input_vec)
            self._update_weights(input_vec, label, output, rate)

    def predict(self, input_vec):  #predict output
        return self.activator(
            reduce(lambda a, b: a + b,
                   map(lambda (x,w): x * w,
                   zip(input_vec,self.weights))
                   ,0.0) + self.bias)
    def _update_weights(self, input_vec, label, output, rate): # update weights and bias
        delta = label - output
        self.weights = map(
            lambda (x,w): w + rate * x * delta
            ,zip(input_vec, self.weights)
        )
        self.bias += rate * delta
def f(x):     # actavition function
    return 1 if x > 0 else 0
def get_trianing_data():  #train data
    input_vects = [[1,1],[1,0],[0,1],[0,0]]
    labels = [1,0,0,0]
    return input_vects,labels
def train_and_perceptron(): # train
    p = Perceptron(2,f)
    input_vecs, labels = get_trianing_data()
    p.train(input_vecs, labels, 10, 0.1)
    return p


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