如何使用神经网络包(neuralnet package)预测新病例

12
使用RGUI。我有一个名为Data的数据集。我感兴趣的响应变量包含在Data的第一列中。
我有名为DataTrain和DataTest的Data训练集。
使用DataTrain,我使用neuralnet软件包和函数训练了一个神经网络模型(称为DataNN)。
> DataNN = neuralnet(DataTrain[,1] ~ DataTrain[,2] + DataTrain[,3], hidden = 1,
    data = DataTrain) 

请问有谁知道如何使用测试集(DataTest)在这个模型上进行预测吗?

通常情况下(对于其他模型),我会使用predict()来进行预测。例如:

> DataPred = predict(DataNN, DataTest)

但是,当我在使用neuralnet时,我得到了以下结果:

> DataPred = predict(DataNN, DataTest)

Error in UseMethod("predict") : 
no applicable method for 'predict' applied to an object of class "nn"  

显然我不能在这个模型上运行 predict()。 有人知道任何替代方法吗?
我查看了 neuralnet 的帮助文档,并在documentation的第12页中找到了一个名为 prediction 的方法。 我不认为它是我想要的,或者至少我不知道如何将其应用于我的 Data 。
如果有任何解决方案,任何帮助都将不胜感激。
4个回答

22

compute方法可以实现你想要的功能,我从帮助文件中复制了这个例子,并添加了一些注释:

 # Make Some Training Data
 Var1 <- runif(50, 0, 100) 
 # create a vector of 50 random values, min 0, max 100, uniformly distributed
 sqrt.data <- data.frame(Var1, Sqrt=sqrt(Var1)) 
 # create a dataframe with two columns, with Var1 as the first column
 # and square root of Var1 as the second column

 # Train the neural net
 print(net.sqrt <- neuralnet(Sqrt~Var1,  sqrt.data, hidden=10, threshold=0.01))
 # train a neural net, try and predict the Sqrt values based on Var1 values
 # 10 hidden nodes

 # Compute or predict for test data, (1:10)^2
 compute(net.sqrt, as.data.frame((1:10)^2))$net.result
 # What the above is doing is using the neural net trained (net.sqrt), 
 # if we have a vector of 1^2, 2^2, 3^2 ... 10 ^2 (i.e. 1, 4, 9, 16, 25 ... 100), 
 # what would net.sqrt produce?

 Output:
 $net.result
             [,1]
 [1,] 1.110635110
 [2,] 1.979895765
 [3,] 3.013604598
 [4,] 3.987401275
 [5,] 5.004621316
 [6,] 5.999245742
 [7,] 6.989198741
 [8,] 8.007833571
 [9,] 9.016971015
[10,] 9.944642147
# The first row corresponds to the square root of 1, second row is square root
# of 2 and so on. . . So from that you can see that net.sqrt is actually 
# pretty close
# Note: Your results may vary since the values of Var1 is generated randomly.

6
当我使用compute时,遇到了这个错误:no applicable method for 'compute' applied to an object of class "nn." 这是与dplyr中的compute方法冲突造成的。我通过这样调用来解决:neuralnet::compute()。 - Erin Shellman
抱歉,在神经网络中,我如何选择更好的预测变量? - Angel
1
这段代码出现了错误:Error in if (ncol(newdata) == length(object$model.list$variables)) { : argument is of length zero - baxx
@baxx:在1:10...周围需要加上as.data.frame(...) - Christopher Oezbek

2
答案是 compute(nn, test)。

2

预测功能的名称是prediction,而不是predict

因此,请尝试使用DataPred = prediction(DataNN, DataTest)代替DataPred = predict(DataNN, DataTest)


1

您应该使用neuralnet的预测版本,即:

DataPred <- compute(DataNN, DataTest)

如果您使用dplyr进行任何操作,则需要明确声明库,然后像这样声明函数名称。
DataPred <- neuralnet::compute(DataNN, DataTest)

顺便说一下,在为变量赋值时永远不要使用等号,不幸的是这是一个不好的习惯。


你能解释一下为什么等号是不好的编程实践吗? - baxx
我使用的惯例符合Google的R风格指南。但主要原因是<-惯例实际上评估右侧的代码,并将右侧代码的结果分配给左侧的变量(在这种情况下,compute(DataNN,DataTest)的结果被分配给变量DataPred)。等号通常在函数内部使用。实际上,“=”和“<-”之间没有太大的区别,但在R中概念上略有不同。 - Naufal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接