gpt4 book ai didi

r - 在 R 中使用神经网络进行预测

转载 作者:行者123 更新时间:2023-11-30 09:48:36 24 4
gpt4 key购买 nike

我正在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com