-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay4_Models.R
228 lines (175 loc) · 7.5 KB
/
Day4_Models.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
##---------------- 設定環境 ----------------
#setwd(dir) #設定working directory的存放位置
# MAC : setwd("/Users/rladiestaipei/R_DragonBall/")
# Windows :
setwd("C://Users/lee/Desktop/R_DragonBall/")
#--- Check Package (如果沒安裝過,會自動執行安裝)
packages.need <- c("caTools", "e1071", 'rpart', 'randomForest', 'xgboost', 'dplyr', 'Metrics')
packages.download <- !packages.need %in% installed.packages()[,"Package"]
if(any(packages.download))
install.packages(packages.need[packages.download],dependencies=TRUE)
#--- Load packaes
lapply(packages.need, require, character.only = TRUE)
##---------------- Load data and split ----------------
#--- Load data (根據 Day3 Feature Engineering 會產生整理完的資料檔,請去網站下載)
dataset <- read.csv('train_new.csv', stringsAsFactors = T)
# select features you want to put in models
# 這邊請根據前面幾天所學的去放入你認為重要的變數(如下只是範例)
dataset <- dataset %>% dplyr::select(SalePrice_log, X1stFlrSF, TotalBsmtSF, YearBuilt, LotArea,
Neighborhood, GarageCars, GarageArea,
GrLivArea_stand, MasVnrArea_stand, LotFrontage_log,
is_Fireplace, TotalBathrooms, TotalSF_stand)
# 部份類別變數用csv讀進來會是numeric,將之轉換成factor
dataset$is_Fireplace <- as.factor(dataset$is_Fireplace)
# Splitting the dataset into the Training set and Validation set
# library(caTools)
set.seed(1)
split <- sample.split(dataset$SalePrice_log, SplitRatio = 0.8)
training_set <- subset(dataset, split == TRUE)
val_set <- subset(dataset, split == FALSE)
##------------------------------------------------
## Part 1 : linear regression
##------------------------------------------------
# Fitting Multiple Linear Regression to the Training set
regressor <- lm(formula = SalePrice_log ~ .,
data = training_set)
# Predicting the Test set results
y_pred <- predict(regressor, newdata = val_set)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
##------------------------------------------------
## Part 2 : SVR
##------------------------------------------------
# Fitting SVR to the dataset
# library(e1071)
regressor <- svm(formula = SalePrice_log ~ .,
data = training_set,
type = 'eps-regression',
kernel = 'radial')
# Predicting the Test set results
y_pred <- predict(regressor, newdata = val_set)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
##------------------------------------------------
## Part 3 : Decision Tree
##------------------------------------------------
# Fitting Decision Tree Regression to the dataset
# library(rpart)
regressor <- rpart(formula = SalePrice_log ~ .,
data = training_set,
control = rpart.control(minsplit = 1))
# Predicting the Test set results
y_pred <- predict(regressor, newdata = val_set)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
##------------------------------------------------
## Part 4 : Random Forest
##------------------------------------------------
# Fitting Random Forest Regression to the dataset
# library(randomForest)
set.seed(1)
regressor <- randomForest(formula = SalePrice_log ~ .,
data = training_set,
ntree = 500)
# Predicting the Test set results
y_pred <- predict(regressor, newdata = val_set)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
##------------------------------------------------
## Part 5 : XGBoost
##------------------------------------------------
# library(xgboost)
# 因XGBoost是吃matrix的格式,故須將所有資料皆轉換為數值型,存入矩陣中
# transfer all feature to numeric
training_set_new <- training_set %>% dplyr::select(-SalePrice_log)
val_set_new <- val_set %>% dplyr::select(-SalePrice_log)
cat_index <- which(sapply(training_set_new, class) == "factor")
training_set_new[cat_index] <- lapply(training_set_new[cat_index], as.numeric)
val_set_new[cat_index] <- lapply(val_set_new[cat_index], as.numeric)
# put testing & training data into two seperates Dmatrixs objects
labels <- training_set$SalePrice_log
dtrain <- xgb.DMatrix(data = as.matrix(training_set_new),label = labels)
dval <- xgb.DMatrix(data = as.matrix(val_set_new))
# set parameters
param <-list(objective = "reg:linear",
booster = "gbtree",
eta = 0.01, #default = 0.3
gamma=0,
max_depth=3, #default=6
min_child_weight=4, #default=1
subsample=1,
colsample_bytree=1
)
# Fitting XGBoost to the Training set
set.seed(1)
regressor <- xgb.train(params = param, data = dtrain, nrounds = 3000
#watchlist = list(train = dtrain, val = dval),
#print_every_n = 50, early_stopping_rounds = 300
)
# Predicting the Test set results
y_pred <- predict(regressor, dval)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
##------------------------------------------------
## 本日小挑戰
##------------------------------------------------
#請試著改變randomforest與XGBoost模型的參數,重新訓練模型並輸出各自的rmse
##------------------------------------------------
## Random Forest
##------------------------------------------------
# Fitting Random Forest Regression to the dataset
# library(randomForest)
set.seed(1)
regressor <- randomForest(formula = SalePrice_log ~ .,
data = training_set,
ntree = 450,
proximity = TRUE,
mtry = 4
)
# Predicting the Test set results
y_pred <- predict(regressor, newdata = val_set)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)
# Observe that what is the best number of trees
plot(regressor)
#tune mtry value
tuneRF(training_set[,-14], training_set[,14])
#變數重要性
importance(regressor)
#變數重要性圖型
varImpPlot(regressor)
##------------------------------------------------
## XGBoost
##------------------------------------------------
# library(xgboost)
# 因XGBoost是吃matrix的格式,故須將所有資料皆轉換為數值型,存入矩陣中
# transfer all feature to numeric
training_set_new <- training_set %>% dplyr::select(-SalePrice_log)
val_set_new <- val_set %>% dplyr::select(-SalePrice_log)
cat_index <- which(sapply(training_set_new, class) == "factor")
training_set_new[cat_index] <- lapply(training_set_new[cat_index], as.numeric)
val_set_new[cat_index] <- lapply(val_set_new[cat_index], as.numeric)
# put testing & training data into two seperates Dmatrixs objects
labels <- training_set$SalePrice_log
dtrain <- xgb.DMatrix(data = as.matrix(training_set_new),label = labels)
dval <- xgb.DMatrix(data = as.matrix(val_set_new))
# set parameters
param <-list(objective = "reg:linear",
booster = "gbtree",
eta = 0.01, #default = 0.3
gamma = 0,
max_depth = 3, #default=6
min_child_weight = 4, #default=1
subsample = 0.5,
colsample_bytree = 1
)
# Fitting XGBoost to the Training set
set.seed(1)
regressor <- xgb.train(params = param, data = dtrain, nrounds = 3000
#watchlist = list(train = dtrain, val = dval),
#print_every_n = 50, early_stopping_rounds = 300
)
# Predicting the Test set results
y_pred <- predict(regressor, dval)
# performance evaluation
rmse(val_set$SalePrice_log, y_pred)