def main(): # generate a 3d ponit with a label # point = Point() # generate a 3d ponit with a label points = [Point() for _ in range(10)] # print(points) prec_x_val = Preceptron(2) prec_y_val = Preceptron(2) prec_z_val = Preceptron(2) for _ in range(10): for _ in range(100): indx = random.randrange(len(points)) point = points[indx] prec_x_val.train([point.t, point.r[0]], point.label[0]) prec_y_val.train([point.t, point.r[1]], point.label[1]) prec_z_val.train([point.t, point.r[2]], point.label[2]) point = Point() fed = [ prec_x_val.feed_forward([point.t, point.r[0]]), prec_y_val.feed_forward([point.t, point.r[1]]), prec_z_val.feed_forward([point.t, point.r[2]]) ] print("predicted:", fed) print("expected:", point.label)
def and_prediction(): and_preceptron = Preceptron(3) # input 1, input 2, bias val0 = [0,0, 1] val1 = [0,1, 1] val2 = [1,0, 1] val3 = [1,1, 1] val_labels = [0, 0, 0, 1] inputs = [val0, val1, val2, val3] for _ in range(100): rand_num = random.randrange(0, 4) input = inputs[rand_num] label = val_labels[rand_num] # expects target to be -1 or 1 if label == 0: label = -1 else: labe = 1 # print('randnum:',rand_num, 'input:', input, 'label:', label) and_preceptron.train(input, label) print("x and y") for i in inputs: # return -1 or 1 pred = and_preceptron.feed_forward(i) # print("pred", pred) if pred == -1: pred = 0 else: pred = 1 print("{} | {} -> {}".format(i[0], i[1], pred))
def not_prediction(): not_preceptron = Preceptron(2) # input 1, bias val0 = [0, 1] val1 = [1, 1] val_labels = [1, 0] inputs = [val0, val1] for _ in range(100): rand_num = random.randrange(0, 2) input = inputs[rand_num] label = val_labels[rand_num] # expects target to be -1 or 1 if label == 0: label = -1 else: labe = 1 # print('randnum:',rand_num, 'input:', input, 'label:', label) not_preceptron.train(input, label) print("not x") for i in inputs: # return -1 or 1 pred = not_preceptron.feed_forward(i) # print("pred", pred) if pred == -1: pred = 0 else: pred = 1 print("{} -> {}".format(i[0], pred))
def test_train_method_2(self): inputs = [0, 0] weights = [1,1,1] target = 0 p = Preceptron(2, weights) p.lr = 1 result = p.feed_forward(inputs) self.assertEqual(result, 1) result = p.train(inputs, target) self.assertEqual(result.data, [1,1,0])
def test_train_method(self): # 2 inputs: x1, x2 # x1*w1 x2*w2 + 1*w3 inputs = [0,0] weights = [0,0,0] # last one is the bias target = 1 p = Preceptron(2, weights) self.assertEqual(p.num_weights, 2) self.assertEqual(len(p.weights.data), 3) p.lr = 1 result = p.feed_forward(inputs) self.assertEqual(result, 1) result = p.train(inputs, target) self.assertEqual(result.data, [0,0,0])
def test_feed_forward_with_invalid_input(self): p = Preceptron(2, [0,0,0]) with self.assertRaises(Exception): p.feed_forward([0])
def test_feed_forward_with_valid_input(self): p = Preceptron(2, [0,0,0]) result = p.feed_forward([0,0]) self.assertEqual(result, 1)