1.項目介紹
數據集包含某年9月份歐洲用戶在兩天時間里發生的284807宗交易,其中包括492宗詐騙。項目通過描述性分析探索詐騙案的相關特點和模式,再通過機器學習算法創建預測模型、調參,並通過混淆矩陣等方法選擇模型。
2.數據清理
2.1導入數據
library(data.table) # fread() # 載入數據 cards<-fread("D:/R/practise/……/creditcard.csv") # 原始數據集有143MB,用數據操作包data.table,fread函數讀取速度是原生函數的近10倍。
2.2 數據概覽
查看數據總體情況、變量類型、缺失值、 異常值、分布類型等等
library(VIM) # aggr()
# 查看數據總體情況,建立數據詞典
str(cards) summary(cards) aggr(cards) # 可視化缺失值 # 其他判斷缺失值辦法:table(is.na(cards)) # 查看樣本數據分布 prop.table(table(cards$Class)) # 正例為僅為0.001727486 qplot(x=cards$Class,data=cards,geom="bar",fill=cards$Class) # 可視化效果
數據詞典
缺失值情況:無
樣本分布情況:正類僅為0.001727486,占比例非常低,據此訓練的模型,對正類(詐騙)案件不敏感,會更偏向識別正常交易。在訓練模型時候需要對訓練集做調整(詳情見后)
2.3 數據處理
# 數據塑形 時間轉換 秒——小時 cards$Time_new<-round(cards$Time/3600,0) # 將時間以秒為單位轉換為 以小時為單位 cards$Time<-NULL # 數據集中原時間變量已經無效,可刪 cards<-cards %>% select(Class,everything()) # 將變量Class調整到第一列 class(cards$Class) cards$Class<-as.factor(cards$Class) # 變量class轉換為因子型
# 解決數據失衡問題
cards_0<-cards[cards$Class=='0'] # 正常 非詐騙交易
cards_1<-cards[cards$Class=='1'] # 詐騙案例
index1<-sample(1:nrow(cards_0),size = nrow(cards_1))
# 合並數據集
cards_new<-rbind(cards_1,cards_0[index1])
# 歸一化處理
library(caret)
standard <- preProcess(cards_new, method = 'range') # caret包中函數,range表示區間為[-1:1]
card_new2 <- predict(standard, cards_new)
traindata_2 <- card_new2[index2, ] # index2 見52行
testdata_2 <- card_new2[-index2, ]
2.4 數據划分
# 對新數據集進行做訓練集、測試集的划分 index2<-createDataPartition(cards_new$Class,times = 1,p=.7,list = F) train_cards<-cards_new[index2,] # 訓練集 test_cards<-cards_new[-index2,] # 測試集
3.數據探索——描述性統計分析
數據集中第2列到第28列都是PCA數據,無法做有效描述性統計分析,故這里主要基於時間、金額等進行分析。
# 詐騙案發生時間、金額分布 p1<-ggplot(cards_1,aes(x=factor(Time_new),fill=factor(Time_new)))+ geom_bar(stat = 'count')+ labs(title = 'Time Distribution of\nFraud Cases',x='Time',y='Count')+ theme_classic()+ theme(legend.position='none') # 計算每小時詐騙案涉及金額 # cards_1$Time_new<-as.factor(as.character(cards_1$Time_new)) Amount_money<-rowsum(cards_1$Amount,group=cards_1$Time_new) # 數據准備 Amount_c<-Amount_money[,1] Time_c<-0:47 DF_money<-data.frame(Time_c,Amount_c) p2<-ggplot(DF_money,aes(x=factor(Time_c),y=Amount_c,fill=Time_c))+ geom_bar(stat = 'identity')+ labs(title = 'Distribution bar chart of \nfraud amount',x='Time')+ theme(legend.position='none') library(Rmisc) multiplot(p1,p2,cols = 1)
描述性分析結論:
從總趨勢說,第一天多余第二天(但因為沒有更多的數據,更長的時間軸,這一點無法得出有效結論);
整體看每小時平均詐騙數量在10次以下,涉案金額在500歐元左右;
從時間上說,詐騙發生次數在一天中的后半夜居多;
從涉案金額來說,而平均詐騙金額基本與次數相對應。其中第二天凌晨兩點發生次數最多,30余起,對應的金額也是最大,超過3000歐元。
4.數據建模
4.1 隨機森林模型
# 使用五折交叉驗證方法建立隨機森林模型
set.feed(1234) model_rf <- train(Class ~., data = train_cards, method = 'rf', trControl = trainControl(method = 'cv', number = 5, selectionFunction = 'oneSE')) # 利用訓練集建立隨機森林模型 pred_model<-predict(model_rf,test_cards[,-1]) # 測試模型 confusionMatrix(data=pred_model,reference=test_cards$Class) # 准確率為94.9% plot(varImp(model_rf)) # 查看模型中變量的重要程度
查看模型:
查看模型中變量的重要程度:
4.2 K近鄰值算法(KNN算法)
results = c() # 創建一個空向量 for(i in 1:10) { set.seed(1234) pred_knn <- knn(train=traindata_2[,2:30], test=testdata_2[,2:30], cl=traindata_2$Class, i) Table <- table(pred_knn, testdata_2$Class) accuracy <- sum(diag(Table))/sum(Table) # diag()提取對角線上的值 results <- c(results, accuracy) } plot(x = 1:10, y = results, type = 'b', col = 'blue', xlab = 'k', ylab = 'accuracy')
# 根據圖像k=4時,准確率最高。 pred_knn <- knn(train=traindata_2[,2:30], test=testdata_2[,2:30], cl=traindata_2$Class, 4) confusionMatrix(pred_knn,testdata_2$Class) # 准確率為95.24%
4.3 模型評估
通過隨機森林、k近鄰算法分別得到model_rf、pred_knn兩個模型,下面根據查全率、查准率和kappa三個維度評估模型。
5.結論
模型pred_knn在查全率、查准率以及kappa三個評估維度上都高於model_rf,其中查准率達到95.24%,在134個詐騙案中,只有1個判斷錯誤,可用性比較高。
補充
為了方便描述,添加包沒有放在文前
# 加載添加包 library(data.table) # fread() library(VIM) # aggr() library(caret) # 機器學習相關 library(dplyr) # select() library(ggplot2) # ggplot/qplot library(Rmisc) # multiplot() library(randomForest) # 隨機森林 library(class) # knn模型