這是一個可重複的例子:
set.seed(1)
want <- sample(50, 40)
Iris <- iris[c(51:100, 101:150), ] ## only keep versicolor and virginica
## take our training and test sets
train <- droplevels(Iris[c((1:50)[want], (51:100)[want]), , drop = FALSE])
test <- droplevels(Iris[c((1:50)[-want], (51:100)[-want]), , drop = FALSE])
## fit the PCA
pc <- prcomp(train[, 1:4])
現在注意pc$x
是旋轉的數據。您使用X %*% pc$rotation
(其中X
是訓練數據矩陣),但未首先將數據居中,但它們是等效的。將預測變量集中在迴歸中可能是有用的。
## create data frame for logistic regression
mydata <- data.frame(Species = train[, "Species"], pc$x)
## ...and fit the model
mod <- glm(Species ~ PC1, data = mydata, family = binomial)
預測測試集數據在PC1上的得分;也就是說,使用與用於形成訓練數據的PC相同的旋轉旋轉測試集。爲此,我們可以使用predict()
方法"prcomp"
類
test.p <- predict(pc, newdata = test[, 1:4])
現在用它來預測類
pred <- predict(mod, newdata = data.frame(test.p), type = "response")
pred
> pred
56 66 67 71 72
0.080427399 0.393133104 0.092661480 0.395813527 0.048277608
74 76 82 87 95
0.226191156 0.333553423 0.003860679 0.617977807 0.029469167
106 116 117 121 122
0.999648054 0.922145431 0.924464339 0.989271655 0.318477762
124 126 132 137 145
0.581235903 0.995224501 0.999770995 0.964825109 0.988121496
> 1 - pred
56 66 67 71 72
0.9195726006 0.6068668957 0.9073385196 0.6041864731 0.9517223918
74 76 82 87 95
0.7738088439 0.6664465767 0.9961393215 0.3820221934 0.9705308332
106 116 117 121 122
0.0003519463 0.0778545688 0.0755356606 0.0107283449 0.6815222382
124 126 132 137 145
0.4187640970 0.0047754987 0.0002290047 0.0351748912 0.0118785036
pred
包含測試觀察光圈錦葵的概率。請注意,在glm()
中,當響應是一個因素時(如本例中那樣),則該因子的第一級(此處爲versicolor
)被視爲失敗或0
,第二級和後續級別指示符成功或1
。正如在這個例子中,只有兩個類,模型參數化爲versicolor
; 1 - pred
將給出virginica
的預測概率。
我不會按照您在問題中包含的錯誤計算,因此將由您來解決。可以通過但產生的模式成功的交叉分類表:
> predSpecies <- factor(ifelse(pred >= 0.5, "virginica", "versicolor"))
> table(test$Species, predSpecies)
predSpecies
versicolor virginica
versicolor 9 1
virginica 1 9
表明我們的模型有兩個試驗組觀察錯了。
請閱讀[常見問題](http://stackoverflow.com/faq)和[可重現的示例]上的這個問題(http://stackoverflow.com/questions/5963269/how-to-make-a-great -r重現-例子)。我不知道你要做什麼,你需要更多地描述你想要的東西。我甚至無法運行你的代碼來檢查你到底在做什麼...... –