Python - Regression
Linear Regression Curve
- Import modules
1
2
3
4
5
6
7import 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)
- Import data through
pandas1
2
3
4
5
6
7train_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()
- Compute the optimal theta based on the formula: .
1
2def optimalTheta(X, y):
return np.matmul(np.matmul(np.linalg.inv(np.matmul(X.transpose(), X)), X.transpose()), y)
- Sketch the curve using
matplotlib.pyplot1
2
3
4
5
6
7
8
9
10
11
12def 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
- 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
- Computing the gradient
1
2
3
4
5
6
7
8
9
10
11
12import 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]
- Computing the iteraction
1
2
3
4
5
6
7
8lr = 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])
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.


