コード例 #1
0
def main():
    file_add = sys.argv[1]
    tst, val, tst_lbl, val_lbl = get_data(file_add)
    vec_size = len(tst[0])
    neuron = Perceptron(vec_size, 0.1)
    # train
    has_err = True
    iters = 0
    cnt_err = 0
    while has_err:
        has_err = False
        cnt_err = 0
        iters += 1
        for x, y in zip(tst, tst_lbl):
            p = neuron.input(x)
            # print('input:', x)
            # print('out:', p)
            # print('expected:', y)
            b = neuron.feedback(p, y, x)
            if b:
                cnt_err += 1
            has_err = b or has_err
        print(f"iteration {iters} finished (err: {cnt_err})")
    print(f"learned weights: {neuron.w} bias: {neuron.b}")
    # evaluate
    count = len(val)
    if count > 0:
        cnt_err = 0
        for x, y in zip(val, val_lbl):
            p = neuron.input(x)
            if p != y:
                cnt_err += 1
        ratio = cnt_err / count
        print(f"err: {cnt_err}/{count} = {ratio:.2f}")
    if vec_size == 2:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        plot_data(tst, tst_lbl, ax)
        x0 = np.min(tst, 0)[0]
        x1 = np.max(tst, 0)[0]
        plot_line(neuron.w, neuron.b, ax, x0, x1)
        plt.show()