我正在尝试使用 PCA 来选择一些 K 主要组件来使用。
我知道不应在测试集上重新运行 PCA,而应使用在对训练集建模时找到的特征向量 \ PC。
我有 2 个 CSV - 一个是训练集,
另一个测试集(每条记录没有标签)
训练集上的 PCA 过程使用以下代码完成:
# Load CSV file
train_set.init_data <- read.csv("D:\\train.csv", header = TRUE)
# Remove identifier and respone variables (ID, and SalePrice):
train_set.vars <- subset(train_set.init_data, select = -c(Id, SalePrice))
# Convert catergorical variables into numerical using dummy variables:
library(dummies)
train_set.vars_dummy <- dummy.data.frame(train_set.vars, sep = ".")
# Principal Component Analysis:
train_set.prin_comp <- prcomp(train_set.vars_dummy, scale. = T)
# Choose some K components
????
# Run linear regression model based on PC's
<.....>
Run Code Online (Sandbox Code Playgroud)
使用训练集完成模型构建后,我需要加载测试集并在其上运行我的预测模型。
我在“如何编码?”方面遇到的困难:
运行PCA(在训练集上)后如何提取K(将根据碎石图选择)PC,因此训练集的建模将基于这些?(规划线性回归)
当想要运行建立在实际测试集上的模型时,如何使用 K 个提取的 PC?
我应该先将测试集中的特征归零还是缩放它们的 STD?对于训练集,我知道prcompmethod 已经为我做到了,所以我不确定是否应该在测试集上手动完成。
我是否应该使用虚拟变量将测试集的分类变量转换为数值,就像我对训练集所做的那样?
我确实了解基本的 - 应用于训练集的相同操作也应该应用于测试集。
但是 - 我不确定这在代码方面究竟意味着什么。
谢谢
我正在使用USArrests数据集让您了解对测试数据执行 PCA 所要遵循的步骤顺序。
library(dplyr)
library(tibble)
data(USArrests)
train <- USArrests %>% rownames_to_column(var = "rowname")
test <- USArrests %>% rownames_to_column(var = "rowname")
Run Code Online (Sandbox Code Playgroud)
方法 1 - 组合训练和测试
# Join train and test set
df <- bind_rows("train" = train, "test" = test, .id="group")
# Run Principal Components Analysis
pc <- prcomp(df %>% select(-rowname, -group), scale = TRUE)
# Plot ScreePlot
pc_var <- (pc$sdev^2)/sum(pc$sdev^2)
plot(pc_var, xlab = "Principal Component", ylab = "Proportion of Variance Explained", type = "b")
# Extract PCs (e.g. 1st 3 PCs)
df <- augment(pc,df) %>% select(group, rowname, .fittedPC1 : .fittedPC3)
# Split into train and test
train <- df %>% filter(group == "train") %>% select(-group)
test <- df %>% filter(group == "test") %>% select(-group)
Run Code Online (Sandbox Code Playgroud)
在这种方法中,测试数据可能会泄漏到列车数据中。
方法 2 -predict()用于从训练数据的 PCA 加载转换测试数据
# Run Principal Components Analysis
pc <- prcomp(train %>% select(-rowname), scale = TRUE)
# Extract PCs (e.g. 1st 3 PCs)
train <- tbl_df(pc1$x) %>% select(PC1:PC3)
test <- tbl_df(predict(pc, newdata = test %>% select(-rowname))) %>% select(PC1:PC3)
Run Code Online (Sandbox Code Playgroud)
与之前的方法相比,这种方法更加稳健。