首页 > 解决方案 > 神经网络输出不一致

问题描述

我正在使用 R 中的 NeuralNet 包来训练人工神经网络,并且能够毫无问题地训练模型。但是,当我使用相同数量的隐藏节点重新运行模型,然后根据我的测试数据评估我的结果时,我会得到截然不同的结果。我正在阅读论坛帖子,有人建议它与随机起始权重有关,并建议设置种子。我一直非常坚持我的种子,但我仍然得到非常不同的结果。有没有人遇到过类似的问题?如果是这样,你做了什么来解决不一致的问题。此外,我所有的 IV 都是数字的,我没有缺失值。

这是我的代码和输出:

#min-max norm the dt vars
normalize = function(x){
  return((x-min(x))/(max(x) - min(x)))
}

#make a smaller dt so it is easier to work with
nrows = nrow(dt.norm)
sm.size = 10000
set.seed(7)
sm.index = sample(nrows, sm.size, replace = FALSE)
dt.norm.sm = dt.norm[sm.index,]

#Split into training and testing
nrows = nrow(dt.norm.sm) 
train.size = floor(0.7*nrows)
set.seed(7)
train.idx = sample(nrows, train.size, replace = F)
dt.sm.train = dt.norm.sm[train.idx, ]
dt.sm.test = dt.norm.sm[-train.idx, ]

#train model on the data
ann.form = as.formula(paste('Pure_Prem ~', paste(names(dt.sm.train[-24]), 
collapse = '+'))) #24 is the dv
pure_prem_model = neuralnet(ann.form, data = dt.sm.train, hidden = 3)

#evaluate model performance
model_results = neuralnet::compute(pure_prem_model, dt.sm.test[1:23]) 
#exclude 24 because it is the DV
predicted_pure_prem = model_results$net.result
cor(predicted_pure_prem, dt.sm.test$Pure_Prem)

我的输出是:

[1,] 0.007210471996

当我再次重新运行完全相同的代码时,我的输出是:

[1,] 0.4554126927

先感谢您。

标签: rneural-network

解决方案


这是我评论中的一个例子。

设置数据:

data <- mtcars
samplesize <-  0.6 * nrow(data)
set.seed(7)
index <-  sample(seq_len(nrow(data)), size = samplesize)
max <-  apply(data , 2 , max)
min <-  apply(data, 2 , min)
scale_df <-  as.data.frame(scale(data, center = min, scale = max - min))
train <-  scale_df[index , ]
test <-  scale_df[-index , ]

设置神经网络

set.seed(6)
model_nn <- neuralnet::neuralnet(mpg ~ cyl + hp + wt, train, hidden = 3)
model_result <- neuralnet::compute(model_nn, test[,c(2,4,6)])
predicted_mpg <- model_result$net.result
cor(predicted_mpg, test$mpg)

输出将永远是

[1,] 0.9310625412

如果省略set.seed(6)before neuralnet::neuralnet(),则 5 次迭代的输出为:

[1,] 0.9142345019
[1,] 0.8531440993
[1,] 0.9414393857
[1,] 0.9309926802
[1,] 0.9164132325

只需添加额外的set.seed. 希望对您有所帮助。


推荐阅读