본문 바로가기
데이터분석, 머신러닝

[프로젝트]따릉이 대여횟수예측_데이터분석 & ML

by kanb 2023. 1. 6.

import pandas as pd #판다스 패키지 불러오기
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor #랜덤 포레스트 불러오기
import matplotlib.pyplot as plt

#데이터 출처: 인공지능 경진대회 플랫폼 데이콘

#데이터 불러오기
train=pd.read_csv("C:/Users/bsg26/Downloads/따릉이/따릉이/train.csv") #모델 학습 파일
test=pd.read_csv('C:/Users/bsg26/Downloads/따릉이/따릉이/test.csv') #모델 시험지 파일
submission=pd.read_csv("C:/Users/bsg26/Downloads/따릉이/따릉이/submission.csv") #답안지 파일

# print(train.head())
# print(train.shape)

'''
id 고유 id
hour 시간
temperature 기온
precipitation 비가 오지 않았으면 0, 비가 오면 1
windspeed 풍속(평균)
humidity 습도
visibility 시정(視程), 시계(視界)(특정 기상 상태에 따른 가시성을 의미)
ozone 오존
pm10 미세먼지(머리카락 굵기의 1/5에서 1/7 크기의 미세먼지)
pm2.5 미세먼지(머리카락 굵기의 1/20에서 1/30 크기의 미세먼지)
count 시간에 따른 따릉이 대여 수
'''
'''
print(test.head())#test 데이터에는 count값이 없는데 이유는 count값을 우리가 찾아야하기 때문이다.

print(train.describe())#기술통계량 출력
a=train.groupby('hour').mean()['count'] #시간별 대여량의 평균값 산출)
print(a)
# a.plot() #뒤에 .plot을 붙이고 plt.show()를 하면된다.
# plt.show()

#또는
plt.plot(a, 'go-') #plt.plot()함수를 통해 그래프를 표현할 수 있다.
#'o'을 뒤에 붙이면 점으로 표현이 가능하고 실선도 같이 표현하고자 한다면 'o-'으로 표현하면된다.
#마커색 바꾸기: 'g'를 입력하면 된다. ex)'go-'

plt.grid() #보조선 그리기
plt.title('count by hours', fontsize=15) #제목
plt.xlabel('hour', fontsize=15) #x축
plt.ylabel('count', fontsize=15) #y축

#8시와 18시에 갑자기 증가한다를 보여주기위한 강조표시
plt.axvline(8,color='r')
plt.axvline(18,color='r') #color=이런식으로 명시를 해줘야한다.
plt.text(8,120,'go work', fontsize=10)
plt.text(18,250,'leave work', fontsize=10)

# plt.savefig('picture.png')#그림저장#ppt작업할 때 유용하다.
#---------------------------------
'''
#상관계수
'''
상관계수: 두 개의 변수가 같이 일어나는 강도를 나타내는 수치
-1~1 사이의 값을 지닙니다.
-1이나 1인 수치는 현실 세계에서 관측되기 힘든 수치입니다.
분야별로 기준을 정하는 것에 따라 달라지겠지만, 보통 0.4이상이면 두 개의 변수간에 상관성이 있다고 얘기합니다.

#상관관계는 인관관계와 다르다.
#상관관계가 더 큰 데이터를 뽑아보자. 그러기 위해 어떤 데이터가 상관관계가 높은지를 시각적으로 표현해 알아보자.
import seaborn as sns
plt.figure(figsize=(10,10))
sns.heatmap(train.corr(),annot=True) #anoot:수치표현함께, corr(): 상관관계표현
plt.show()
#우리는 count와 상관계수가 높은 것을 찾으면 된다.
'''
# =================================================
#데이터 전처리

#결측값 확인하기
print(train.isnull().sum())
#결측치가 어디에 있는지 확인하기
print(train[train['hour_bef_temperature'].isna()])
print(train.groupby('hour').mean()['hour_bef_temperature'])
#전체 평균 축그리기
plt.axhline(train.groupby('hour').mean()['hour_bef_temperature'].mean())

#결측값 채우기 .fillna()
train['hour_bef_temperature'].fillna({ 934:14.788136,1035:20.926667}, inplace=True)
#딕셔너리형태로 표현하였다. inplace=True를 쓰면 저장까지 완료!
# =============================================================
print(train.groupby('hour').mean()['hour_bef_windspeed'])


print(train[train['hour_bef_windspeed'].isna()])
print(train[train['hour_bef_windspeed'].isna()].index)
train['hour_bef_windspeed'].fillna({18:3.281356, 244:1.836667, 260: 1.620000, 376:1.965517, 780: 3.278333, 934: 1.965517, 1035: 1.633333,1138:2.766667, 1229:1.836667}, inplace=True)
#평균값을 직접 채워넣었다.
# plt.show()

#제대로 채워졌는지 확인하자.
print(train[train['hour_bef_windspeed'].isna()].index)
#완전히 채워넣었기때문에 더이상 isna()값이 없다.isna()

#======train 뿐만 아니라 test도 결측값이 있으면 안되기 때문에 test도 결측값처리를 해주어야한다.==========
print('test데이터에 결측값이 어디에 있는지 확인해보자_temperature')
print(test[test['hour_bef_temperature'].isna()].index)
print(test.groupby('hour').mean()['hour_bef_temperature'])
print(test[test['hour_bef_temperature'].isna()])
test['hour_bef_temperature'].fillna({653:26.110345},inplace=True)

print('test데이터에 결측값이 어디에 있는지 확인해보자_windspeed')
print(test[test['hour_bef_windspeed'].isna()].index)
print(test.groupby('hour').mean()['hour_bef_windspeed'])
print(test[test['hour_bef_windspeed'].isna()])
test['hour_bef_windspeed'].fillna({653:3.541379},inplace=True)


# =========================================
# 모델링..

features=['hour','hour_bef_temperature','hour_bef_windspeed']
X_train=train[features]
y_train=train['count']
X_test=train[features]

print(X_train.shape)
print(y_train.shape)
print(X_test.shape)

model=RandomForestRegressor()
DecisionTreeRegressor()

#다양한 옵션을 해봄으로 어떤 것이 더 잘 나오는지를 확인해본다: 튜닝
model100=RandomForestRegressor(n_estimators=100, random_state=0)
model100_5=RandomForestRegressor(n_estimators=100,max_depth=5,random_state=0)
model200=RandomForestRegressor(n_estimators=200)

model100.fit(X_train,y_train)
model100_5.fit(X_train,y_train)
model200.fit(X_train,y_train)

ypred1=model100.predict(X_test)
ypred2=model100_5.predict(X_test)
ypred3=model200.predict(X_test)

#답안지에 옮겨적기
submission['count']=ypred1
print(submission)
submission.to_csv('model100.csv',index=False)

submission['count']=ypred2
submission.to_csv('model100_5.csv',index=False)

submission['count']=ypred3
submission.to_csv('model200.csv',index=False)