''' Design of an artificial neuron using perceptron learning rule ''' import numpy from neuron import Neuron, bipolar_step numpy.set_printoptions(precision=2) w = [1, -1, 0, 0.5] C = 0.1 D = [-1, -1, 1] X = numpy.array([[1, -2, 0, -1], [0, 1.5, -0.5, -1], [-1, 1, 0.5, -1]]) neuron = Neuron(activation_fn=bipolar_step, weights=w) for epoch in range(5): print(f'\nepoch {epoch+1}') for x, di in zip(X, D): neuron.inputs = x o = neuron.calc_out() neuron.weights += C * (di - o) * x print(f'weights: {neuron.weights}')
# nand gate print('\nnand') nand_gate = Neuron(lambda net: net > -2, weights=[-1, -1]) show_output(nand_gate, gate_inputs) # nor gate print('\nnor') nor_gate = Neuron(lambda net: net > -1, weights=[-1, -1]) show_output(nor_gate, gate_inputs) # not print('\nnot') not_gate = Neuron(lambda net: net > -1, weights=[-1]) for g_inputs in [[0], [1]]: not_gate.inputs = numpy.array(g_inputs) print(f'x:{g_inputs} O:', not_gate.calc_out()) # xor print('\nxor') o1 = Neuron(signum, weights=[-2, 1], bias=-1 / 2) o2 = Neuron(signum, weights=[1, -1], bias=-1 / 2) xor_gate = Neuron(signum, weights=[1, 1], bias=-1 / 2) def sh_xor_output(gate_inputs_list): '''helper fuction to display xor output''' gate_inputs_array = numpy.array(gate_inputs_list) o1.inputs = o2.inputs = gate_inputs_array xor_gate.inputs = numpy.array([o1.calc_out(), o2.calc_out()]) print(f'x1:{gate_inputs_array[0]} x2:{gate_inputs_array[1]} O:', xor_gate.calc_out())