Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SW-2646] Calculate Metrics on Arbitrary Dataset #2745

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
753562d
[SW-2646] Calculate Metrics on Arbitrary Dataset
mn-mikke Nov 15, 2021
d8af501
Update api
mn-mikke Mar 18, 2022
5ed9b34
Remove unrelated tests
mn-mikke Mar 21, 2022
c50fffe
Remove unrelated logic
mn-mikke Mar 21, 2022
aeb48eb
Remove unrelated logic
mn-mikke Mar 21, 2022
e25801a
Remove extra dependency
mn-mikke Mar 21, 2022
32db73d
Remove extra dependency and return test back
mn-mikke Mar 21, 2022
a777a7d
Remove extra tests
mn-mikke Mar 21, 2022
66f0451
Update tests
mn-mikke Mar 21, 2022
38e5ab4
Fix tests
mn-mikke Mar 22, 2022
d118f74
Fix tests
mn-mikke Mar 25, 2022
3f4cf56
Python wrappers
mn-mikke Mar 28, 2022
3f2dabd
Fix multinomial tests
mn-mikke Mar 29, 2022
ef0670c
Remove prior distribution
mn-mikke Mar 29, 2022
6a4a15c
remove distribution option
mn-mikke Mar 29, 2022
624a627
spotless Apply
mn-mikke Mar 29, 2022
cefff34
dataType checks
mn-mikke Mar 29, 2022
75d1274
revert test changes in python
mn-mikke Mar 30, 2022
e6887bc
revert change in R
mn-mikke Mar 30, 2022
1708d9b
Add R classes
mn-mikke Mar 30, 2022
5240eba
Remove offset column from multinomial metrics
mn-mikke Mar 30, 2022
0dfc38e
Fix metric factory generatino
mn-mikke Mar 30, 2022
afd7676
Use original builders instead
mn-mikke Apr 4, 2022
756e169
Add python smoke tests
mn-mikke Apr 4, 2022
d1de562
Use master version
mn-mikke Apr 5, 2022
df87eb3
Update python API
mn-mikke Apr 5, 2022
87d434c
fix formatting
mn-mikke Apr 7, 2022
3002e21
fix python test
mn-mikke Apr 7, 2022
93fd203
Add R tests
mn-mikke Apr 8, 2022
c939266
add more conditions to python tests
mn-mikke Apr 8, 2022
da2c335
spotless apply
mn-mikke Apr 8, 2022
da8417c
Update metric calculation to work with just probabilities
mn-mikke Apr 12, 2022
45bc54e
Fix Python test
mn-mikke Apr 12, 2022
1965292
Fix R test
mn-mikke Apr 13, 2022
7e8f954
Address review comments from Bartosz
mn-mikke Apr 14, 2022
2be8b85
spotless apply
mn-mikke Apr 19, 2022
ea696fe
dataframe.isEmpty is not present in spark 2.2
mn-mikke Apr 20, 2022
e5457e8
Merge remote-tracking branch 'origin/master' into mn/SW-2646b
krasinski Jun 2, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update python API
  • Loading branch information
mn-mikke committed Apr 12, 2022
commit df87eb3330ba291eb402a34c923e875eeb787224
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ import ai.h2o.sparkling.api.generation.common.{EntitySubstitutionContext, ModelM
object MetricsInitTemplate extends ((Seq[ModelMetricsSubstitutionContext]) => String) with PythonEntityTemplate {

def apply(metricSubstitutionContexts: Seq[ModelMetricsSubstitutionContext]): String = {
val metricClasses = metricSubstitutionContexts.map(_.entityName)
val metricClasses = metricSubstitutionContexts.map { metricSubstitutionContext =>
if (metricSubstitutionContext.entityName.endsWith("Base")) {
metricSubstitutionContext.entityName.substring(0, metricSubstitutionContext.entityName.length - 4)
} else {
metricSubstitutionContext.entityName
}
}
val imports = metricClasses.map(metricClass => s"ai.h2o.sparkling.ml.metrics.$metricClass.$metricClass")

val entitySubstitutionContext = EntitySubstitutionContext(null, null, null, imports)
Expand Down
1 change: 1 addition & 0 deletions py-scoring/src/ai/h2o/sparkling/ml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
from ai.h2o.sparkling.ml.models import H2ODeepLearningMOJOModel, H2ODRFMOJOModel, H2OIsolationForestMOJOModel, H2OPCAMOJOModel, H2OGLRMMOJOModel
from ai.h2o.sparkling.ml.models import H2OMOJOModel, H2OAlgorithmMOJOModel, H2OFeatureMOJOModel, H2OMOJOPipelineModel, H2OMOJOSettings
from ai.h2o.sparkling.ml.models import H2OCoxPHMOJOModel, H2ORuleFitMOJOModel, H2OWord2VecMOJOModel
from ai.h2o.sparkling.ml.metrics import H2ORegressionMetrics, H2OBinomialMetrics, H2OMultinomialMetrics
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,26 @@ def calculate(dataFrame,
labelCol = "label",
weightCol = None,
offsetCol = None):
'''
The method calculates binomial metrics on a provided data frame with predictions and actual values.
:param dataFrame: A data frame with predictions and actual values
:param domain: A list of classes representing negative and positive response. Negative class must at position 0
and positive at 1
:param predictionCol: The name of prediction column. The prediction column must have the same type as
a detailed_prediction column coming from the transform method of H2OMOJOModel descendant or a array type or
vector of doubles. First item is must be 0.0 or 1.0 representing negative or positive response. The other items
must be probabilities to predict given probability classes.
:param labelCol: The name of label column that contains actual values.
:param weightCol: The name of a weight column.
:param offsetCol: The name of a offset column.
:return: Calculated binomial metrics
'''
# We need to make sure that Sparkling Water classes are available on the Spark driver and executor paths
Initializer.load_sparkling_jar()
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2OBinomialMetrics.calculate(dataFrame,
domain,
predictionCol,
labelCol,
weightCol,
offsetCol)
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2OBinomialMetrics.calculateInternal(dataFrame._jdf,
domain,
predictionCol,
labelCol,
weightCol,
offsetCol)
return H2OBinomialMetrics(javaMetrics)
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,31 @@ def calculate(dataFrame,
labelCol = "label",
weightCol = None,
aucType = "AUTO"):
'''
The method calculates multinomial metrics on a provided data frame with predictions and actual values.
:param dataFrame: A data frame with predictions and actual values.
:param domain: List of response classes.
:param predictionCol: The name of prediction column. The prediction column must have the same type as
a detailed_prediction column coming from the transform method of H2OMOJOModel descendant or a array type or
vector of doubles. First item is must be 0.0, 1.0, 2.0 representing indexes of response classes. The other
items must be probabilities to predict given probability classes.
:param labelCol: The name of label column that contains actual values.
:param weightCol: The name of a weight column.
:param aucType: Type of multinomial AUC/AUCPR calculation. Possible values:
- AUTO,
- NONE,
- MACRO_OVR,
- WEIGHTED_OVR,
- MACRO_OVO,
- WEIGHTED_OVO
:return: Calculated multinomial metrics
'''
# We need to make sure that Sparkling Water classes are available on the Spark driver and executor paths
Initializer.load_sparkling_jar()
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2OMultinomialMetrics.calculate(dataFrame,
domain,
predictionCol,
labelCol,
weightCol,
aucType)
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2OMultinomialMetrics.calculateInternal(dataFrame._jdf,
domain,
predictionCol,
labelCol,
weightCol,
aucType)
return H2OMultinomialMetrics(javaMetrics)
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,26 @@ class H2ORegressionMetrics(H2ORegressionMetricsBase):

@staticmethod
def calculate(dataFrame,
domain,
predictionCol = "detailed_prediction",
labelCol = "label",
weightCol = None,
offsetCol = None):
'''
The method calculates regression metrics on a provided data frame with predictions and actual values.
:param dataFrame: A data frame with predictions and actual values
:param predictionCol: The name of prediction column. The prediction column must have the same type as
a detailed_prediction column coming from the transform method of H2OMOJOModel descendant or
it must be of DoubleType or FloatType.
:param labelCol: The name of label column that contains actual values.
:param weightCol: The name of a weight column.
:param offsetCol: The name of a offset column.
:return: Calculated regression metrics
'''
# We need to make sure that Sparkling Water classes are available on the Spark driver and executor paths
Initializer.load_sparkling_jar()
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2ORegressionMetrics.calculate(dataFrame,
domain,
predictionCol,
labelCol,
weightCol,
offsetCol)
javaMetrics = _jvm().ai.h2o.sparkling.ml.metrics.H2ORegressionMetrics.calculateInternal(dataFrame._jdf,
predictionCol,
labelCol,
weightCol,
offsetCol)
return H2ORegressionMetrics(javaMetrics)
4 changes: 3 additions & 1 deletion py-scoring/src/pysparkling/ml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
#

from pysparkling.ml.models import *
from pysparkling.ml.metrics import *

__all__ = ["H2OMOJOModel", "H2OSupervisedMOJOModel", "H2OTreeBasedSupervisedMOJOModel", "H2OUnsupervisedMOJOModel",
"H2OTreeBasedUnsupervisedMOJOModel", "H2OMOJOPipelineModel", "H2OMOJOSettings", "H2OBinaryModel",
"H2OKMeansMOJOModel", "H2OGLMMOJOModel", "H2OGAMMOJOModel", "H2OGBMMOJOModel", "H2OXGBoostMOJOModel",
"H2ODeepLearningMOJOModel", "H2ODRFMOJOModel", "H2OIsolationForestMOJOModel", "H2OPCAMOJOModel",
"H2OGLRMMOJOModel", "H2OCoxPHMOJOModel", "H2ORuleFitMOJOModel", "H2OWord2VecMOJOModel"]
"H2OGLRMMOJOModel", "H2OCoxPHMOJOModel", "H2ORuleFitMOJOModel", "H2OWord2VecMOJOModel",
"H2ORegressionMetrics", "H2OMultinomialMetrics", "H2OBinomialMetrics"]

from pysparkling.initializer import Initializer

Expand Down
20 changes: 20 additions & 0 deletions py-scoring/src/pysparkling/ml/metrics/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from ai.h2o.sparkling.ml.metrics import H2ORegressionMetrics, H2OMultinomialMetrics, H2OBinomialMetrics

__all__ = ["H2ORegressionMetrics", "H2OMultinomialMetrics", "H2OBinomialMetrics"]
1 change: 1 addition & 0 deletions py/src/ai/h2o/sparkling/ml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@
from ai.h2o.sparkling.ml.models import H2ODeepLearningMOJOModel, H2OWord2VecMOJOModel, H2OAutoEncoderMOJOModel, H2ODRFMOJOModel, H2OPCAMOJOModel, H2OGLRMMOJOModel
from ai.h2o.sparkling.ml.models import H2OIsolationForestMOJOModel, H2OCoxPHMOJOModel, H2ORuleFitMOJOModel, H2OStackedEnsembleMOJOModel
from ai.h2o.sparkling.ml.models import H2OMOJOModel, H2OAlgorithmMOJOModel, H2OFeatureMOJOModel, H2OMOJOPipelineModel, H2OMOJOSettings
from ai.h2o.sparkling.ml.metrics import H2ORegressionMetrics, H2OBinomialMetrics, H2OMultinomialMetrics
3 changes: 2 additions & 1 deletion py/src/pysparkling/ml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from pysparkling.ml.algos.regression import *
from pysparkling.ml.features import *
from pysparkling.ml.models import *
from pysparkling.ml.metrics import *

__all__ = ["ColumnPruner", "H2OGBM", "H2ODeepLearning", "H2OAutoML", "H2OXGBoost", "H2OGLM", "H2OCoxPH", "H2OGAM",
"H2OMOJOModel", "H2OAlgorithmMOJOModel", "H2OFeatureMOJOModel", "H2OSupervisedMOJOModel",
Expand All @@ -32,7 +33,7 @@
"H2ODRFMOJOModel", "H2OIsolationForestMOJOModel", "H2OWord2Vec", "H2OWord2VecMOJOModel", "H2OAutoEncoder",
"H2OAutoEncoderMOJOModel", "H2OPCA", "H2OPCAMOJOModel", "H2OGLRM", "H2OGLRMMOJOModel", "H2ORuleFit",
"H2ORuleFitClassifier", "H2ORuleFitRegressor", "H2ORuleFitMOJOModel", "H2OStackedEnsemble",
"H2OStackedEnsembleMOJOModel"]
"H2OStackedEnsembleMOJOModel", "H2ORegressionMetrics", "H2OBinomialMetrics", "H2OMultinomialMetrics"]

from pysparkling.initializer import Initializer

Expand Down
21 changes: 21 additions & 0 deletions py/src/pysparkling/ml/metrics/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from ai.h2o.sparkling.ml.metrics import H2ORegressionMetrics, H2OBinomialMetrics, H2OMultinomialMetrics


__all__ = ["H2ORegressionMetrics", "H2OBinomialMetrics", "H2OMultinomialMetrics"]
5 changes: 5 additions & 0 deletions py/tests/unit/with_runtime_sparkling/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ def irisDatasetPath():
return "file://" + os.path.abspath("../examples/smalldata/iris/iris_wheader.csv")


@pytest.fixture(scope="module")
def irisDataset(spark, irisDatasetPath):
return spark.read.csv(irisDatasetPath, header=True, inferSchema=True)


@pytest.fixture(scope="module")
def airlinesDatasetPath():
return "file://" + os.path.abspath("../examples/smalldata/airlines/allyears2k_headers.csv")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,19 @@
import os
from pysparkling.ml import *

from ai.h2o.sparkling.ml.models.H2OBinomialMetrics import H2OBinomialMetrics
from ai.h2o.sparkling.ml.models.H2OMultinomialMetrics import H2OMultinomialMetrics
from ai.h2o.sparkling.ml.models.H2ORegressionMetrics import H2ORegressionMetrics
from ai.h2o.sparkling.ml.models.H2OMOJOModel import H2OMOJOModel


def testRegressionMetricsCalculation(prostateDataset):
mojo = H2OMOJOModel.createFromMojo(
"file://" + os.path.abspath("../ml/src/test/resources/regre_model_prostate.mojo"))
metrics = H2ORegressionMetrics.calculate(mojo.transform(prostateDataset), labelCol = "capsule")
metrics = H2ORegressionMetrics.calculate(mojo.transform(prostateDataset), labelCol = "CAPSULE")
assert metrics is not None


def testBinomialMetricsCalculation(prostateDataset):
mojo = H2OMOJOModel.createFromMojo(
"file://" + os.path.abspath("../ml/src/test/resources/binom_model_prostate.mojo"))
domain = mojo.getDomainValues()["capsule"]
metrics = H2OBinomialMetrics.calculate(mojo.transform(prostateDataset), domain, labelCol = "capsule")
metrics = H2OBinomialMetrics.calculate(mojo.transform(prostateDataset), domain, labelCol = "CAPSULE")
assert metrics is not None


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,15 @@ object H2OBinomialMetrics extends MetricCalculation {
result
}

def calculate(
// The method serves for call from Python/R API
def calculateInternal(
dataFrame: DataFrame,
domain: Array[String],
domain: java.util.ArrayList[String],
predictionCol: String,
labelCol: String,
weightCol: String,
offsetCol: String): Unit = {
calculate(dataFrame, domain, predictionCol, labelCol, Option(weightCol), Option(offsetCol))
calculate(dataFrame, domain.toArray[String](new Array[String](0)), predictionCol, labelCol, Option(weightCol), Option(offsetCol))
}

override protected def getPredictionValues(dataType: DataType, domain: Array[String], row: Row): Array[Double] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import hex.MultinomialAucType
import org.apache.spark.{ExposeUtils, ml, mllib}
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.functions.col
import org.apache.spark.sql.{DataFrame, Row}
import org.apache.spark.sql.{DataFrame, Dataset, Row}
import org.apache.spark.sql.types.{ArrayType, DataType, DoubleType, FloatType, StringType, StructType}

@MetricsDescription(
Expand All @@ -38,7 +38,7 @@ object H2OMultinomialMetrics extends MetricCalculation {
/**
* The method calculates multinomial metrics on a provided data frame with predictions and actual values.
*
* @param dataFrame A data frame with predictions and actual values
* @param dataFrame A data frame with predictions and actual values.
* @param domain Array of response classes.
* @param predictionCol The name of prediction column. The prediction column must have the same type as
* a detailed_prediction column coming from the transform method of H2OMOJOModel descendant or
Expand Down Expand Up @@ -77,14 +77,15 @@ object H2OMultinomialMetrics extends MetricCalculation {
result
}

def calculate(
// The method serves for call from Python/R API
def calculateInternal(
dataFrame: DataFrame,
domain: Array[String],
domain: java.util.ArrayList[String],
predictionCol: String,
labelCol: String,
weightCol: String,
aucType: String): H2OMultinomialMetrics = {
calculate(dataFrame, domain, predictionCol, labelCol, Option(weightCol), aucType)
calculate(dataFrame, domain.toArray[String](new Array[String](0)), predictionCol, labelCol, Option(weightCol), aucType)
}

override protected def getPredictionValues(dataType: DataType, domain: Array[String], row: Row): Array[Double] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ object H2ORegressionMetrics extends MetricCalculation {
result
}

def calculate(
// The method serves for call from Python/R API
def calculateInternal(
dataFrame: DataFrame,
predictionCol: String,
labelCol: String,
Expand Down