import seaborn as sns cols = ['y','RM','LSTAT','NOX'] sns.pairplot( housing[cols]) plt.show() # y, RM 양의 상관관계, LSTAT, NOX 음의 상관관계
# 독립속성, 종속속성 선택 y = housing['y']
from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from math import sqrt #1 독립속성 선택 x = housing[['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE', 'DIS','RAD','TAX','PTRATIO','B','LSTAT']] # 2 종속속성 선택 y = housing['y'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=33)
lr = linear_model.LinearRegression() model = lr.fit(x_train, y_train) print(model.score(x_train, y_train)) print(model.score(x_test, y_test)) 0.7490284664199387 0.7009342135321538
plt.plot(pred_y, color = 'gold') # 모델 예측한 가격그래프
plt.plot(pred_y_lower, color = 'red') # 모델이 예상한 최소 가격 그래프
plt.plot(pred_y_upper, color = 'blue') # 모델이 예상한 최대 가격 그래프
plt.plot(test_y, color = 'green') # 실제 가격 그래프
plt.plot(pred_y, color = 'gold') # 모델 예측한 가격그래프
plt.plot(pred_y_lower, color = 'red') # 모델이 예상한 최소 가격 그래프
plt.plot(pred_y_upper, color = 'blue') # 모델이 예상한 최대 가격 그래프
plt.plot(test_y, color = 'green') # 실제 가격 그래프
#
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from fbprophet import Prophet
file_path = 'market-price.csv'
bitcoin_df = pd.read_csv(file_path, names = ['ds', 'y'], header=0)
# 상한가 설정
bitcoin_df['cap'] = 20000
# 하한가 설정
bitcoin_df['floor'] = 2000
# growth = logistic 상한설정시 추가, 비선형방식으로 분석
prophet = Prophet(seasonality_mode = 'multiplicative',
growth = 'logistic', # 상하한가 설정할때 , 비선형방식
yearly_seasonality = True, # 연별
weekly_seasonality = True, # 주별
daily_seasonality = True, # 일별
changepoint_prior_scale = 0.5) # 과적합 방지 0.5만큼 만 분석
prophet.fit(bitcoin_df) # 학습하기
plt.plot(pred_y, color = 'gold') # 모델 예측한 가격그래프
plt.plot(pred_y_lower, color = 'red') # 모델이 예상한 최소 가격 그래프
plt.plot(pred_y_upper, color = 'blue') # 모델이 예상한 최대 가격 그래프
plt.plot(test_y, color = 'green') # 실제 가격 그래프
bitcoin_df.describe()
price
count 365.000000
mean 8395.863578
std 3239.804756
min 3319.630000
25% 6396.772500
50% 7685.633333
75% 9630.136277
max 19498.683333
bitcoin_df.plot()
plt.show()
# arima 모델 학습 # order = (2,1,2) # 2 => ar 2번째 과거까지 알고리즘에 넣음 # 1 => difference 차분 정보, 현재상태 - 바로 이전의 상태 뺀값 # 시계열 데이터의 불규칙성을 파악 => 비트코인 ^^ # 2 => ma 2번째 과거정보오차를 이용해서 현재를 추론
from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(bitcoin_df.price.values, order=(2,1,2))
model_fit = model.fit(trend='c', full_output=True, disp=True)
fig = model_fit.plot_predict() # 학습 데이터에 대한 예측 결과 출력
risiduals = pd.DataFrame(model_fit.resid)# 잔차의 변동을 시각화
risiduals.plot()
# 실제데이터와 비교
# 이후 5일 정보 예측
forecast_data = model_fit.forecast(steps=5)
forecast_data
# 1 번 배열 : 예측값, 5일차 예측값
# 2 번 배열 : 표준오차, 5일차 예측값
# 3 번 배열 : 5개 배열 [예측데이터 하한값, 예측데이터 상한값]
(array([6676.91689529, 6685.04884511, 6690.29837254, 6697.35159419,
6703.26452567]),
array([ 512.41529746, 753.50414112, 914.97749885, 1061.45286959,
1184.4382798 ]),
array([[5672.60136715, 7681.23242343],
[5208.20786632, 8161.8898239 ],
[4896.97542813, 8483.62131695],
[4616.94219851, 8777.76098987],
[4381.80815535, 9024.720896 ]]))
# adj 수정결정계수 독립변수가 많아지는 경우 결정계수값이 커질수있어, 표본의 크기와 독립변수의 수를 고려하여 다중회귀분석을 수행하는 경우 p>|t| 각피처의 검정통계량(f statistics )이 유의미한지를 나타내는 pvalue 값 p value < 0.05 이면 피처가 회귀분석에 유의미한 피처다 이분석에서는 war 연복2017 한화 3개가 0.05미만 => 회귀분석에서 유의미한 피처들
x_train = sm.add_constant(x_train)
model = sm.OLS(y_train, x_train).fit()
model.summary()
OLS Regression Results
Dep. Variable: y R-squared: 0.928
Model: OLS Adj. R-squared: 0.907
Method: Least Squares F-statistic: 44.19
Date: Tue, 20 Jul 2021 Prob (F-statistic): 7.70e-42
Time: 10:53:15 Log-Likelihood: -1247.8
No. Observations: 121 AIC: 2552.
Df Residuals: 93 BIC: 2630.
Df Model: 27
Covariance Type: nonrobust
coef std err t P>|t| [0.025 0.975]
const 1.678e+04 697.967 24.036 0.000 1.54e+04 1.82e+04
BABIP -1481.0173 1293.397 -1.145 0.255 -4049.448 1087.414
ERA -416.6874 2322.402 -0.179 0.858 -5028.517 4195.143
FIP -9.414e+04 9.43e+04 -0.998 0.321 -2.81e+05 9.31e+04
KIA 303.1852 2222.099 0.136 0.892 -4109.462 4715.833
KT 3436.0520 2133.084 1.611 0.111 -799.831 7671.935
LG 1116.9978 2403.317 0.465 0.643 -3655.513 5889.509
LOB% -1375.5383 1564.806 -0.879 0.382 -4482.933 1731.857
NC 1340.5004 2660.966 0.504 0.616 -3943.651 6624.652
RA9-WAR 3959.1065 2931.488 1.351 0.180 -1862.247 9780.460
SK 2762.4237 2243.540 1.231 0.221 -1692.803 7217.650
WAR 1.027e+04 2532.309 4.057 0.000 5243.823 1.53e+04
kFIP 7.767e+04 7.95e+04 0.977 0.331 -8.03e+04 2.36e+05
경기 -2434.3895 2953.530 -0.824 0.412 -8299.515 3430.736
두산 971.9293 2589.849 0.375 0.708 -4170.998 6114.857
롯데 2313.9585 2566.009 0.902 0.370 -2781.627 7409.544
볼넷/9 7612.1566 6275.338 1.213 0.228 -4849.421 2.01e+04
블론 1271.0450 1242.128 1.023 0.309 -1195.576 3737.666
삼성 -946.5092 2482.257 -0.381 0.704 -5875.780 3982.762
삼진/9 5396.9728 7286.221 0.741 0.461 -9072.019 1.99e+04
선발 -4797.3028 5489.352 -0.874 0.384 -1.57e+04 6103.463
세 -250.6977 1295.377 -0.194 0.847 -2823.059 2321.663
승 236.0253 2215.264 0.107 0.915 -4163.049 4635.100
연봉(2017) 1.913e+04 1270.754 15.055 0.000 1.66e+04 2.17e+04
이닝 854.0260 6623.940 0.129 0.898 -1.23e+04 1.4e+04
패 1301.6197 1935.935 0.672 0.503 -2542.763 5146.003
한화 5477.8879 2184.273 2.508 0.014 1140.355 9815.421
홀드 -935.0728 1637.923 -0.571 0.569 -4187.663 2317.518
홈런/9 1.814e+04 1.68e+04 1.082 0.282 -1.52e+04 5.14e+04
Omnibus: 28.069 Durbin-Watson: 2.025
Prob(Omnibus): 0.000 Jarque-Bera (JB): 194.274
Skew: -0.405 Prob(JB): 6.52e-43
Kurtosis: 9.155 Cond. No. 3.63e+16
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The smallest eigenvalue is 6.04e-31. This might indicate that there are
strong multicollinearity problems or that the design matrix is singular.
from statsmodels.stats.outliers_influence import variance_inflation_factor
vif = pd.DataFrame()
vif['VIF Factor'] = [variance_inflation_factor(x.values, i) for i in range(x.shape[1])]
vif['features'] = x.columns
vif.round(1)
VIF Factor features
0 3.2 BABIP
1 10.6 ERA
2 14238.3 FIP
3 1.1 KIA
4 1.1 KT
5 1.1 LG
6 4.3 LOB%
7 1.1 NC
8 13.6 RA9-WAR
9 1.1 SK
10 10.4 WAR
11 10264.1 kFIP
12 14.6 경기
13 1.2 두산
14 1.1 롯데
15 57.8 볼넷/9
16 3.0 블론
17 1.2 삼성
18 89.5 삼진/9
19 39.6 선발
20 3.1 세
21 8.0 승
22 2.5 연봉(2017)
23 63.8 이닝
24 5.9 패
25 1.1 한화
26 3.8 홀드
27 425.6 홈런/9
변수간 상관관계가 높아서 분석에 부정적인 영향을 미침 vif 평가 : 분산팽창요인 보통 10~15 정도를 넘으면 다중공선성에 문제가 있다고 판단 홈런, 이닝, 선발, 삼진, 볼넷, 경기, kfip,fip 특히 이둘은 너무 유사해서 상승효과가 생김, 그래서 하나는 빼버려야함 1. vif 계수 높은 피처 제거, 유사피처중 한개만 제거 2. 다시모델을 실행해서 공선성 검증 3. 분석결과에서 p-value값이 유의미한 피처들을 선정
# rmse 평가
# mse 평균제곱오차
from math import sqrt
from sklearn.metrics import mean_squared_error
y_pred = lr.predict(x_train)
print(sqrt(mean_squared_error(y_train, y_pred)))
y_pred = lr.predict(x_test)
print(sqrt(mean_squared_error(y_test, y_pred)))
# 7893.462873347693
# 13141.86606359108
# 피처별 vif 공분산
from statsmodels.stats.outliers_influence import variance_inflation_factor
x = picher_df[['FIP','WAR','볼넷/9','삼진/9','연봉(2017)']]
vif = pd.DataFrame()
vif['VIF Factor'] = [variance_inflation_factor(x.values, i) for i in range(x.shape[1])]
vif['features'] = x.columns
vif.round(1)
VIF Factor features
0 1.9 FIP
1 2.1 WAR
2 1.9 볼넷/9
3 1.1 삼진/9
4 1.9 연봉(2017)
# 시각화\ 비교
# 모든 데이터 검증
# lr 학습이 완료된 객체
x = picher_df[['FIP','WAR','볼넷/9','삼진/9','연봉(2017)']]
predict_2018_salary = lr.predict(x)
predict_2018_salary[:5]
picher_df['예측연봉(2018)'] = pd.Series(predict_2018_salary)
df.head()
지역 학교명 코드 유형 주야 ... 기타진학 취업 미상 위도 경도
0 성북구 서울대학교사범대학부설중학교 3 국립 주간 ... 0.004 0 0.000 37.594942 127.038909
1 종로구 서울대학교사범대학부설여자중학교 3 국립 주간 ... 0.031 0 0.000 37.577473 127.003857
2 강남구 개원중학교 3 공립 주간 ... 0.009 0 0.003 37.491637 127.071744
3 강남구 개포중학교 3 공립 주간 ... 0.019 0 0.000 37.480439 127.062201
4 서초구 경원중학교 3 공립 주간 ... 0.010 0 0.000 37.510750 127.008900
df['location'] = label_location
df['type'] = label_type
df['code'] = label_code
df['day'] = label_day
df.head()
지역 학교명 코드 유형 주야 ... 경도 location type code day
0 성북구 서울대학교사범대학부설중학교 3 국립 주간 ... 127.038909 16 1 0 0
1 종로구 서울대학교사범대학부설여자중학교 3 국립 주간 ... 127.003857 22 1 0 0
2 강남구 개원중학교 3 공립 주간 ... 127.071744 0 0 0 0
3 강남구 개포중학교 3 공립 주간 ... 127.062201 0 0 0 0
4 서초구 경원중학교 3 공립 주간 ... 127.008900 14 0 0 0
5 rows × 24 columns
df['Cluster'] = cluster_label
df.head()
지역 학교명 코드 유형 주야 ... location type code day Cluster
0 성북구 서울대학교사범대학부설중학교 3 국립 주간 ... 16 1 0 0 -1
1 종로구 서울대학교사범대학부설여자중학교 3 국립 주간 ... 22 1 0 0 -1
2 강남구 개원중학교 3 공립 주간 ... 0 0 0 0 -1
3 강남구 개포중학교 3 공립 주간 ... 0 0 0 0 -1
4 서초구 경원중학교 3 공립 주간 ... 14 0 0 0 -1