R语言实现神经网络(1)

#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)

参考文献:《精通机器学习-基于R(第二版)》

相关推荐
拓端研究室TRL6 小时前
R软件线性模型与lmer混合效应模型对生态学龙类智力测试数据层级结构应用
开发语言·r语言
D.Leo12 小时前
R语言中byrow参数的作用
开发语言·r语言
Wis4e18 小时前
基于PyTorch的深度学习5——如何构建神经网络
pytorch·深度学习·神经网络
Francek Chen20 小时前
【现代深度学习技术】卷积神经网络06:卷积神经网络(LeNet)
人工智能·pytorch·深度学习·神经网络·cnn
浪九天1 天前
人工智能直通车系列14【机器学习基础】(逻辑回归原理逻辑回归模型实现)
人工智能·深度学习·神经网络·机器学习·自然语言处理
天桥下的卖艺者1 天前
R语言使用scitable包交互效应深度挖掘一个陌生数据库
数据库·r语言·交互
闲人编程2 天前
生成对抗网络(GAN)实战
pytorch·神经网络·gan
AAA小肥杨2 天前
2025人工智能AI新突破:PINN内嵌物理神经网络火了
人工智能·深度学习·神经网络·ai·大模型部署
weixin_贾2 天前
R+VIC模型融合实践技术应用及未来气候变化模型预测
r语言·vic模型·未来气候变化
KY_chenzhao2 天前
R+VIC模型融合实践技术应用-防洪规划、水资源管理以及未来气候预测等领域
r语言·vic模型·水文模型·气候变化