用R语言对一个信用卡数据实现logit,GBM,knn,xgboost
Prepare the data
数据来自UCIhttp://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening,一个信a用卡的数据,具体各项变量名以及变量名代表的含义不明(应该是出于保护隐私的目的),本文会用logit,GBM,knn,xgboost来对数据进行分类预测,对比准确率
预计的准确率应该是:
xgboost > GBM > logit > knn
Download the data
dataset = read.table("http://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening/crx.data", sep = ",", essay-header = F, na.strings = "?")
head(dataset)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16
1 b 30.83 0.000 u g w v 1.25 t t 1 f g 202 0 +
2 a 58.67 4.460 u g q h 3.04 t t 6 f g 43 560 +
3 a 24.50 0.500 u g q h 1.50 t f 0 f g 280 824 +
4 b 27.83 1.540 u g w v 3.75 t t 5 t g 100 3 +
5 b 20.17 5.625 u g w v 1.71 t f 0 f s 120 0 +
6 b 32.08 4.000 u g m v 2.50 t f 0 t g 360 0 +
## save.csv(dataset,file = "creditCard.csv")
以上是数据的形式,接下来看下数据是否有缺失值和各个数据的类型
sapply(dataset,function(x) sum(is.na(x)))
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16
12 12 0 6 6 9 9 0 0 0 0 0 0 13 0 0
sapply(dataset,class)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
"factor" "numeric" "numeric" "factor" "factor" "factor" "factor" "numeric" "factor" "factor"
V11 V12 V13 V14 V15 V16
"integer" "factor" "factor" "integer" "integer" "factor"
Train and Test
分割数据的训练集和测试集,这里set.seed(123),设定70%的训练集,30%的测试集.
set.seed(123)dataset = na.omit(dataset)n = dim(dataset)[1]index = sample(n,round(0.7*n))train = dataset[index,]test = dataset[-index,]dim(train)
[1] 457 16
dim(test)
[1] 196 16
Change the variable into dummy variables
有时候,需要转化变量为哑变量,因为在一些挖掘场合,数据不能直接使用因子型的数据:
knn
glmnet
svm
xgboost
有些挖掘方法是可以使用因子变量的,比如:
logistic regression
raprt
GBM
randomforest
dataset2 = datasetlibrary(plyr)into_factor = function(x){
if(class(x) == "factor"){
n = length(x)
data.fac = data.frame(x = x,y = 1:n)
output = model.matrix(y~x,data.fac)[,-1]
## Convert factor into dummy variable matrix
}else{
output = x
## if x is numeric, output is x
}
output
}into_factor(dataset$V4)[1:5,]
xu xy
1 1 0
2 1 0
3 1 0
4 1 0
5 1 0
dataset2 = colwise(into_factor)(dataset2)dataset2 = do.call(cbind,dataset2)dataset2 = as.data.frame(dataset2)head(dataset2)
V1 V2 V3 xu xy xgg xp xc xcc xd xe xff xi xj xk xm xq xr xw xx xdd xff xh xj xn xo xv xz
1 1 30.83 0.000 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0
2 0 58.67 4.460 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
3 0 24.50 0.500 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
4 1 27.83 1.540 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0
5 1 20.17 5.625 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0
6 1 32.08 4.000 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0
V8 V9 V10 V11 V12 xp xs V14 V15 V16
1 1.25 1 1 1 0 0 0 202 0 1
2 3.04 1 1 6 0 0 0 43 560 1
3 1.50 1 0 0 0 0 0 280 824 1
4 3.75 1 1 5 1 0 0 100 3 1
5 1.71 1 0 0 0 0 1 120 0 1
6 2.50 1 0 0 1 0 0 360 0 1
dim(dataset2)
[1] 653 38
Logistic Regression
使用logistic回归来进行测试建模和预测,使用的函数是glm
logit.model = glm(V16~.,data = train,family = "binomial")logit.response = predict(logit.model,test,type = "response")logit.predict = ifelse(logit.response>0.5,"+","-")table(logit.predict,test$V16)
logit.predict - +
- 90 24
+ 13 69
accurancy1 = mean(logit.predict == test$V16)accurancy1
[1] 0.81122
GBM
使用GBM方法来进行预测,这里用的是caret,repeat-cv来选择最优树
library(caret)
ctrl = trainControl(method = "repeatedcv", number = 5, repeats = 5)set.seed(300)m_gbm = train(V16 ~ ., data=train, method = "gbm", metric = "Kappa", trControl = ctrl)
gbm.predict = predict(m_gbm,test)table(gbm.predict,test$V16)
accurancy2 = mean(gbm.predict == test$V16)accurancy2
[1] 0.85714
knn method for classification
knn set k = 5
This is a model without cross-validation
首先测试一个knn模型,不做CV,不做标准化,不做数据类型转换得到的结果,这里,不转换数据类型会把因子类型的变量舍弃,仅保留数值变量
library(caret)knn.model1 = knn3(V16 ~ .,data = train, k = 5)
knn.response1 = predict(knn.model1,test,class = "response")
knn.predict1 = ifelse(knn.response1[,1]<0.5,"+","-")
table(knn.predict1,test$V16)
knn.predict1 - +
- 78 48
+ 25 45
mean(knn.predict1 == test$V16)
[1] 0.62755
knn after scale
After scaling and convert into dummy variables:
经过标准化和数据转换之后的准确率:
knn.dataset = cbind(
colwise(scale)(dataset2[,-38]),V16 = as.factor(dataset2$V16)
)
set.seed(123)
index = sample(n,round(0.7*n))
train.knn = knn.dataset[index,]
test.knn = knn.dataset[-index,]
knn.model1 = knn3(V16 ~ .,data = train.knn, k = 5)
knn.predict1 = predict(knn.model1,test.knn,,type = "class") table(knn.predict1,test.knn$V16)
knn.predict1 0 1
0 89 32
1 14 61
mean(knn.predict1 == test.knn$V16)
[1] 0.76531
knn CV for k
my-try
不管是我的这个程序函数caret,总算出来应该是k=2的时候误差最小,但是实际情况不是这样
library(class)cv.knn = function(data,n=5,k){
index = sample(1:5,nrow(data),replace = T)
acc=0
for ( i in 1:5){
ind = index == i
train = data[-ind,]
test = data[ind,]
knn.model1 = knn3(V16 ~ .,data = train, k = k)
knn.predict= predict(knn.model1,test,type = "class")
acc[i] = mean(knn.predict == test$V16)
}
mean(acc)}cv.knn(train.knn,3,5)
[1] 0.8533
k = 2:20set.seed(123)acc = sapply(k,function(x) cv.knn(train.knn,3,x))plot(k,acc,type = "b")
k.final = which.max(acc)knn.model.f = knn3(V16 ~ .,data = train.knn, k = k.final) knn.predict.f = predict(knn.model.f,test.knn,type = "class")
table(knn.predict.f,test.knn$V16)
knn.predict.f 0 1
0 81 31
1 22 62
mean(knn.predict.f == test.knn$V16)
[1] 0.72959
library(caret)
fitControl <- trainControl(method = "cv", number = 10)
knnTune <- train(x = dataset2[1:37], y = dataset2[,38], method = "knn", preProc = c("center", "scale"),tuneGrid = data.frame(.k = 1:20), trControl = fitControl)
直接train,test来看:
效果是k=5最好
knn_train_test = function(train,test,k =5){
knn.model.f = knn3(V16 ~ .,data = train, k = k)
knn.predict.f = predict(knn.model.f,test,type = "class")
mean(knn.predict.f == test$V16)}x = 1:20result =
sapply(x, function(x) knn_train_test(train.knn,test.knn,k = x)) plot(x,result,type = "b")
k.final = which.max(result)accurancy3 = knn_train_test(train.knn,test.knn,k = k.final)accurancy3
[1] 0.75
xgboost
Install:
## devtools::install_github('dmlc/xgboost',subdir='R-package')
require(xgboost)
require(methods)
require(plyr)
set.seed(123)
set.seed(123)
index = sample(n,round(0.7*n))
train.xg = dataset2[index,]
test.xg = dataset2[-index,]
label <- as.matrix(train.xg[,38,drop =F])
data <- as.matrix(train.xg[,-38,drop =F])
data2 <- as.matrix(test.xg[,-38,drop =F])
label2 = as.matrix(test.xg[,38,drop =F])
# weight <- as.numeric(dtrain[[32]]) * testsize / length(label)
xgmat <- xgb.DMatrix(data, label = label, missing = -10000)
param <- list("objective" = "binary:logistic","bst:eta" = 1,"bst:max_depth" = 2,"eval_metric" = "logloss","silent" = 1,"nthread" = 16 ,"min_child_weight" =1.45)
nround =275
bst = xgb.train(param, xgmat, nround )
res1 = predict(bst,data2)
pre1 = ifelse(res1>0.5,1,0)
table(pre1,label2)
label2
pre1 0 1
0 91 15
1 12 78
accurancy4 = mean(pre1 ==label2)
accurancy4
[1] 0.86224
Final Results
| Method | Accurancy |
|---|---|
| logistic regression | 0.81122 |
| GBM | 0.85714 |
| knn | 0.75 |
| xgboost | 0.86224 |
用R语言对一个信用卡数据实现logit,GBM,knn,xgboost的更多相关文章
- R语言系列:生成数据
R语言系列:生成数据 (2014-05-04 17:41:57) 转载▼ 标签: r语言 教育 分类: 生物信息 生成规则数据1.使用“:“,如x=1:10,注意该方法既可以递增也可以递减,如y=10 ...
- R语言中的横向数据合并merge及纵向数据合并rbind的使用
R语言中的横向数据合并merge及纵向数据合并rbind的使用 我们经常会遇到两个数据框拥有相同的时间或观测值,但这些列却不尽相同.处理的办法就是使用merge(x, y ,by.x = ,by.y ...
- 用R语言实现对不平衡数据的四种处理方法
https://www.weixin765.com/doc/gmlxlfqf.html 在对不平衡的分类数据集进行建模时,机器学**算法可能并不稳定,其预测结果甚至可能是有偏的,而预测精度此时也变得带 ...
- R语言︱噪声数据处理、数据分组——分箱法(离散化、等级化)
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 分箱法在实际案例操作过程中较为常见,能够将一些 ...
- R语言数据集合并、数据增减、不等长合并
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 数据选取与简单操作: which 返回一个向量 ...
- R语言读取matlab中数据
1. 在matlab中将数据保存到*.mat 文件夹 save("data.mat","data","label")#将data和label ...
- R语言:导入导出数据
主要学习如何把几种常用的数据格式导入到R中进行处理,并简单介绍如何把R中的数据保存为R数据格式和csv文件. 1.保存和加载R的数据(与R.data的交互:save()函数和load()函数) a & ...
- DT包 -- R语言中自定义表格数据
DT 包提供了 JavaScript 库 DataTables 的一个R接口,它使得R对象(矩阵或数据框)可以在HTML页面上显示为表格. 该包的DataTables函数生成的表格提供了数据的筛选.分 ...
- 吴裕雄--天生自然 R语言开发学习:数据集和数据结构
数据集的概念 数据集通常是由数据构成的一个矩形数组,行表示观测,列表示变量.表2-1提供了一个假想的病例数据集. 不同的行业对于数据集的行和列叫法不同.统计学家称它们为观测(observation)和 ...
随机推荐
- 07 The VC Dimension
当N大于等于2,k大于等于3时, 易得:mH(N)被Nk-1给bound住. VC维:最小断点值-1/H能shatter的最大k值. 这里的k指的是存在k个输入能被H给shatter,不是任意k个输入 ...
- ado.net知识整理
对ado.net总是半知半解,五大对象也总是混淆,近期自己做小项目练手,整理了一些知识点 ado.net的无要素(摘自其他博文) Connection 物件 Connection 对象主要是开启 ...
- [Python]peewee使用经验
peewee 使用经验 本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作.所以,没有使用过 peewee,可以先阅读文档 正确 ...
- 如何快速将本地项目托管到到github上?
1,打开你的本地项目文件夹,比如 test-demo: 2,打开github(没有github的要自己注册下), 点击new repository 3,填写项目信息,创建项目 4,复制新建的项目url ...
- .NET程序员也学Node.js——初识Node.js
清明在石门休了八天假,一眨眼,4月又到中旬了...看到.NET在天朝彻底沦陷而又无能为力,我开始尝试去学习一些新的东西来充实自己,我自然是打死不会去学java的,没有为什么,于是乎,最近开始学习一些前 ...
- Angular.js学习笔记 (一)
- angular中最重要的概念是指令(directive)- ng-model 是双向数据绑定的指令,效果就是将当前元素的value属性和模型中的[user.name]建立绑定关系### 模块(Mo ...
- 跟着刚哥梳理java知识点——包装类(十)
Java为8种基本数据类型都提供了对应的包装器类型 装箱和拆箱: public class Main { public static void main(String[] args) { Intege ...
- windows升级到1607后操作很卡顿的解决办法
CPU I5,固态128G,win7主系统,WIN10和WIN7都安装在固态硬盘上. 未升级之前,操作很流畅,以至于把家里的老古董电脑也换固态,系统换WIN10了.自从升级了1607后这个问题就出现了 ...
- jQuery控制元素隐藏和显示
1.jQuery隐藏和显示效果 通过 jQuery,您可以使用 hide() 和 show() 方法来隐藏和显示 HTML 元素: $("#hide").click(functio ...
- Spring+SpringMVC+Mybaties整合之配置文件如何配置及内容解释--可直接拷贝使用--不定时更改之2017/4/27
以下配置可直接使用,只需更改包名. 关于内部标签的解释及用法,都以注解形式在代码内部说明.个人原创,转载需注明出处. 1,web.xml.添加jar包后首先需要配置WEB-INF下的web.xml文件 ...