神经网络与R语言

'''
神经网络需要的安装包是neuralnet包,RSNNS包
在iris数据集里面随机抽取训练集和测试集
'''
data("iris")
head(iris)
library(neuralnet)
ind <- sample(2,nrow(iris),replace = T,prob = c(0.7,0.3))
trainset <- iris[ind == 1,]
testset <- iris[ind == 2,]
table(iris$Species)
trainset$setosa = trainset$Species =="setosa"
trainset$versicolor = trainset$Species =="versicolor"
trainset$virginica = trainset$Species =="virginica"
#调用neural函数创建一个包含设个隐藏层的神经网络
set.seed(12345)
network <- neuralnet(setosa + versicolor + virginica~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
          hidden = 3,trainset)
network$result.matrix#神经网络模型的结果矩阵
head(network$generalized.weights[[1]])
summary(network)
plot(network)#可以画出来神经网络的图可以显示误差率,和迭代步数
#计算模型的性能,要注意testset里面含有类别,应当去掉
result_testset <- compute(network,testset[1:4,])
result_testset$neurons
predict <- result_testset$net.result#相关的预测概率矩阵
#然后找到概率矩阵最大的那一列
apply(predict,1,which.max)#返回每一行中最大的那一列,比如149行最大的那个数在第三列,则第149行就属于第三类,然后再给第三类取名字
#
prediction <- c("virginica","versicolor","setosa")[apply(predict,1,which.max)]#"virginica","versicolor","setosa,注意着三个数的排列
#是根据plot函数从下往上排列的
predict.table = table(prediction,testset$Species)
#计算分类表
classAgreement(predict.table)#在研究一下
confusionMatrix(predict.table)#在研究一下


#利用nnet包处理人工神经网络
library(nnet)
network <- nnet(Species~.,trainset,size= 2,rang = 0.1,decay = 5e-4,maxit =200)#size代表隐藏层的个数,maxit表示迭代次数
#这个函数是不用这个命令的plot(network)

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值