R XGBoost

Jmnote (토론 | 기여)님의 2020년 5월 9일 (토) 16:54 판 (새 문서: ==개요== ;R XGBoost <source lang='r' run> set.seed(42) # 랜덤값 고정 # 데이터 준비 df = iris num_class = 3 class = df$Species level = levels(df$Species) label = as.integ...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

R XGBoost
set.seed(42) # 랜덤값 고정

# 데이터 준비
df = iris
num_class = 3
class = df$Species
level = levels(df$Species)
label = as.integer(class)-1 # 0기반
df$Species = NULL

# 데이터 분할
idx = createDataPartition(class, list=F, p=0.75)
train.data = as.matrix(df[ idx,])
test.data  = as.matrix(df[-idx,])
train.label = label[ idx]
test.label  = label[-idx]
dtrain = xgb.DMatrix(data=train.data, label=train.label)
dtest  = xgb.DMatrix(data=test.data , label=test.label )
watchlist = list(train=dtrain, eval=dtest)

# 모델 적합
library(xgboost)
param = list(max_depth=2, eta=1, verbose=0, nthread=2,
             objective="multi:softprob", eval_metric="mlogloss",
             num_class=num_class)
model = xgb.train(param, dtrain, nrounds=2, watchlist)

# 모델 정보
model

# 테스트
pred = as.data.frame(predict(model,test.data,reshape=T))
colnames(pred) = levels(class)
pred$prediction = apply(pred,1,function(x) colnames(pred)[which.max(x)])
pred$label = level[test.label+1]

# 분류표
table(pred$prediction, pred$label)
# 정분류율(accuracy)
sum(pred$prediction==pred$label)/nrow(pred)

2 같이 보기

3 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}