【发布时间】:2023-03-09 02:57:02
【问题描述】:
我是数据科学的新手,想在 R 中构建一个神经网络模型。我在训练之前阅读了有关 one-hot encoding 分类数据的信息。我尝试实现这一点,但是,在尝试训练模型时收到以下错误:
Error in model.frame.default(formula = nndf$class ~ ., data = train) :
invalid type (list) for variable 'nndf$class'
我已经阅读了 nnet 文档,其中解释了公式应该传递为:
class ~ x1 + x2
但我仍然不确定如何正确传递数据。
代码如下:
nndf$al <- one_hot(as.data.table(nndf$al))
nndf$su <- one_hot(as.data.table(nndf$su))
nndf$rbc <- one_hot(as.data.table(nndf$rbc))
nndf$pc <- one_hot(as.data.table(nndf$pc))
nndf$pcc <- one_hot(as.data.table(nndf$pcc))
nndf$ba <- one_hot(as.data.table(nndf$ba))
nndf$htn <- one_hot(as.data.table(nndf$htn))
nndf$dm <- one_hot(as.data.table(nndf$dm))
nndf$cad <- one_hot(as.data.table(nndf$cad))
nndf$appet <- one_hot(as.data.table(nndf$appet))
nndf$pe <- one_hot(as.data.table(nndf$pe))
nndf$ane <- one_hot(as.data.table(nndf$ane))
nndf$class <- one_hot(as.data.table(nndf$class))
class(nndf$class)
# view the dataframe to ensure one hot encoding is correct
summary(nndf)
# randomly sample rows for tt split
train_idx <- sample(1:nrow(nndf), 0.8 * nrow(nndf))
test_idx <- setdiff(1:nrow(nndf), train_idx)
# prepare training set and corresponding labels
train <- nndf[train_idx,]
# prepare testing set and corresponding labels
X_test <- nndf[test_idx,]
y_test <- nndf[test_idx, "class"]
# create model with a single hidden layer containing 500 neurons
model <- nnet(nndf$class~., train, maxit=150, size=10)
# prediction
X_pred <- predict(train, type="raw")
【问题讨论】:
-
我不确定你的函数
one_hot做了什么,但model.matrix以这种方式处理因素model.matrix(~ factor(gear) + 0, mtcars) -
我应该提到,我正在使用库 mltools 中的 one_hot 函数
-
@mrrain 在强制使用之前不需要使用
one_hot,正如@rawr 建议的那样,您应该使用model.matrix( ~ . - 1, df)将所有分类变量一次转换为one_hot 编码。 注意:df必须只包含分类变量。
标签: r machine-learning one-hot-encoding nnet