TensorFlow

다중선형회귀 예제 - 자전거 공유 시스템 분석

코딩탕탕 2022. 12. 1. 13:58

 

 

 

# 문제2)
# https://github.com/pykwon/python/tree/master/data
# 자전거 공유 시스템 분석용 데이터 train.csv를 이용하여 대여횟수에 영향을 주는 변수들을 골라 다중선형회귀분석 모델을 작성하시오.
# 모델 학습시에 발생하는 loss를 시각화하고 설명력을 출력하시오.
# 새로운 데이터를 input 함수를 사용해 키보드로 입력하여 대여횟수 예측결과를 콘솔로 출력하시오.

import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from xgboost import plot_importance
import xgboost as xgb
from sklearn.metrics import r2_score
from sklearn.preprocessing import MinMaxScaler

df = pd.read_csv('https://raw.githubusercontent.com/pykwon/python/master/data/train.csv')
print(df.head(3))
# print(df.isnull().sum()) # 널값없음

x = df.drop(['count', 'datetime'], axis=1)
# print(x[:3])
y = df['count']
# print(y[:3])

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)

# XGBClassifier로 중요 변수 뽑아내기
model = xgb.XGBClassifier(booster = 'gbtree', max_depth = 6, n_estimators=500 ).fit(x, y)
fig, ax = plt.subplots(figsize = (10, 12))
plot_importance(model, ax = ax) 
plt.show()

features = df[['registered', 'casual', 'humidity', 'windspeed', 'temp']] # 중요변수 따로 뽑아서 담아줌
x_train, x_test, y_train, y_test = train_test_split(features, y, test_size = 0.3)
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape) # (7620, 5) (3266, 5) (7620,) (3266,)

#모델 작성
scaler=MinMaxScaler(feature_range=(0,1))
features=scaler.fit_transform(features)

x_train, x_test, y_train,y_test=train_test_split(features, y, test_size=0.3)
# print(x_train.shape, x_test.shape, y_train.shape,y_test.shape)
# (7620, 5) (3266, 5) (7620,) (3266,)

model=Sequential()
model.add(Dense(units=1, input_dim=5, activation='linear'))

model.compile(optimizer='sgd', loss='mse', metrics=['mse'])
history=model.fit(x_train, y_train, epochs=15, verbose=0, validation_split=0.15)
print(history.history['loss'])

#시각화
plt.plot(history.history['loss'], label='train loss')
plt.xlabel('epochs')
plt.show()

#설명계수
pred=model.predict(x_test)
print('설명력', r2_score(y_test, pred))


<console>
              datetime  season  holiday  ...  casual  registered  count
0  2011-01-01 00:00:00       1        0  ...       3          13     16
1  2011-01-01 01:00:00       1        0  ...       8          32     40
2  2011-01-01 02:00:00       1        0  ...       5          27     32

[3 rows x 12 columns]
(7620, 5) (3266, 5) (7620,) (3266,)
[28182.78125, 18007.283203125, 13020.318359375, 9664.0107421875, 7350.62841796875, 5717.56591796875, 4541.59912109375, 3670.263427734375, 3008.651611328125, 2491.644287109375, 2082.2470703125, 1751.3590087890625, 1482.5010986328125, 1260.165771484375, 1074.5880126953125]

  1/103 [..............................] - ETA: 5s
 85/103 [=======================>......] - ETA: 0s
103/103 [==============================] - 0s 592us/step
설명력 0.9680765313450331

xgb를 import 하여 시각화로 중요변수를 알아보고 그것들을 꺼내여 train / test split 및 validation_split을 진행하여 모델을 설계하고 작성하였다.

 

 

 

독립변수들 중 중요변수 시각

 

학습률 loss 시각화