【问题标题】:How can I pass one-hot encoded data to a nnet model to perform prediction?如何将 one-hot 编码数据传递给 nnet 模型以执行预测?
【发布时间】: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


【解决方案1】:

假设

数据集中的所有变量 (nndf) 都是分类变量。

步骤

  1. 将除响应变量(即类)之外的所有变量转换为one-hot编码(即0,1格式)

one_hot方法

  one_hot_df <- one_hot(nndf[, -13]) # 13 is the index of `class` variable.

model.matrix方法

  model_mat_df <- model.matrix( ~ . - 1, nndf[, -13])
  1. class 转换为因子并将其添加到上述dfs中。

    class &lt;- as.factor(nndf$class)
    final_df &lt;- cbind(model_mat_df, class)

  2. final_df 拆分为训练和测试并在模型中使用它。

    nnet(class~., train, maxit=150, size=10)

【讨论】:

  • 是否可以将虚拟分类变量和标准化数值变量都传递到 R 中的 nnet 中?这是我总体上要实现的目标,但是,我找不到任何示例。
  • 是的,你可以,因为大多数算法都以相同的格式接受输入,数字作为归一化和分类:一个热门。只需将数字df和分类分开,进行操作并使用cbind/bind_columns组合回来。最后,将合并后的 df 拆分为 test 并将其训练传递给 algo 以构建模型。
猜你喜欢
  • 2019-07-14
  • 2019-10-11
  • 2017-11-06
  • 1970-01-01
  • 2018-03-24
  • 2018-03-29
  • 1970-01-01
  • 2023-03-13
  • 2018-06-05
相关资源
最近更新 更多