我为无监督的情况创建了随机森林。
g = randomForest(iris[,-5],keep.forest=TRUE)
现在我需要知道每个条目的类概率(关于 iris$Species)。如果是受监督的情况,那么我将使用以下代码:
p = predict(g, iris, type = "prob")
但是,对于无人监督的情况,它说:
无法预测无监督森林。
那么,我怎样才能提取类概率呢?
我为无监督的情况创建了随机森林。
g = randomForest(iris[,-5],keep.forest=TRUE)
现在我需要知道每个条目的类概率(关于 iris$Species)。如果是受监督的情况,那么我将使用以下代码:
p = predict(g, iris, type = "prob")
但是,对于无人监督的情况,它说:
无法预测无监督森林。
那么,我怎样才能提取类概率呢?
在无监督的情况下,randomForest 生成一个可用于聚类的邻近矩阵。
library(randomForest)
g <- randomForest(iris[,-5], keep.forest=FALSE, proximity=TRUE)
mds <- MDSplot(g, iris$Species, k=2, pch=16, palette=c("skyblue", "orange", "darkblue"))
library(cluster)
clusters_pam <- pam(1-g$proximity, k=3, diss = TRUE)
plot(mds$points[, 1], mds$points[, 2], pch=clusters_pam$clustering+14, col=c("skyblue", "orange", "darkblue")[as.numeric(iris$Species)])
legend("bottomleft", legend=unique(clusters_pam$clustering), pch = 15:17, title = "PAM cluster")
legend("topleft", legend=unique(iris$Species), pch = 16, col=c("skyblue", "orange", "darkblue"), title = "Iris species")
MDS 代表多维缩放。
当然,集群不会一对一地映射到原始类(这就是为什么我故意不重新映射集群 - 所以它不是混淆矩阵:
table(clusters_pam$clustering, iris$Species)
setosa versicolor virginica
1 50 0 0
2 0 9 42
3 0 41 8
然后,您可以将集群用作类来训练监督模型:
g_new <- randomForest(x=iris[,-5], y=as.factor(clusters_pam$clustering), keep.forest=TRUE, proximity=TRUE)
table(predict(g_new, iris[,-5]), clusters_pam$clustering)
1 2 3
1 50 0 0
2 0 51 0
3 0 0 49
为了我们的示例,并且由于 Iris 数据集非常短,我们生成了一个模拟的 Iris 数据集:
library(semiArtificial) # to generate dummy data for testing
# create tree ensemble generator for classification problem
irisGenerator<- treeEnsemble(Species~., iris, noTrees=100)
# use the generator to create new data
irisNew <- newdata(irisGenerator, size=200)
现在我们可以预测新数据集并检查它与模拟数据集的物种类别的一致性:
table(predict(g_new, irisNew[,-5]), irisNew$Species)
setosa versicolor virginica
1 66 1 4
2 1 7 56
3 5 55 5
预测概率:
predict(g_new, irisNew[,-5], type="prob")
1 2 3
1 1.000 0.000 0.000
2 0.014 0.002 0.984
3 0.000 0.000 1.000
4 1.000 0.000 0.000
5 0.020 0.068 0.912
6 0.000 1.000 0.000
7 1.000 0.000 0.000
8 0.480 0.000 0.520
9 0.526 0.000 0.474
10 1.000 0.000 0.000