필드명 | 설명 |
---|---|
datetime | hourly date + timestamp |
season | 1 = spring(봄), 2 = summer(여름), 3 = fall(가을), 4 = winter(겨울) |
holiday | whether the day is considered a holiday(휴일인지 아닌지) |
workingday | whether the day is neither a weekend nor holiday(주말도 휴일도 아닌 날인지) |
weather | 1: Clear, Few clouds, Partly cloudy, Partly cloudy 2: Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist 3: Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds 4: Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog |
temp | temperature in Celsius (온도) |
atemp | "feels like" temperature in Celsius (체감온도) |
humidity | relative humidity (습도) |
windspeed | wind speed (바람속도) |
casual | number of non-registered user rentals initiated (비가입자 사용유저) |
registered | number of registered user rentals initiated (가입자 사용유저) |
count | number of total rentals (전체 렌탈 대수) |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
train = pd.read_csv("../bike/train.csv", parse_dates=['datetime'])
test = pd.read_csv("../bike/test.csv", parse_dates=['datetime'])
sub = pd.read_csv("../bike/sampleSubmission.csv")
sel = ['season', 'weather', 'temp']
X_tr_all = train[sel] # 학습용 데이터의 변수 선택
y_tr_all = train['count'] # 학습용 데이터의 레이블 변수 선택
last_X_test = test[sel] # 최종 예측. 테스트 데이터의 변수 선택
X_train, X_test, y_train, y_test = train_test_split(X_tr_all,
y_tr_all,
test_size=0.3,
random_state=77)
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
# score()함수를 이용 - 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(model.score(X_test, y_test)))
model.predict(X_test) # 예측(새로운 데이터로)
학습용 세트 결정계수: 0.175 테스트 세트 결정계수: 0.163
array([207.35014841, 159.81017357, 235.16616427, ..., 145.59903806, 182.62193532, 53.83291236])
print( model.coef_ ) # 모델(선형회귀의 계수)
print( model.intercept_) # 모델(선형 회귀의 교차점)
[ 11.40588087 -30.62127051 8.66532654] 32.6138949247285
# sub = pd.read_csv("../bike/sampleSubmission.csv")
pred = model.predict(last_X_test) # 예측
sub['count'] = pred
sub
datetime | count | |
---|---|---|
0 | 2011-01-20 00:00:00 | 105.770886 |
1 | 2011-01-20 01:00:00 | 105.770886 |
2 | 2011-01-20 02:00:00 | 105.770886 |
3 | 2011-01-20 03:00:00 | 105.770886 |
4 | 2011-01-20 04:00:00 | 105.770886 |
... | ... | ... |
6488 | 2012-12-31 19:00:00 | 75.149616 |
6489 | 2012-12-31 20:00:00 | 75.149616 |
6490 | 2012-12-31 21:00:00 | 105.770886 |
6491 | 2012-12-31 22:00:00 | 105.770886 |
6492 | 2012-12-31 23:00:00 | 105.770886 |
6493 rows × 2 columns
# 처음 만는 제출용 csv 파일, 행번호를 없애기
sub.to_csv("firstsubmission.csv", index=False)
train.columns
Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp', 'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count'], dtype='object')
sel = ['season', 'holiday', 'workingday', 'weather', 'temp',
'atemp', 'humidity', 'windspeed']
X_tr_all = train[sel] # 학습용 데이터의 변수 선택
last_X_test = test[sel] # 테스트 데이터의 변수 선택
y_tr_all = train['count']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_tr_all,
y_tr_all,
test_size=0.3,
random_state=77)
model = LinearRegression()
model.fit(X_train, y_train)
# 결정계수 확인
print("학습용 세트 결정계수 : {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수 : {:.3f}".format(model.score(X_test, y_test)))
학습용 세트 결정계수 : 0.262 테스트 세트 결정계수 : 0.257
from sklearn.metrics import mean_absolute_error
preds = model.predict(X_test)
mean_absolute_error(preds, y_test)
115.49633229240679
from sklearn.preprocessing import PolynomialFeatures
sel = ['season', 'weather', 'temp']
X_tr = train[sel] # 학습용 데이터의 변수 선택
y = train['count']
last_X_test = test[sel] # 테스트 데이터의 변수 선택
transform from (x1, x2) to (1, x1, x2, x1^2, x1*x2, x2^2)
(x1, x2, x3) to (x1, x2, x3, x1^2, x2^2, x3^2, x1*x2, x1*x3, x2*x3) 3->9
include_bias=True일 경우, 1 추가
(1, x1, x2, x3, x1^2, x2^2, x3^2, x1*x2, x1*x3, x2*x3) 3->10
ex_X_tr = PolynomialFeatures(degree=2, include_bias=False).fit_transform(X_tr)
X_tr.shape, ex_X_tr.shape
((10886, 3), (10886, 9))
ex_X_test = PolynomialFeatures(degree=2,
include_bias=False).fit_transform(last_X_test)
last_X_test.shape, ex_X_test.shape
((6493, 3), (6493, 9))
X_train, X_test, y_train, y_test = train_test_split(ex_X_tr,
y,
test_size=0.3,
random_state=77)
model = LinearRegression()
model.fit(X_train, y_train)
# score()함수를 이용 - 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(model.score(X_test, y_test)))
학습용 세트 결정계수: 0.199 테스트 세트 결정계수: 0.182
다항회귀 적용 전 결정계수
학습용 세트 결정계수: 0.175
테스트 세트 결정계수: 0.163
from sklearn.preprocessing import MinMaxScaler
sel = ['season', 'holiday', 'workingday', 'weather', 'temp',
'atemp', 'humidity', 'windspeed']
X_tr = train[sel] # 학습용 데이터의 변수 선택
y_tr = train['count']
last_X_test = test[sel] # 테스트 데이터의 변수 선택
X_train, X_test, y_train, y_test = train_test_split(X_tr,
y_tr,
test_size=0.3,
random_state=77)
m1 = KNeighborsRegressor()
m1.fit(X_train, y_train)
pred = m1.predict(X_test)
# score()함수를 이용 - 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(m1.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(m1.score(X_test, y_test)))
학습용 세트 결정계수: 0.474 테스트 세트 결정계수: 0.212
from sklearn.metrics import mean_absolute_error
preds = m1.predict(X_test)
mean_absolute_error(pred, y_test)
116.17372933251684
scaler = MinMaxScaler().fit(X_tr)
nor_X_tr = scaler.transform(X_tr)
X_train, X_test, y_train, y_test = train_test_split(nor_X_tr,
y_tr,
test_size=0.3,
random_state=77)
X_train.min(), X_train.max(), X_test.min(), X_test.max()
(0.0, 1.0, 0.0, 1.0)
m2 = KNeighborsRegressor()
m2.fit(X_train, y_train)
pred = m2.predict(X_test)
# score()함수를 이용 - 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(m2.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(m2.score(X_test, y_test)))
학습용 세트 결정계수: 0.527 테스트 세트 결정계수: 0.292
from sklearn.metrics import mean_absolute_error
preds = m2.predict(X_test)
mean_absolute_error(pred, y_test)
107.95119412124923
from sklearn.linear_model import Ridge, Lasso
train.columns
Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp', 'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count'], dtype='object')
f_names = ['season', 'holiday', 'workingday', 'weather', 'temp',
'atemp', 'humidity', 'windspeed']
X_tr = train[f_names] # 학습용 데이터의 변수 선택
y = train['count']
last_X_test = test[f_names] # 테스트 데이터의 변수 선택
ex_X_tr = PolynomialFeatures(degree=3, include_bias=False).fit_transform(X_tr)
ex_X_test = PolynomialFeatures(degree=3,
include_bias=False).fit_transform(last_X_test)
X_tr.shape, ex_X_tr.shape, last_X_test.shape, ex_X_test.shape
((10886, 8), (10886, 164), (6493, 8), (6493, 164))
X_train, X_test, y_train, y_test = train_test_split(ex_X_tr,
y,
test_size=0.4,
random_state=11)
model = LinearRegression()
model.fit(X_train, y_train)
# 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(model.score(X_test, y_test)))
학습용 세트 결정계수: 0.351 테스트 세트 결정계수: 0.308
m1 = Ridge(alpha=0.10)
m1.fit(X_train, y_train)
# 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(m1.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(m1.score(X_test, y_test)))
학습용 세트 결정계수: 0.351 테스트 세트 결정계수: 0.308
model = Lasso(alpha=0.001)
model.fit(X_train, y_train)
# 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(model.score(X_test, y_test)))
학습용 세트 결정계수: 0.343 테스트 세트 결정계수: 0.310
C:\Users\totofriend\anaconda3\lib\site-packages\sklearn\linear_model\_coordinate_descent.py:647: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations, check the scale of the features or consider increasing regularisation. Duality gap: 6.977e+07, tolerance: 2.123e+04 model = cd_fast.enet_coordinate_descent(
# Linear Regression(선형 회귀), Ridge(리지), Lasso(라소)
model_list = [LinearRegression(), KNeighborsRegressor(),
Ridge(alpha=10), Lasso(alpha=0.001)]
for model in model_list:
model.fit(X_train, y_train)
print("모델 : ", model)
# 결정계수 확인
print("학습용 세트 결정계수: {:.3f}".format(model.score(X_train, y_train)))
print("테스트 세트 결정계수: {:.3f}".format(model.score(X_test, y_test)))
모델 : LinearRegression() 학습용 세트 결정계수: 0.351 테스트 세트 결정계수: 0.308 모델 : KNeighborsRegressor() 학습용 세트 결정계수: 0.482 테스트 세트 결정계수: 0.156 모델 : Ridge(alpha=10) 학습용 세트 결정계수: 0.350 테스트 세트 결정계수: 0.309 모델 : Lasso(alpha=0.001) 학습용 세트 결정계수: 0.343 테스트 세트 결정계수: 0.310
C:\Users\totofriend\anaconda3\lib\site-packages\sklearn\linear_model\_coordinate_descent.py:647: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations, check the scale of the features or consider increasing regularisation. Duality gap: 6.977e+07, tolerance: 2.123e+04 model = cd_fast.enet_coordinate_descent(
model = Lasso(alpha=0.001)
model.fit(X_train, y_train)
C:\Users\totofriend\anaconda3\lib\site-packages\sklearn\linear_model\_coordinate_descent.py:647: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations, check the scale of the features or consider increasing regularisation. Duality gap: 6.977e+07, tolerance: 2.123e+04 model = cd_fast.enet_coordinate_descent(
Lasso(alpha=0.001)
pred = model.predict(ex_X_test) # 예측
sub['count'] = pred
sub.loc[sub['count'] < 0, 'count'] = 0
sub.head(3)
datetime | count | |
---|---|---|
0 | 2011-01-20 00:00:00 | 105.416193 |
1 | 2011-01-20 01:00:00 | 66.081767 |
2 | 2011-01-20 02:00:00 | 66.081767 |
# 두번째 제출
sub.to_csv("second_sub.csv", index=False)