구현1. linear regression¶
- x의 1차항만 고려하는 선형회귀(Linear Regression) 모형
- 13개의 Attribute 중 첫 번째 Attribute만 Feature varaible로 활용함 (강의에서 첫 번째 항은 더미데이터처럼 1이라 한 것 기억!)
- $\hat \theta = argmin_{\theta}(f-\hat f)^2 ~~>> \theta = (X^TX)^{-1}X^TY$
- y_est(= x_temp * θ): 위에서 구해진 theta로 도출된 예측치
In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
pd.set_option('display.max_columns', 500)
pd.options.display.float_format = '{:.5f}'.format
In [2]:
x=pd.read_csv('X.csv', header=None)
y=pd.read_csv('Y.csv', header=None)
x
Out[2]:
In [3]:
x = x.values
y = y.values
In [4]:
x_temp = x[:, 0:2]
theta = np.dot(np.dot(np.linalg.inv(np.dot(np.transpose(x_temp), x_temp)), np.transpose(x_temp)), y)
y_est = np.dot(x_temp, theta)
np.linalg.lstsq()
명령은 행렬 A 와 b 를 모두 인수로 받고
- 최소자승문제(least square problem)의 답 x,
- 잔차제곱합(residual sum of squares) resid,
- 랭크(rank) rank,
- 특잇값(singular value) s를 반환한다.
미지수와 방정식의 개수가 같고 행렬 A 의 역행렬이 존재하면 최소자승문제의 답과 선형 연립방정식의 답이 같으므로 lstsq() 명령으로 선형 연립방정식을 풀 수도 있다.
In [5]:
np.linalg.lstsq(x_temp, y, rcond=None)
# rcond
# Cut-off ratio for small singular values of a.
# For the purposes of rank determination,
# singular values are treated as zero if they are smaller than rcond times the largest singular value of a.
Out[5]:
In [6]:
# m0, c0 = argmin |Y - (m0 * xYemp + c0)|^2
# m1, c1 = argmin |Y_est - (m1 * xYemp + c1)|^2
m0, c0 = np.linalg.lstsq(x_temp, y, rcond=None)[0]
m1, c1 = np.linalg.lstsq(x_temp, y_est, rcond=None)[0]
구현2. polynomial regression¶
- 8차항으로 이루어진 다항 회귀 모형
- new_x: new_x[i] = $[1,~x_i,~x_i^2,~x_i^3~,~...~,~x_i^8]$
- new_theta: 오차의 제곱을 최소화하는 parameter
- new_y_est: new_theta로 측정된 예측치
In [7]:
new_x = np.zeros((x.shape[0], 9))
new_x
Out[7]:
In [8]:
new_x[:, 0:2] = x[:, 0:2]
for i in range(2, 9):
new_x[:, i] = new_x[:, 1] * new_x[:, i-1]
new_theta = np.dot(np.dot(np.linalg.inv(np.dot(np.transpose(new_x), new_x)), np.transpose(new_x)),y)
new_y_est = np.dot(new_x, new_theta)
# m2, c2 = argmin |Y_est - (m2 * xYemp + c2)|^2
m2, c2 = np.linalg.lstsq(x_temp, new_y_est, rcond=None)[0]
구현3. 그래프¶
In [9]:
# 결과값을 그래프로 나타냄
# x축은 사용한 Feature Variable의 값이고, y축은 Dependent Variable의 값
plt.figure(1, figsize = (17, 5))
# 그래프 1
ax1 = plt.subplot(1, 3, 1)
plt.plot(x[:, 1], y, 'ro', markeredgecolor = 'none')
plt.plot(x[:, 1], m0+c0*x[:, 1], 'r-')
plt.plot(x[:, 1], y_est, 'bo', markeredgecolor = 'none')
plt.plot(x[:, 1], m1+c1*x[:, 1], 'b-')
plt.xlabel('Feature Variable', fontsize = 14)
plt.ylabel('Dependent Variable', fontsize = 14)
# 그래프 2
ax2 = plt.subplot(1, 3, 2, sharey = ax1)
plt.plot(x[:, 1], y, 'ro', markeredgecolor = 'none')
plt.plot(x[:, 1], new_y_est, 'go', markeredgecolor = 'none')
plt.plot(x[:, 1], m2 + c2*x[:, 1], 'g-')
plt.xlabel('Feature Variable', fontsize = 14)
plt.ylabel('Dependent Variable', fontsize = 14)
# 그래프3
ax3 = plt.subplot(1, 3, 3, sharey = ax2)
plt.plot(x[:, 1], y, 'ro', markeredgecolor = 'none')
plt.plot(x[:, 1], y_est, 'bo', markeredgecolor = 'none')
plt.plot(x[:, 1], new_y_est, 'go', markeredgecolor = 'none')
plt.xlabel('Feature Variable', fontsize = 14)
plt.ylabel('Dependent Variable', fontsize = 14)
plt.show()
구현4. statsmodel: linear regression¶
In [10]:
from statsmodels.api import OLS
model1 = OLS(y, x_temp).fit()
p = model1.params
y_pred1 = model1.predict(x_temp)
model1.summary()
Out[10]:
In [11]:
plt.plot(x[:, 1], y, 'ro', markeredgecolor = 'none')
plt.plot(x[:, 1], y_pred1, 'bo', markeredgecolor = 'none')
plt.plot(x[:, 1], p[0] + p[1]*x[:, 1], 'b-')
Out[11]:
구현5. statsmodel+scikit learn: polynomial regression¶
In [12]:
from sklearn.preprocessing import PolynomialFeatures
polynomial_features = PolynomialFeatures(degree=8)
xp = polynomial_features.fit_transform(x[:, 1:2])
print(xp.shape)
xp
Out[12]:
In [15]:
model2 = OLS(y, xp).fit()
y_pred2 = model2.predict(xp)
y_pred2.shape
Out[15]:
In [16]:
model2.summary()
Out[16]:
In [17]:
plt.plot(x[:, 1], y, 'ro', markeredgecolor = 'none')
plt.plot(x[:, 1], y_pred2, 'go', markeredgecolor = 'none')
Out[17]:
In [ ]:
'기계학습 > 인공지능및기계학습개론정리' 카테고리의 다른 글
Hidden Markov Model(1: Joint, Marginal Probability of HMM) (0) | 2020.11.16 |
---|---|
Bayesian Network (0) | 2020.11.03 |
Naive Bayes Classifier + Logistic Regression (parameter approximation) (0) | 2020.08.27 |
MLE(Maximum Likelihood Estimator) vs MAP(Maximum A Posterior) (0) | 2020.08.27 |
Logistic Regression + Gaussian Naive Bayes (0) | 2020.08.27 |