我有下面的代码,其中形成了一个简单的基于规则的分类数据集:
# # Data preparation
data = data.frame(A = round(runif(100)), B = round(runif(100)), C = round(runif(100)))
# Y - is the classification output column
data$Y = ifelse((data$A == 1 & data$B == 1 & data$C == 0), 1, ifelse((data$A == 0 & data$B == 1 & data$C == 1), 1, ifelse((data$A == 0 & data$B ==0 & data$C == 0), 1, 0)))
# Shuffling the data set
data = data[sample(rownames(data)), ]
我已将数据集划分为训练和测试,以便我可以在测试集上验证我的结果:
# # Divide into train and test
library(caret)
trainIndex = createDataPartition(data[, "Y"], p = .7, list = FALSE, times = 1) # for balanced sampling
train = data[trainIndex, ]
test = data[-trainIndex, ]
我尝试构建一个简单的神经网络,通过循环选择隐藏层中的神经元数量(如上所述here)
# # Build a neural net
library(neuralnet)
for(alpha in 2:10)
{
nHidden = round(nrow(train)/(alpha*(3+1)))
nn = neuralnet(Y ~ A + B + C, train, linear.output = F, likelihood = T, err.fct = "ce", hidden = nHidden)
# Calculate Mean Squared Error for Train and Test
trainMSE = mean((round(nn$net.result[[1]]) - train$Y)^2)
testPred = round(compute(nn,test[-length(ncol(test))])$net.result)
testMSE = mean((testPred - test$Y)^2)
print(paste("Train Error: " , round(trainMSE, 4), ", Test Error: ", round(testMSE, 4), ", #. Hidden = ", nHidden, sep = ""))
}
[1]“训练错误:0,测试错误:0.6,#。隐藏= 9”
[1]“训练错误:0,测试错误:0.6,#。隐藏= 6”
[1]“训练错误:0,测试错误:0.6,#。隐藏= 4”
[1]“训练错误:0,测试错误:0.6,#。隐藏= 4”
[1]“训练错误:0.1429,测试错误:0.8333,#。隐藏= 3”
[1]“训练错误:0.1429,测试错误:0.8333,#。隐藏= 2”
[1]“训练错误:0.0857,测试错误:0.6,#。隐藏= 2”
[1]“训练错误:0.1429,测试错误:0.8333,#。隐藏= 2”
[1]“训练错误:0.0857,测试错误:0.6,#。隐藏= 2”
这给了穷人超过合适的结果。但是,当我在同一数据集上构建一个简单的随机森林时。我得到的火车和测试错误为 - 0
# # Build a Random Forest
trainRF = train
trainRF$Y = as.factor(trainRF$Y)
testRF = test
library(randomForest)
rf = randomForest(Y ~ ., data = trainRF, mtry = 2)
# Calculate Mean Squared Error for Train and Test
trainMSE = mean((round(rf$votes[,2]) - as.numeric(as.character(trainRF$Y)))^2)
testMSE = mean((round(predict(rf, testRF, type = "prob")[,2]) - as.numeric(as.character(testRF$Y)))^2)
print(paste("Train Error: " , round(trainMSE, 4), ", Test Error: ", round(testMSE, 4), sep = ""))
[1]“训练错误:0,测试错误:0”
请帮助我理解为什么神经网络会在一个简单的情况下失败,其中随机森林的准确率达到100%。
注意:我只使用了一个隐藏层(假设一个隐藏层足以进行这种简单的分类)并迭代隐藏层中的神经元数量。
另外,如果我对神经网络参数的理解是错误的,请帮帮我。
可以找到完整的代码here
答案 0 :(得分:1)
类似的问题一直困扰着我,所以我尝试了解你的数据和问题并将它们与我的相比较。但最后,它只是这一行中的一个小错误:
testPred = round(compute(nn,test[-length(ncol(test))])$net.result)
您选择B
,C
和Y
进行预测,而不是A
,B
和C
,因为{{1}将始终返回1.您只需要length(ncol(something))
。
test[-ncol(test)]