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的更多相关文章

  1. R语言系列:生成数据

    R语言系列:生成数据 (2014-05-04 17:41:57) 转载▼ 标签: r语言 教育 分类: 生物信息 生成规则数据1.使用“:“,如x=1:10,注意该方法既可以递增也可以递减,如y=10 ...

  2. R语言中的横向数据合并merge及纵向数据合并rbind的使用

    R语言中的横向数据合并merge及纵向数据合并rbind的使用 我们经常会遇到两个数据框拥有相同的时间或观测值,但这些列却不尽相同.处理的办法就是使用merge(x, y ,by.x = ,by.y ...

  3. 用R语言实现对不平衡数据的四种处理方法

    https://www.weixin765.com/doc/gmlxlfqf.html 在对不平衡的分类数据集进行建模时,机器学**算法可能并不稳定,其预测结果甚至可能是有偏的,而预测精度此时也变得带 ...

  4. R语言︱噪声数据处理、数据分组——分箱法(离散化、等级化)

    每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 分箱法在实际案例操作过程中较为常见,能够将一些 ...

  5. R语言数据集合并、数据增减、不等长合并

    每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 数据选取与简单操作: which 返回一个向量 ...

  6. R语言读取matlab中数据

    1. 在matlab中将数据保存到*.mat 文件夹 save("data.mat","data","label")#将data和label ...

  7. R语言:导入导出数据

    主要学习如何把几种常用的数据格式导入到R中进行处理,并简单介绍如何把R中的数据保存为R数据格式和csv文件. 1.保存和加载R的数据(与R.data的交互:save()函数和load()函数) a & ...

  8. DT包 -- R语言中自定义表格数据

    DT 包提供了 JavaScript 库 DataTables 的一个R接口,它使得R对象(矩阵或数据框)可以在HTML页面上显示为表格. 该包的DataTables函数生成的表格提供了数据的筛选.分 ...

  9. 吴裕雄--天生自然 R语言开发学习:数据集和数据结构

    数据集的概念 数据集通常是由数据构成的一个矩形数组,行表示观测,列表示变量.表2-1提供了一个假想的病例数据集. 不同的行业对于数据集的行和列叫法不同.统计学家称它们为观测(observation)和 ...

随机推荐

  1. 如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

    前言 软件系统中总是希望做到松耦合,项目的组织形式也是一样,本篇文章将介绍在ASP.NET CORE MVC中怎么样将Controller与主网站项目进行分离,并且对Areas进行支持. 实践 1.新 ...

  2. window server2012 许可证过期

    研发的服务器装得windows server 2012 Standard ,许可证只有半年使用时间,过期了老是自动关机,于是在网上找了下,最终找了个可以用的方法,记录下,留用 步骤: 1.cmd命令打 ...

  3. es6基础系列一:let和const

    let 声明变量,可以说是具有作用域的var,用于声明变量,主要规则如下: 1 let声明的变量拥有块级作用域 { let i = 1; console.log(i); // 1 } console. ...

  4. 跟着刚哥梳理java知识点——基本数据类型(三)

    1.8种基本数据类型 1)4种整数类型(byte.short.int.long) [知识点] 类型 存储空间 数值范围 byte 1字节=8位 -128-127 short 2字节 -2的15次方-2 ...

  5. Webdriver API之操作(一)

    一. 控制浏览器 1. 控制浏览器大小 driver.set_window_size(480,800) #浏览器宽480,高800显示 dirver.maximize_window() #浏览器最大化 ...

  6. Java NIO之通道

    一.前言 前面学习了缓冲区的相关知识点,接下来学习通道. 二.通道 2.1 层次结构图 对于通道的类层次结构如下图所示. 其中,Channel是所有类的父类,其定义了通道的基本操作.从 Channel ...

  7. 【模板】Dijkstra的heap优化

    为了将最小费用最大流的spfa优化,决定将spfa换成heap优化的Dijkstra.(dijkstra不能处理负边权) 所以还得现学... 白点表示已经确定最短路径的点. 蓝点表示还未确定最短路径的 ...

  8. C#处理JSON 数据

    网络中数据传输经常是xml或者json,现在做的一个项目之前调其他系统接口都是返回的xml格式,刚刚遇到一个返回json格式数据的接口,通过例子由易到难总结一下处理过程,希望能帮到和我一样开始不会的朋 ...

  9. CSS背景图片常见属性设置

    在CSS中,图片属性的设置是必不可少的,下面介绍一下常见的图片属性: 1)背景图片插入:background-image:url(位置及名称);  //默认在父级元素内的左上角 2)背景平铺方式:ba ...

  10. fuse on TDH4.8

    一.安装依赖包 yum install autoconf.noarch yum install automake yum install libtool* yum install m4 yum ins ...