[R - ml] 决策树

install.packages(c('rpart', 'partykit', 'rpart.plot'))
require(rpart)
require(rpart.plot)
require(partykit)
require(caret)
set.seed(2014)
inTrain = createDataPartition(y = iris$Species, p = 0.8, list = FALSE)
irisTrain = iris[inTrain, ]
irisTest = iris[-inTrain, ]

treemodel <- rpart(Species~. , data = irisTrain)
summary(treemodel)
plot(treemodel)
text(treemodel)

prp(treemodel)
prp(treemodel, varlen = 5)

prediction <- predict(treemodel, newdata = irisTest, type = 'class')
table(prediction, irisTest$Species)

https://www.statmethods.net/advstats/cart.html
https://blog.revolutionanalytics.com/2013/06/plotting-classification-and-regression-trees-with-plotrpart.html

Case 2

数据准备

http://archive.ics.uci.edu/ml/datasets/Statlog+%28German+Credit+Data%29

credit = read.table('E:/rpath/german.data', header = F, sep = ' ' , stringsAsFactors = FALSE)

str(credit)
dim(credit)

一共1000个样本, 20个feature,最后一个为带预测的变量。
接下来我们需要给每一列加上一个说明

colnames(credit) = c("Status.of.existing.checking.account","Duration.in.month","Credit.history","Purpose","Credit.amount","Savings.account.bonds","Present.employment.since","Installment.rate.in.percentage.of.disposable.income","Personal.status.and.sex","Other.debtors.guarantors","Present.residence.since","Property","Age.in.years","Other.installment.plans.","Housing","Number.of.existing.credits.at.this.bank","Job","Number.of.people.being.liable.to.provide.maintenance.for","Telephone","foreign.worker","Good.Loan") # 最后一个属性命名为Good.Loan 特殊符号全换成.
# 出错 Sys.setlocale('LC_ALL','C')
mapping = list(
 "A11" = "  ... < 0 DM",
 "A12" = "0 <= ... < 200 DM",
 "A13" = "  ... >= 200 DM salary assignments for at least 1 year",
 "A14" = "no checking account",
 "A30" = "no credits taken all credits paid back duly",
 "A31" = "all credits at this bank paid back duly",
 "A32" = "existing credits paid back duly till now",
 "A33" = "delay in paying off in the past",
 "A34" = "critical account other credits existing not at this bank",
 "A40" = "car new",
 "A41" = "car used",
 "A42" = "furnitureequipment",
 "A43" = "radiotelevision",
 "A44" = "domestic appliances",
 "A45" = "repairs",
 "A46" = "education",
 "A47" = "vacation - does not exist",
 "A48" = "retraining",
 "A49" = "business",
 "A410" = "others",
 "A61" = "   ... < 100 DM",
 "A62" = " 100 <= ... < 500 DM",
 "A63" = " 500 <= ... < 1000 DM",
 "A64" = "   .. >= 1000 DM",
 "A65" = "unknown no savings account",
 "A71" = "unemployed",
 "A72" = "  ... < 1 year",
 "A73" = "1 <= ... < 4 years ",
 "A74" = "4 <= ... < 7 years",
 "A75" = "  .. >= 7 years",
 "A91" = "male - divorcedseparated",
 "A92" = "female - divorcedseparatedmarried",
 "A93" = "male - single",
 "A94" = "male - marriedwidowed",
 "A95" = "female - single",
 "A101" = "none",
 "A102" = "co-applicant",
 "A103" = "guarantor",
 "A121" = "real estate",
 "A122" = "if not A121 - building society savings agreement life insurance",
 "A123" = "if not A121A122 - car or other, not in attribute 6",
 "A124" = "unknown no property",
 "A141" = "bank",
 "A142" = "stores",
 "A143" = "none",
 "A151" = "rent",
 "A152" = "own",
 "A153" = "for free",
 "A171" = "unemployed unskilled - non-resident",
 "A172" = "unskilled - resident",
 "A173" = "skilled employee official",
 "A174" = "management self-employed highly qualified employee officer",
 "A191" = "none",
 "A192" = "yes, registered under the customers name",
 "A201" = "yes",
 "A202" = "no")

for(i in 1:(dim(credit))[2]) {
  if(class(credit[, i]) == 'character') {
    credit[, i] = as.factor(as.character(mapping[credit[, i]]))
  }
}
credit$Good.Loan = as.factor(ifelse(credit$Good.Loan == 1, 'GoodLoan', 'BadLoan'))

看起来点复杂,首先我们建立了一个从缩写到真实意义的映射变量mapping
下来对应每个为字符的列,我们对列的值进行映射。
最后将Good.Load转换为factor。

接下来对数据进行一个大致的了解:

table(credit$Status.of.existing.checking.account)
table(credit$Savings.account.bonds)
summary(credit$Duration.in.month) # 分布是右偏的,大的数据分布在右边
summary(credit$Credit.amount)
summary(credit$Good.Loan)

以上,完成了对数据的探索

构建训练与测试数据集

使用caret包 Classification and Regression Training 分类和回归训练

require(caret)
set.seed(2014)
inTrain = createDataPartition(y = credit$Good.Loan, p = 0.8, list = FALSE)
credit_train = credit[inTrain, ]
credit_test = credit[-inTrain, ]
prop.table(table(credit_train$Good.Loan))
prop.table(table(credit_test$Good.Loan))

另一种方法

set.seed(2014)
credit_rand = credit[order(runif(1000)), ]  # 均匀分布
credit_train = credit_rand[1:900, ]
credit_test = credit_rand[901:1000, ]
prop.table(table(credit_train$Good.Loan))
prop.table(table(credit_test$Good.Loan))

建立模型

我们使用C50包的c5.0算法

install.packages('C50')
require(C50)
credit_model = C5.0(credit_train[-21], credit_train$Good.Loan) # c50 包对字符要求很严格, 要剔除() :这类符号
credit_model
summary(credit_model)

这里的第一个decision, 372/46 代表有372 个样本达到该decision, 有46个错误的归类为 good loan。
整体而言错误率 15.4%,其中88个 bar loan 被归类到 good loan,35个 good loan 被归类为 bad loan。

m = C5.0(train, class, trials = 1, costs = NULL)
p = predict(m, test, type = 'class')

credit_pred = predict(credit_model, credit_test)
require(gmodels)
CrossTable(credit_test$Good.Loan, credit_pred,
           prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,
           dnn = c('actual loan status', 'predicted loan status'))

我们看到错误率 为 (26 + 37)/ 200 = 31.5%。
同时有61.7 % bad loan 我们归类为 good loan, 我们的错误率还只有 30%

模型优化

C5.0 中加入了 adaptive boosting 的支持。
boosting 的详细内容可以参考Wikipedia

credit_boost10 = C5.0(credit_train[-21], credit_train$Good.Loan, trials = 10) # trials 迭代的次数
credit_boost10
credit_pred10 = predict(credit_boost10, credit_test)
CrossTable(credit_test$Good.Loan, credit_pred10,
           prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,
           dnn = c('actual loan status', 'predicted loan status'))
error_cost = matrix(c(0, 1, 5, 0), nrow = 2) # 成本矩阵
rownames(error_cost) = c('GoodLoan', 'BadLoan')
colnames(error_cost) = c('GoodLoan', 'BadLoan')
credit_cost = C5.0(credit_train[-21], credit_train$Good.Loan, costs = error_cost)
credit_cost_pred = predict(credit_cost, credit_test)
CrossTable(credit_test$Good.Loan, credit_cost_pred,
           prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,
           dnn = c('actual loan status', 'predicted loan status'))

有次虽然总的错误率达到 47% , 但是把 bad loan 归类为 good loan的情况却大大减小
只有18.3%。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容