计算R中PCA的变换?

时间:2016-03-31 11:07:55

标签: r classification random-forest pca

我正在寻找代表从数据集到其PC的映射的权重。目的是建立一个“校准的”固定空间,例如三种葡萄酒和新的观察结果,例如引入了一种新的葡萄酒,它可以在之前校准的空间内分配而不会改变固定的PC值。因此,通过执行应用于前三种排序的转换,可以适当地分配新的观察结果。

 library(ggbiplot)
 data(wine)
 wine.pca <- prcomp(wine, center = TRUE, scale. = TRUE)
 print(ggbiplot(wine.pca, obs.scale = 1, var.scale = 1, groups =   wine.class, ellipse = TRUE, circle = TRUE))

编辑:将葡萄酒数据集拆分为训练数据,以获得我称之为校准空间的数据。

samp <- sample(nrow(wine), nrow(wine)*0.75)
wine.train <- wine[samp,]

然后使用训练数据对要验证的数据集进行子集,例如

wine.valid <- wine[-samp,]

#PCA on training data
wine.train.pca <- prcomp(wine.train, center = TRUE, scale. = TRUE)
#use the transformation matrix from the training data to predict the validation data
pred <- predict(wine.train.pca, newdata = wine.valid)

随后,在thread中解决了如何表示由训练和变换的验证/测试数据产生的校准空间。

1 个答案:

答案 0 :(得分:1)

使用predict的{​​{1}}功能很容易做到这一点。下面我将您的葡萄酒数据分成两部分来展示性能;培训和验证数据集。然后使用训练集上的prcomp-fit PCA对验证PCA坐标的预测与从完整数据集导出的相同坐标进行比较:

prcomp

enter image description here

您还可以查看预测坐标和原始坐标之间的相关性,并发现它们对于领先的PC来说非常高:

library(ggbiplot)
data(wine)

# pca on whole dataset
wine.pca <- prcomp(wine, center = TRUE, scale. = TRUE)

# pca on training part of dataset, then project new data onto pca coordinates 
set.seed(1)
samp <- sample(nrow(wine), nrow(wine)*0.75)
wine.train <- wine[samp,]
wine.valid <- wine[-samp,]
wine.train.pca <- prcomp(wine.train, center = TRUE, scale. = TRUE)
pred <- predict(wine.train.pca, newdata = wine.valid)

# plot original vs predicted pca coordinates
matplot(wine.pca$x[-samp,,1:4], pred[,1:4])

编辑:

以下是使用# correlation of predicted coordinates abs(diag(cor(wine.pca$x[-samp,], pred[,]))) # PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 # 0.9991291 0.9955028 0.9882540 0.9418268 0.9681989 0.9770390 0.9603593 0.8991734 0.8090762 0.9326917 # PC11 PC12 PC13 # 0.9270951 0.9596963 0.9397388 进行分类的示例:

randomForest

每个变量的重要性可以通过以下方式返回:

library(ggbiplot)
data(wine)
wine$class <- wine.class

# install.packages("randomForest")
library(randomForest)

set.seed(1)
train <- sample(nrow(wine), nrow(wine)*0.5)
valid <- seq(nrow(wine))[-train]
winetrain <- wine[train,]
winevalid <- wine[valid,]

modfit <- randomForest(class~., data=winetrain, nTree=500)
pred <- predict(modfit, newdata=winevalid, type='class')

并且,预测准确性返回如下:

importance(modfit) # importance of variables in predition
#                MeanDecreaseGini
# Alcohol               8.5032770
# MalicAcid             1.3122286
# Ash                   0.6827924
# AlcAsh                1.9517369
# Mg                    1.3632713
# Phenols               2.7943536
# Flav                  6.5798205
# NonFlavPhenols        1.1712744
# Proa                  1.2412928
# Color                 8.7097870
# Hue                   5.2674082
# OD                    6.6101764
# Proline              10.7032775