如何在SparkR分类中获取性能矩阵,例如F1分数、精确度、召回率和混淆矩阵?
# 加载训练数据
df <- read.df("data/mllib/sample_libsvm_data.txt", source = "libsvm")
training <- df
testing <- df
# 使用spark.randomForest拟合随机森林分类模型
model <- spark.randomForest(training, label ~ features, "classification", numTrees = 10)
# 模型摘要
summary(model)
# 预测
predictions <- predict(model, testing)
head(predictions)
# 性能评估
我尝试使用caret::confusionMatrix(testing$label,testing$prediction)
时,出现了错误:
Error in unique.default(x, nmax = nmax) :
unique() applies only to vectors
回答:
Caret的confusionMatrix
无法使用,因为它需要R数据框,而你的数据是Spark数据框。
一种不推荐的方法是使用as.data.frame
将Spark数据框“收集”到R中本地使用,然后使用caret
等工具;但这意味着你的数据必须能装进驱动机器的主内存,如果是这种情况,你当然完全没有理由使用Spark…
因此,这里介绍一种分布式的方式(即不将数据本地收集)来获取准确率,使用iris
数据作为示例:
sparkR.version()
# "2.1.1"
df <- as.DataFrame(iris)
model <- spark.randomForest(df, Species ~ ., "classification", numTrees = 10)
predictions <- predict(model, df)
summary(predictions)
# SparkDataFrame[summary:string, Sepal_Length:string, Sepal_Width:string, Petal_Length:string, Petal_Width:string, Species:string, prediction:string]
createOrReplaceTempView(predictions, "predictions")
correct <- sql("SELECT prediction, Species FROM predictions WHERE prediction=Species")
count(correct)
# 149
acc = count(correct)/count(predictions)
acc
# 0.9933333
(关于150个样本中有149个预测正确,如果你执行showDF(predictions, numRows=150)
,你会发现确实有一个virginica
样本被误分类为versicolor
)。