1.演示使用的数据集为iris数据集
df<-iris
head(df)
2.载入RSNNS包
library(RSNNS)
3.对数据进行预处理,将目标变量Specie转换为one_hot矩阵形式
df<-cbind(df,decodeClassLabels(df$Species))
head(df)
4.对输入的X矩阵数据进行归一化(神经网络 对于数据的输入值的区间有要求的,一般使用标准正太分布归一化)
for(i in 1:4){
df[,i]<-scale(df[,i])}
head(df)
5.使用随机树种子123,对数据按7:3的比例化分为训练集和测试集。
set.seed(123)
sam<-sample(nrow(df),nrow(df)*0.7)
dftrain<-df[sam,]
dftest<-df[-sam,]
6.使用mlp函数建立bp神经网络模型
mobp<-mlp(as.matrix(dftrain[,1:4]),as.matrix(dftrain[,6:8]),size=4,
learnFunc="SCG",learnFuncParams=c(0,0,0,0),hiddenActFunc="Act_TanH")
7.对训练集进行预测
pretrain<-predict(mobp,as.matrix(dftrain[,1:4]))
head(pretrain)
pretrainclass<-colnames(dftrain[,6:8])[apply(pretrain,1,which.max)]
confumatrix<-table(dftrain$Species,pretrainclass)
confumatrix
sum(diag(confumatrix))/sum(confumatrix)
分类正确率为100%
8.对测试集进行预测
pretest<-predict(mobp,as.matrix(dftest[,1:4]))
head(pretest)
pretestclass<-colnames(dftrain[,6:8])[apply(pretest,1,which.max)]
confumatrix<-table(dftest$Species,pretestclass)
confumatrix
sum(diag(confumatrix))/sum(confumatrix)
分类正确率为97.78%。
可以看出,神经网线对于分类类型的任务可以做到很好预测性。
Q:994804370
闲:名曰夷希微
抖:linxy_R_project
感兴趣可以联系哦