Linear Regression Curve

  1. Import modules
    1
    2
    3
    4
    5
    6
    7
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from statistics import variance
    from sklearn.metrics import mean_squared_error

    np.set_printoptions(suppress=True)
  1. Import data through pandas
    1
    2
    3
    4
    5
    6
    7
    train_data = pd.read_csv("train_data.csv")
    X_train = np.array(train_data['x'].tolist())
    y_train = np.array(train_data['y'].tolist())

    test_data = pd.read_csv("test_data.csv")
    X_test = test_data['x'].tolist()
    y_test = test_data['y'].tolist()
  1. Compute the optimal theta based on the formula: .
    1
    2
    def optimalTheta(X, y):
    return np.matmul(np.matmul(np.linalg.inv(np.matmul(X.transpose(), X)), X.transpose()), y)
  1. Sketch the curve using matplotlib.pyplot
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    def sketchGraph(theta, color):
    plt.scatter(X_train, y_train)
    i = np.linspace(0, 10)
    j = 0

    for dimension in range(len(theta)):
    j += theta[dimension] * pow(i, dimension)

    plt.plot(i, j, color)
    plt.xlim(0, 9)
    plt.ylim(-1, 2)
    plt.show()

Logistic Regression

  1. Set up the logistic model
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    # Logistic Model
    def computeError(theta):
    lm = [1/(1 + np.exp(-(np.matmul(X_train[i].transpose(), theta)))) for i in range(len(X_train))]

    # Prediction Accuracy
    p = [lm[i] ** y_train[i] * (1 - lm[i]) ** (1 - y_train[i]) for i in range(len(X_train))]

    # Maximum Likelihood Estimation
    E = -1 * sum([np.log(p[i]) for i in range(len(X_train))])
    return E
  1. Computing the gradient
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import math

    def compGradient(X, theta):
    def de(X, theta):
    partialDe0 = [(1 - y_train[i] - math.exp(-1 * np.matmul(X[i].transpose(), theta)) / (1 + math.exp(-1 * np.matmul(X[i].transpose(), theta)))) for i in range(6)]
    return [partialDe0, partialDe1, partialDe2]

    de = de(X_train, theta)

    gradient = sum(de)

    return [gradient]
  1. Computing the iteraction
    1
    2
    3
    4
    5
    6
    7
    8
    lr = 1      # learning rate
    theta = np.array([-2.5, 6.0, 0.5]) # initial theta
    gradient = np.array([0.723, 0.084, 0.433])

    for i in range(1):
    theta = theta - gradient * lr
    E = computeError(theta)
    print('Iteration', i + 1, '=', [E])