import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


def read_data(file_path):
    data = pd.read_csv(file_path, header=None, names=["feature"])
    data = np.array(data)
    return data


def scatter(x, y):
    pos = np.where(y == 1)[0].tolist()
    neg = np.where(y == 0)[0].tolist()
    plt.plot(x[pos, 0], x[pos, 1], '+')
    plt.plot(x[neg, 0], x[neg, 1], 'o')
    plt.show()


def sigmoid(x, w, b):
    t = x.dot(w) + b
    t = 1 + np.exp(-t)
    t = 1 / t
    return t


def compute_acc(x, y, w, b):
    pre = sigmoid(x, w, b)
    pre = np.where(pre>0.5, 1, 0)
    res = pre == y
    acc = np.sum(res == True)
    return acc/len(x)

def GD(x, y, w, b, l_rate, epoches):
    loss = []
    for epoch in range(epoches):
        dl_db = (y - sigmoid(x, w, b))
        dl_dw = dl_db * x
        dl_db = np.mean(dl_db)
        dl_dw = np.mean(dl_dw, axis=0)
        dl_dw = np.expand_dims(dl_dw, axis=1)
        w = w + l_rate * dl_dw
        b = b + l_rate * dl_db
        loss.append(np.sum((y - sigmoid(x, w, b))**2))
        if epoch % 10 == 0:
            print("epoch {}: w={} , b={}, loss={}".format(epoch, w, b, loss[epoch]))
    return w, b, loss


def main():
    # 数据准备
    x = read_data("./ex4x.dat")
    y = read_data("./ex4y.dat")
    t = []
    for i in range(len(x)):
        temp = x[i, 0].split()
        temp[0] = float(temp[0])
        temp[1] = float(temp[1])
        t.append(temp)
    x = np.array(t)
    y = y.astype("int16")
    # -----------------------
    w, b, loss = GD(x, y, np.random.rand(2, 1), np.random.rand(), 0.0001, 1000)

    pos = np.where(y == 1)[0].tolist()
    neg = np.where(y == 0)[0].tolist()
    plt.plot(x[pos, 0], x[pos, 1], '+')
    plt.plot(x[neg, 0], x[neg, 1], 'o')
    plt.plot(x, (-b-w[0, 0]*x[:, 0])/w[1, 0], 'r')
    plt.show()
    print(compute_acc(x, y, w, b))



if __name__ == '__main__':
    main()