SparkR 2.0 分类:如何获取性能矩阵?

如何在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)。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注