xec*_*eco 10 r one-hot-encoding
我正在研究一个预测问题,我在R中构建一个决策树,我有几个分类变量,我想在我的训练和测试集中对它们进行一次性热编码.我设法用我的训练数据做到:
temps <- X_train
tt <- subset(temps, select = -output)
oh <- data.frame(model.matrix(~ . -1, tt), CLASS = temps$output)
Run Code Online (Sandbox Code Playgroud)
但我找不到在我的测试集上应用相同编码的方法,我该怎么做?
Est*_* PS 26
我建议在插入符包中使用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
Run Code Online (Sandbox Code Playgroud)
示例来源
您将相同的过程应用于训练集和验证集.
D A*_*lls 22
这是一个简单的解决方案,可以不使用包对您的类别进行单热编码。
model.matrix(~0+category)
它需要您的分类变量作为一个因素。训练和测试数据中的因子水平必须相同,请使用levels(train$category)和 进行检查levels(test$category)。测试集中是否出现某些级别并不重要。
这是一个使用 iris 数据集的示例。
data(iris)
#Split into train and test sets.
train <- sample(1:nrow(iris),100)
test <- -1*train
iris[test,]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
34 5.5 4.2 1.4 0.2 setosa
106 7.6 3.0 6.6 2.1 virginica
112 6.4 2.7 5.3 1.9 virginica
127 6.2 2.8 4.8 1.8 virginica
132 7.9 3.8 6.4 2.0 virginica
Run Code Online (Sandbox Code Playgroud)
model.matrix()为因子的每个水平创建一列,即使它不存在于数据中。零表示不是那个级别,一表示是。添加零表示您不需要截距或参考电平,相当于 -1。
oh_train <- model.matrix(~0+iris[train,'Species'])
oh_test <- model.matrix(~0+iris[test,'Species'])
#Renaming the columns to be more concise.
attr(oh_test, "dimnames")[[2]] <- levels(iris$Species)
setosa versicolor virginica
1 1 0 0
2 0 0 1
3 0 0 1
4 0 0 1
5 0 0 1
Run Code Online (Sandbox Code Playgroud)
PS 通常最好在训练和测试数据中包含所有类别。但这不关我的事。
Rom*_*man 13
library(data.table)
library(mltools)
customers_1h <- one_hot(as.data.table(customers))
Run Code Online (Sandbox Code Playgroud)
> customers_1h
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
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)