gpt4 book ai didi

r - 如何在R中热编码几个分类变量

转载 作者:行者123 更新时间:2023-12-03 22:48:38 26 4
gpt4 key购买 nike

我正在研究一个预测问题,并且正在R中构建决策树,我有几个分类变量,我想在我的训练和测试集中对它们进行一次热编码。
我设法通过以下方式在训练数据上做到了这一点:

temps <- X_train
tt <- subset(temps, select = -output)
oh <- data.frame(model.matrix(~ . -1, tt), CLASS = temps$output)

但是我找不到在测试集上应用相同编码的方法,我该怎么做?

最佳答案

我建议在插入符号包中使用dummyVars函数:

customers <- data.frame(
id=c(10, 20, 30, 40, 50),
gender=c('male', 'female', 'female', 'male', 'female'),
mood=c('happy', 'sad', 'happy', 'sad','happy'),
outcome=c(1, 1, 0, 0, 0))
customers
id gender mood outcome
1 10 male happy 1
2 20 female sad 1
3 30 female happy 0
4 40 male sad 0
5 50 female happy 0


# dummify the data
dmy <- dummyVars(" ~ .", data = customers)
trsf <- data.frame(predict(dmy, newdata = customers))
trsf
id gender.female gender.male mood.happy mood.sad outcome
1 10 0 1 1 0 1
2 20 1 0 0 1 1
3 30 1 0 1 0 0
4 40 0 1 0 1 0
5 50 1 0 1 0 0

示例 source

您对训练和验证集应用相同的过程。

关于r - 如何在R中热编码几个分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649443/

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