对于teengamb数据集进行神经网络分类
MLP神经网络介绍:
MLP(Multi-Layer Perceptron),即多层感知器,是一种趋向结构的人工神经网络,映射一组输入向量到一组输出向量。
MLP可以被看做是一个有向图,由多个节点层组成,每一层全连接到下一层。除了输入节点,每个节点都是一个带有非线性激活函数的神经元(或称处理单元)。一种被称为反向传播算法的监督学习方法常被用来训练MLP。MLP是感知器的推广,克服了感知器无法实现对线性不可分数据识别的缺点。
在 faraway 包中,包含一个 47 行 5 列的 teengamb 数据集(加载 faraway包后,可通过代码“head(teengamb)”查看数据的前 5 行,通过“?teengamb”查看每个变量的具体意义),该数据是研究关于青少年赌博情况的数据集。针对该数据集,请回答以下问题:
数据集概况:
> head(teengamb)
sex status income verbal gamble
1 1 51 2.00 8 0.0
2 1 28 2.50 8 0.0
3 1 37 2.00 6 0.0
4 1 28 7.00 4 7.3
5 1 65 2.00 8 19.6
6 1 61 3.47 6 0.1
程序如下:
library(neuralnet)
library(NeuralNetTools)
library(readr)
library(psych)
library(Metrics)
library(ggplot2)
library(caret)
library(Metrics)
library(dplyr)
library(corrplot)
library(faraway)
library(ggcorrplot)
library(tidyr)
library(GGally)
data(teengamb)
head(teengamb)
teengamb<-teengamb
sigmlp <- neuralnet(sex~.,data = teengamb,
hidden = c(10),linear.output = FALSE,
act.fct = "logistic",algorithm = "rprop+")
summary(sigmlp)
label<-predict(sigmlp,teengamb[,2:5],type = "response")
label <- as.factor(ifelse(label > 0.5,1,0))#将数据规范为0,1
table(teengamb$sex,label)
sprintf("MLP神经网络的精度为:%f",accuracy(teengamb$sex,label))
结果如下:
> summary(sigmlp)
Length Class Mode
call 7 -none- call
response 47 -none- numeric
covariate 188 -none- numeric
model.list 2 -none- list
err.fct 1 -none- function
act.fct 1 -none- function
linear.output 1 -none- logical
data 5 data.frame list
exclude 0 -none- NULL
net.result 1 -none- list
weights 1 -none- list
generalized.weights 1 -none- list
startweights 1 -none- list
result.matrix 64 -none- numeric
> table(teengamb$sex,label)
label
0 1
0 28 0
1 2 17
> sprintf("MLP神经网络的精度为:%f",accuracy(teengamb$sex,label))
[1] "MLP神经网络的精度为:0.957447"
绘制网络结构图:
par(cex = 0.6)
plotnet(sigmlp,pos_col = "red", neg_col = "grey")
结果如下: