作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 R 中使用“neuralnet”包来训练“wine”数据集的模型。下面是我到目前为止想出的代码-
library(neuralnet)
library(rattle)
library(rattle.data)
# load 'wine' dataset-
data(wine)
D <- as.data.frame(wine, stringsAsFactors=FALSE)
# replace 'Type' response variable (with values- 1, 2, 3) by 3 dummy variables-
D$wine1 <- 0
D$wine1[D$Type == 1] <- 1
D$wine2 <- 0
D$wine2[D$Type == 2] <- 1
D$wine3 <- 0
D$wine3[D$Type == 3] <- 1
# create formula to be used-
wine_formula <- as.formula(wine1 + wine2 + wine3 ~ Alcohol + Malic + Ash + Alcalinity + Magnesium + Phenols + Flavanoids + Nonflavanoids + Proanthocyanins + Color + Hue + Dilution + Proline)
# split dataset into training and testing datasets-
train_indices <- sample(1:nrow(wine), floor(0.7 * nrow(wine)), replace = F)
training <- D[train_indices, ]
testing <- D[-train_indices, ]
# train neural network model-
wine_nn <- neuralnet(wine_formula, data = training, hidden = c(5, 3), linear.output = FALSE, stepmax = 1e+07)
# make predictions using 'compute()'-
preds <- compute(wine_nn, testing[, 2:14])
# create a final data frame 'results' containing predicted & actual values-
results <- as.data.frame(preds$net.result)
results <- cbind(results, testing$wine1, testing$wine2, testing$wine3)
# rename the data frame-
names(results) <- c("Pred_Wine1", "Pred_Wine2", "Pred_Wine3", "Actual_Wine1", "Actual_Wine2", "Actual_Wine3")
我现在的任务是将属性“Pred_Wine1”、“Pred_Wine2”和“Pred_Wine3”中的值转换为 1 和 0,以便我可以创建混淆矩阵并测试模型准确性。
我应该如何处理,因为“Pred_Wine1”、“Pred_Wine2”、“Pred_Wine3”包含介于 0 和 1 之间的计算值。
有什么建议吗?
谢谢!
最佳答案
我认为你需要在这里进行标签编码。
假设您的数据框名为df
。这会将特征中的值转换为数字。因此,如果 Pred_Wine1
包含 a,b,它会将其转换为 0,1,反之亦然。
试试这个:
features <- c("Pred_Wine1", "Pred_Wine2","Pred_Wine3")
for(f in features)
{
levels <- unique(df[[f]])
df[[i]] <- as.integer(factor(df[[i]], levels=levels))
}
关于r - 在 R 中使用神经网络进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49075653/
我是一名优秀的程序员,十分优秀!