首页 文章

R中神经网络的预测

提问于
浏览
1

我想获得神经网络的预测结果的准确性或 RMSE . 我开始使用混淆矩阵,但如前面的答案所示,混淆矩阵为非连续变量提供有效结果 .

有什么方法可以获得神经网络预测的准确度或错误率吗?

作为一个例子,这是我到目前为止的代码:

library(nnet)
library(caret)
library(e1071)
data(rock)
newformula <- perm ~ area + peri + shape
y <- rock[, "perm"]
x <- rock[!colnames(rock)%in% "perm"]
original <- datacol(rock,"perm")

nnclas_model <- nnet(newformula, data = rock, size = 4, decay = 0.0001, maxit = 500)    
nnclas_prediction <- predict(nnclas_model, x)
nnclas_tab <- table(nnclas_prediction, y)
rmse <- sqrt(mean((original - nnclas_prediction)^2))

有谁知道我怎么能做这个工作?或者我如何获得准确度或神经网络预测?任何帮助将深表感谢 .

2 回答

  • 1

    正如评论中所提到的,混淆矩阵用于分类问题 . 如果您打算根据其级别对 perm 进行分类,那么以下代码应该适合您 .

    library(nnet)
    library(caret)
    library(e1071)
    data(rock)
    rock$perm <- as.factor(rock$perm)
    nnclas_model <- nnet(perm ~ area + peri + shape, data = rock, 
                         size = 4, decay = 0.0001, maxit = 500)
    x <- rock[, 1:3]
    y <- rock[, 4]
    yhat <- predict(nnclas_model, x, type = 'class')
    confusionMatrix(as.factor(yhat), y)
    

    如果你的意思是将 perm 视为连续的,那么混淆矩阵没有任何意义 . 您应该考虑均方误差 .

  • 2

    我不知道"nnet",但我使用了"neuralnet"库并且能够获得RMSE . 这是我的完整代码: Just change the data for training_Data and testing_Data as per your requirements and in place of "Channel" give what is your classification attribute

    dat <- read.csv("Give path of your data file here")
    summary(dat)
    cleandata <- dat
    cleandata <- na.omit(cleandata)
    
    #scaling
    
    apply(cleandata,MARGIN = 2, FUN = function(x)sum(is.na(x)))
    maxs    =   apply(cleandata,    MARGIN  =   2,  max)
    mins    =   apply(cleandata,    MARGIN  =   2,  min)
    scaledData =     as.data.frame(scale(cleandata, center  =   mins,   scale   =   maxs    - mins))
    summary(scaledData)
    
    #Splitting data in 80:20 ratio
    train = sample(1:nrow(scaledData), nrow(scaledData)*0.8)
    test = -train
    training_Data = scaledData[train,]
    testing_Data = scaledData[test,]
    dim(training_Data)
    dim(testing_Data)
    
    #neural net
    
    library(neuralnet)
    n   <- names(training_Data)
    f   <- as.formula(paste("Channel    ~", paste(n[!n  %in%    "Channel"], collapse    =   "   +   ")))
    neuralnet_Model <- neuralnet(f,data = training_Data, hidden = c(2,1))
    plot(neuralnet_Model)
    neuralnet_Model$result.matrix
    pred_neuralnet<-compute(neuralnet_Model,testing_Data[,2:8])
    pred_neuralnet.scaled   <- pred_neuralnet$net.result *(max(scaledData$Channel)-min(scaledData$Channel))+min(scaledData$Channel)
    real.values <- (testing_Data$Channel)*(max(cleandata$Channel)-min(cleandata$Channel))+min(cleandata$Channel)
    MSE.neuralnetModel  <- sum((real.values - pred_neuralnet.scaled)^2)/nrow(testing_Data)
    MSE.neuralnetModel
    plot(real.values, pred_neuralnet.scaled, col='red',main='Real   vs  predicted',pch=18,cex=0.7)
    abline(0,1,lwd=2)
    legend('bottomright',legend='NN',pch=18,col='red',  bty='n')
    

相关问题