我在尝试绘制神经网络时收到了错误消息。起初代码运行正常,后来就停止了。运行neuralnet()函数时没有出现错误消息。任何帮助都将不胜感激。我在预测贷款违约。
library(neuralnet)library(plyr)CreditCardnn <- read.csv("https://raw.githubusercontent.com/621-Group2/Final-Project/master/UCI_Credit_Card.csv")#标准化数据集maxValue <- apply(CreditCardnn, 2, max)minValue <- apply(CreditCardnn, 2, min)CreditCardnn <- as.data.frame(scale(CreditCardnn, center = minValue, scale = maxValue - minValue))#重命名目标变量colnames(CreditCardnn)[25] <- "target"smp <- floor(0.70 * nrow(CreditCardnn))set.seed(4784)CreditCardnn$ID <- NULLtrain_index <- sample(seq_len(nrow(CreditCardnn)), size = smp, replace = FALSE)train_nn <- CreditCardnn[train_index, ]test_nn <- CreditCardnn[-train_index, ]allVars <- colnames(CreditCardnn)predictorVars <- allVars[!allVars%in%'target']predictorVars <- paste(predictorVars, collapse = "+")f <- as.formula(paste("target~", predictorVars, collapse = "+"))nueralModel <- neuralnet(formula = f, hidden = c(4,2), linear.output = T, data = train_nn)plot(nueralModel)
这导致了以下错误:
Error in plot.nn(nueralModel) : weights were not calculated
回答:
在你报告的错误之前,你很可能还收到了一个警告:
# 你的数据准备代码在这里> nueralModel <- neuralnet(formula = f, hidden = c(4,2), linear.output = T, data = train_nn)Warning message:algorithm did not converge in 1 of 1 repetition(s) within the stepmax
这条消息很重要,实际上是在警告你你的神经网络没有收敛。鉴于这条消息,当你尝试绘制网络时,后续出现的错误其实是可以预见的:
> plot(nueralModel)Error in plot.nn(nueralModel) : weights were not calculated
更仔细地查看你的代码和数据,问题出在你选择了linear.output = T
来拟合你的神经网络;根据文档:
linear.output 逻辑值。如果不应对输出神经元应用激活函数,请将linear output设置为TRUE,否则设置为FALSE。
在神经网络的最后一层保持线性输出通常只用于回归设置;在分类设置中,如你所使用的,正确的选择是对输出神经元也应用激活函数。因此,尝试使用与你相同的代码,但将linear.output = F
,我们得到:
> nueralModel <- neuralnet(formula = f, hidden = c(4,2), linear.output = F, data = train_nn) # 这次没有警告> plot(nueralModel)
这是plot
的结果: