#R语言实现神经网络
library(neuralnet)
library(caret)
library(MASS)
library(vcd)
data(shuttle)
str(shuttle)#因变量use;
table1<-structable(wind+magn~use,shuttle)
mosaic(table1,shading=T)
mosaic(use~error+vis,shuttle)
prop.table(table(shuttle$use,shuttle$stability))#用来计算两个变量 shuttle$use 和 shuttle$stability 之间频率表的函数
#数据准备
#虚拟变量
dummies<-dummyVars(use~.,shuttle,fullRank=T)
#虚拟变量预测现有数据
shuttle.2=as.data.frame(predict(dummies,newdata=shuttle))
names(shuttle.2)
shuttle.2$use<-ifelse(shuttle$use=="auto",1,0)
#拆分测试集和训练集
set.seed(123)
trainIndex<-createDataPartition(shuttle.2$use,p=0.7,list=F)
shuttleTrain<-shuttle.2[trainIndex,]
shuttleTest<-shuttle.2[-trainIndex,]
#模型构建
n<-names(shuttleTrain)
form<-as.formula(paste("use~",paste(n[!n %in% "use"],collapse = "+")))
fit<-neuralnet(form,data=shuttleTrain,
hidden = c(3, 3),#第一个隐藏层有3个神经元,第二个隐藏层有3个神经元
err.fct = "ce",#默认sse,因为此处是二值结果,所以选择ce
linear.output = F,#是否忽略act.fct
likelihood=TRUE)
fit$result.matrix
plot(fit)
par(mfrow=c(1,2))
gwplot(fit,selected.covariate="magn.Out")
gwplot(fit,selected.covariate="wind.tail")
#预测
resultsTrain<-compute(fit,shuttleTrain[,1:10])
predTrain<-resultsTrain$net.result
predTrain<-ifelse(predTrain>=0.5,1,0)
table(predTrain,shuttleTrain$use)
#在测试集上的结果
resultsTest <- compute(fit, shuttleTest[,1:10])
predTest <- resultsTest$net.result
predTest <- ifelse(predTest >= 0.5, 1, 0)
table(predTest, shuttleTest$use)
which(predTest == 0 & shuttleTest$use ==1)
文章来源:https://www.toymoban.com/news/detail-662130.html
参考文献:《精通机器学习-基于R(第二版)》文章来源地址https://www.toymoban.com/news/detail-662130.html
到了这里,关于R语言实现神经网络(1)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!