首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只缩放训练集和测试集的某些列

只缩放训练集和测试集的某些列
EN

Stack Overflow用户
提问于 2018-02-07 19:03:34
回答 1查看 860关注 0票数 2

我经常要处理以下问题:

  • 我有一个测试集和一个训练集。
  • 我想要缩放训练集的所有列,只有少数几列是由字符向量识别的。
  • 然后,根据训练集中选定的列的样本均值和样本标准差,我也想重新确定测试集。

目前,我的工作流程很混乱:我使用索引向量,然后部分赋值,只缩放一些列的火车集。我在训练集上存储来自缩放操作的均值和标准差,并使用它们来缩放测试集。我想知道是否有一种更简单的方法,而不必安装caret (出于一系列原因,我并不是caret的忠实粉丝,我肯定不会仅仅为了这个问题就开始使用它)。下面是我当前的工作流程:

代码语言:javascript
复制
# define dummy train and test sets
train <- data.frame(letters = LETTERS[1:10], months = month.abb[1:10], numbers = 1:10,
                    x = rnorm(10, 1), y = runif(10))
test <- train
test$x <- rnorm(10, 1)
test$y <- runif(10)

# names of variables I don't want to scale
varnames <- c("letters", "months", "numbers")

# index vector of columns which must not be scaled
index <- names(train) %in% varnames

# scale only the columns not in index
temp <- scale(train[, !index])
train[, !index] <- temp

# get the means and standard deviations from temp, to scale test too
means <- attr(temp, "scaled:center")
standard_deviations <- attr(temp, "scaled:center")

# scale test
test[, !index] <- scale(test[, !index], center = means, scale = standard_deviations)

是否有一种更简单/更惯用的方法来做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2018-02-08 10:25:26

这是一个很好的问题,我尽力想出一个答案。我认为这是一个更优雅的代码:

代码语言:javascript
复制
    train0=train%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale
means <- attr(train0, "scaled:center")
standard_deviations <- attr(train0, "scaled:center")
train0=cbind(select(train,c(letters, months, numbers)),train0)
test0=test%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale(center = means, scale = standard_deviations)
test0=cbind(select(test,c(letters, months, numbers)),test0)

我努力地使用mutate_at,以避免cbind额外的代码,但并不缺少。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48671439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档