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(第二版)》

相关推荐
临床数据科学和人工智能兴趣组3 小时前
提取匹配模式的第一个值
人工智能·r语言·1024程序员节·r语言-4.2.1·临床试验·临床科研·科学问题
在所不辞兄10 小时前
【零基础学智能仿真-61】DFT数值收敛与计算预算
人工智能·深度学习·神经网络·机器学习·1024程序员节
weixin_4684668513 小时前
让机器像视网膜一样“看”:事件相机与脉冲神经网络如何重构视觉感知
人工智能·神经网络·ai·机器视觉·1024程序员节
Yula99331 天前
从“撰写耗时”到“认知卸载”:企业邮件AI的效率边界与工程化路径
人工智能·神经网络·机器学习·数据挖掘·系统安全·信息与通信
哦哦~9211 天前
上海理工大学 Sci. Adv.|自旋解耦超表面赋能 D-D²NN:大容量方向依赖全光衍射神经网络
人工智能·深度学习·神经网络·超表面
临床数据科学和人工智能兴趣组2 天前
在数据分析和处理过程中,字符串的操作常常扮演着极其重要的角色。R语言内置了多种功能强大的字符串处理函数,gsub() 就是其中之一
数据分析·r语言·r语言-4.2.1·临床研究·临床试验·临床科研
tellmewhoisi2 天前
深度学习8:神经网络学习5:随机梯度下降法(基本概念,基本原理)
深度学习·神经网络·学习
Yolanda_20222 天前
神经网络基础原理-使用梯度下降训练二次函数模型简单示例
人工智能·深度学习·神经网络
田里的水稻2 天前
FA_CNN卷积神经网络十二_CIFAR10全流程PyTorch
人工智能·pytorch·深度学习·神经网络·cnn
集芯微电科技有限公司2 天前
集芯微电科技推出5.5V/10A集成功率MOSFET降压DC/DC转换器
人工智能·科技·单片机·嵌入式硬件·神经网络·生成对抗网络