是否有与 sklearn.preprocessing 的 OneHotEncoder 相当的 R 语言?
我想在我的火车数据上安装一个 OHE,对其进行转换,然后通过相同的转换来转换我的测试数据。
例如在python中:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame(['a','a','b','c','d'])
test = pd.DataFrame(['a','a'])
ohe = OneHotEncoder(drop='first')
train_dummies = ohe.fit_transform(train)
test_dummies = ohe.transform(test)
我能在 R 中找到的最接近的等价物是插入符号的 dummyVars(),但以下代码片段失败:
library(caret)
train = data.frame(a=c('a','a','b','c','d'))
dummies = dummyVars(~ ., data = train)
train_dummies = predict(dummies, newdata = train)
test = data.frame(a=c('a','a'))
test_dummies = predict(dummies, newdata = test)
与
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
发生此故障是因为 test 中的 a 只有一个级别,尽管 train 中的 a 上安装了 4 个级别的假人。 R 中是否有更好的等价物,或者如果有必要,可以做一些软糖来使它起作用?还有什么方法可以按照 python 复制“降低第一级”?
R 中有
fastDummies
用于单热编码。
library(fastDummies)
train = data.frame(col=c('a','a','b','c','d'))
dummy_cols(train,
remove_first_dummy = T,
remove_selected_columns = T)
输出
col_b col_c col_d
1 0 0 0
2 0 0 0
3 1 0 0
4 0 1 0
5 0 0 1
创建于 2023-04-14 与 reprex v2.0.2
我猜你需要在使用之前将变量转换为因子
dummyVars
# Create train and test data frames
train <- data.frame(a = c('a', 'a', 'b', 'c', 'd'))
test <- data.frame(a = c('a', 'a'))
# Convert input variables to factors
train$a <- as.factor(train$a)
test$a <- as.factor(test$a)
# Perform one-hot encoding using caret
dummies <- caret::dummyVars("~.", data = train)
train_dummies <- predict(dummies, newdata = train)
test_dummies <- predict(dummies, newdata = test)
> dummies
Dummy Variable Object
Formula: ~.
<environment: 0x7f9dd8053160>
1 variables, 1 factors
Variables and levels will be separated by '.'
A less than full rank encoding is used
> test_dummies
a.a a.b a.c a.d
1 1 0 0 0
2 1 0 0 0