2015-01-28 20:14:23 -05:00
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
#
|
2016-03-23 14:20:44 -04:00
|
|
|
import array
|
2015-01-28 20:14:23 -05:00
|
|
|
from abc import ABCMeta
|
2015-05-18 15:02:18 -04:00
|
|
|
import copy
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2020-07-13 22:22:44 -04:00
|
|
|
import numpy as np
|
2016-04-15 15:14:41 -04:00
|
|
|
from py4j.java_gateway import JavaObject
|
|
|
|
|
2017-08-02 06:10:26 -04:00
|
|
|
from pyspark.ml.linalg import DenseVector, Vector, Matrix
|
2015-01-28 20:14:23 -05:00
|
|
|
from pyspark.ml.util import Identifiable
|
|
|
|
|
|
|
|
|
2016-03-23 14:20:44 -04:00
|
|
|
__all__ = ['Param', 'Params', 'TypeConverters']
|
2015-01-28 20:14:23 -05:00
|
|
|
|
|
|
|
|
|
|
|
class Param(object):
|
|
|
|
"""
|
2015-04-16 02:49:42 -04:00
|
|
|
A param with self-contained documentation.
|
2015-11-02 19:09:22 -05:00
|
|
|
|
|
|
|
.. versionadded:: 1.3.0
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
|
|
|
|
2016-04-25 09:32:11 -04:00
|
|
|
def __init__(self, parent, name, doc, typeConverter=None):
|
2015-05-18 15:02:18 -04:00
|
|
|
if not isinstance(parent, Identifiable):
|
|
|
|
raise TypeError("Parent must be an Identifiable but got type %s." % type(parent))
|
|
|
|
self.parent = parent.uid
|
2015-01-28 20:14:23 -05:00
|
|
|
self.name = str(name)
|
|
|
|
self.doc = str(doc)
|
2016-03-23 14:20:44 -04:00
|
|
|
self.typeConverter = TypeConverters.identity if typeConverter is None else typeConverter
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2016-01-26 18:53:48 -05:00
|
|
|
def _copy_new_parent(self, parent):
|
|
|
|
"""Copy the current param to a new parent, must be a dummy param."""
|
|
|
|
if self.parent == "undefined":
|
|
|
|
param = copy.copy(self)
|
|
|
|
param.parent = parent.uid
|
|
|
|
return param
|
|
|
|
else:
|
|
|
|
raise ValueError("Cannot copy from non-dummy parent %s." % parent)
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
def __str__(self):
|
2015-04-16 02:49:42 -04:00
|
|
|
return str(self.parent) + "__" + self.name
|
2015-01-28 20:14:23 -05:00
|
|
|
|
|
|
|
def __repr__(self):
|
2015-04-16 02:49:42 -04:00
|
|
|
return "Param(parent=%r, name=%r, doc=%r)" % (self.parent, self.name, self.doc)
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2015-05-18 15:02:18 -04:00
|
|
|
def __hash__(self):
|
|
|
|
return hash(str(self))
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, Param):
|
|
|
|
return self.parent == other.parent and self.name == other.name
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2016-03-23 14:20:44 -04:00
|
|
|
class TypeConverters(object):
|
|
|
|
"""
|
|
|
|
Factory methods for common type conversion functions for `Param.typeConverter`.
|
|
|
|
|
|
|
|
.. versionadded:: 2.0.0
|
|
|
|
"""
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _is_numeric(value):
|
|
|
|
vtype = type(value)
|
|
|
|
return vtype in [int, float, np.float64, np.int64] or vtype.__name__ == 'long'
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _is_integer(value):
|
|
|
|
return TypeConverters._is_numeric(value) and float(value).is_integer()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _can_convert_to_list(value):
|
|
|
|
vtype = type(value)
|
2020-07-13 22:22:44 -04:00
|
|
|
return vtype in [list, np.ndarray, tuple, range, array.array] or isinstance(value, Vector)
|
2016-03-23 14:20:44 -04:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _can_convert_to_string(value):
|
|
|
|
vtype = type(value)
|
2020-07-13 22:22:44 -04:00
|
|
|
return isinstance(value, str) or vtype in [np.unicode_, np.string_, np.str_]
|
2016-03-23 14:20:44 -04:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def identity(value):
|
|
|
|
"""
|
|
|
|
Dummy converter that just returns value.
|
|
|
|
"""
|
|
|
|
return value
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toList(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a list, if possible.
|
|
|
|
"""
|
|
|
|
if type(value) == list:
|
|
|
|
return value
|
2020-07-13 22:22:44 -04:00
|
|
|
elif type(value) in [np.ndarray, tuple, range, array.array]:
|
2016-03-23 14:20:44 -04:00
|
|
|
return list(value)
|
|
|
|
elif isinstance(value, Vector):
|
|
|
|
return list(value.toArray())
|
|
|
|
else:
|
|
|
|
raise TypeError("Could not convert %s to list" % value)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toListFloat(value):
|
|
|
|
"""
|
|
|
|
Convert a value to list of floats, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._can_convert_to_list(value):
|
|
|
|
value = TypeConverters.toList(value)
|
|
|
|
if all(map(lambda v: TypeConverters._is_numeric(v), value)):
|
|
|
|
return [float(v) for v in value]
|
|
|
|
raise TypeError("Could not convert %s to list of floats" % value)
|
|
|
|
|
2019-09-16 23:52:20 -04:00
|
|
|
@staticmethod
|
|
|
|
def toListListFloat(value):
|
|
|
|
"""
|
|
|
|
Convert a value to list of list of floats, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._can_convert_to_list(value):
|
|
|
|
value = TypeConverters.toList(value)
|
|
|
|
return [TypeConverters.toListFloat(v) for v in value]
|
|
|
|
raise TypeError("Could not convert %s to list of list of floats" % value)
|
|
|
|
|
2016-03-23 14:20:44 -04:00
|
|
|
@staticmethod
|
|
|
|
def toListInt(value):
|
|
|
|
"""
|
|
|
|
Convert a value to list of ints, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._can_convert_to_list(value):
|
|
|
|
value = TypeConverters.toList(value)
|
|
|
|
if all(map(lambda v: TypeConverters._is_integer(v), value)):
|
|
|
|
return [int(v) for v in value]
|
|
|
|
raise TypeError("Could not convert %s to list of ints" % value)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toListString(value):
|
|
|
|
"""
|
|
|
|
Convert a value to list of strings, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._can_convert_to_list(value):
|
|
|
|
value = TypeConverters.toList(value)
|
|
|
|
if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)):
|
|
|
|
return [TypeConverters.toString(v) for v in value]
|
|
|
|
raise TypeError("Could not convert %s to list of strings" % value)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toVector(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a MLlib Vector, if possible.
|
|
|
|
"""
|
|
|
|
if isinstance(value, Vector):
|
|
|
|
return value
|
|
|
|
elif TypeConverters._can_convert_to_list(value):
|
|
|
|
value = TypeConverters.toList(value)
|
|
|
|
if all(map(lambda v: TypeConverters._is_numeric(v), value)):
|
|
|
|
return DenseVector(value)
|
|
|
|
raise TypeError("Could not convert %s to vector" % value)
|
|
|
|
|
2017-08-02 06:10:26 -04:00
|
|
|
@staticmethod
|
|
|
|
def toMatrix(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a MLlib Matrix, if possible.
|
|
|
|
"""
|
|
|
|
if isinstance(value, Matrix):
|
|
|
|
return value
|
|
|
|
raise TypeError("Could not convert %s to matrix" % value)
|
|
|
|
|
2016-03-23 14:20:44 -04:00
|
|
|
@staticmethod
|
|
|
|
def toFloat(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a float, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._is_numeric(value):
|
|
|
|
return float(value)
|
|
|
|
else:
|
|
|
|
raise TypeError("Could not convert %s to float" % value)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toInt(value):
|
|
|
|
"""
|
|
|
|
Convert a value to an int, if possible.
|
|
|
|
"""
|
|
|
|
if TypeConverters._is_integer(value):
|
|
|
|
return int(value)
|
|
|
|
else:
|
|
|
|
raise TypeError("Could not convert %s to int" % value)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toString(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a string, if possible.
|
|
|
|
"""
|
2020-07-13 22:22:44 -04:00
|
|
|
if isinstance(value, str):
|
2016-03-23 14:20:44 -04:00
|
|
|
return value
|
2020-07-13 22:22:44 -04:00
|
|
|
elif type(value) in [np.string_, np.str_, np.unicode_]:
|
2016-03-23 14:20:44 -04:00
|
|
|
return str(value)
|
|
|
|
else:
|
|
|
|
raise TypeError("Could not convert %s to string type" % type(value))
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def toBoolean(value):
|
|
|
|
"""
|
|
|
|
Convert a value to a boolean, if possible.
|
|
|
|
"""
|
|
|
|
if type(value) == bool:
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
raise TypeError("Boolean Param requires value of type bool. Found %s." % type(value))
|
|
|
|
|
|
|
|
|
2020-09-16 07:22:11 -04:00
|
|
|
class Params(Identifiable, metaclass=ABCMeta):
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
|
|
|
Components that take parameters. This also provides an internal
|
|
|
|
param map to store parameter values attached to the instance.
|
2015-11-02 19:09:22 -05:00
|
|
|
|
|
|
|
.. versionadded:: 1.3.0
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
def __init__(self):
|
|
|
|
super(Params, self).__init__()
|
|
|
|
#: internal param map for user-supplied values param map
|
|
|
|
self._paramMap = {}
|
2015-04-16 02:49:42 -04:00
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
#: internal param map for default values
|
|
|
|
self._defaultParamMap = {}
|
2015-05-18 15:02:18 -04:00
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
#: value returned by :py:func:`params`
|
|
|
|
self._params = None
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2016-01-26 18:53:48 -05:00
|
|
|
# Copy the params from the class to the object
|
|
|
|
self._copy_params()
|
|
|
|
|
|
|
|
def _copy_params(self):
|
|
|
|
"""
|
|
|
|
Copy all params defined on the class to current object.
|
|
|
|
"""
|
|
|
|
cls = type(self)
|
|
|
|
src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]
|
|
|
|
src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))
|
|
|
|
for name, param in src_params:
|
|
|
|
setattr(self, name, param._copy_new_parent(self))
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
@property
|
|
|
|
def params(self):
|
|
|
|
"""
|
2015-04-16 02:49:42 -04:00
|
|
|
Returns all params ordered by name. The default implementation
|
|
|
|
uses :py:func:`dir` to get all attributes of type
|
2015-01-28 20:14:23 -05:00
|
|
|
:py:class:`Param`.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
if self._params is None:
|
|
|
|
self._params = list(filter(lambda attr: isinstance(attr, Param),
|
2016-03-08 20:34:25 -05:00
|
|
|
[getattr(self, x) for x in dir(self) if x != "params" and
|
|
|
|
not isinstance(getattr(type(self), x, None), property)]))
|
2015-05-18 15:02:18 -04:00
|
|
|
return self._params
|
2015-01-28 20:14:23 -05:00
|
|
|
|
2015-05-18 15:02:18 -04:00
|
|
|
def explainParam(self, param):
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
|
|
|
Explains a single param and returns its name, doc, and optional
|
|
|
|
default value and user-supplied value in a string.
|
|
|
|
"""
|
|
|
|
param = self._resolveParam(param)
|
|
|
|
values = []
|
|
|
|
if self.isDefined(param):
|
2015-05-18 15:02:18 -04:00
|
|
|
if param in self._defaultParamMap:
|
|
|
|
values.append("default: %s" % self._defaultParamMap[param])
|
|
|
|
if param in self._paramMap:
|
|
|
|
values.append("current: %s" % self._paramMap[param])
|
2015-04-16 02:49:42 -04:00
|
|
|
else:
|
|
|
|
values.append("undefined")
|
|
|
|
valueStr = "(" + ", ".join(values) + ")"
|
|
|
|
return "%s: %s %s" % (param.name, param.doc, valueStr)
|
|
|
|
|
|
|
|
def explainParams(self):
|
|
|
|
"""
|
|
|
|
Returns the documentation of all params with their optionally
|
|
|
|
default values and user-supplied values.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
return "\n".join([self.explainParam(param) for param in self.params])
|
2015-04-16 02:49:42 -04:00
|
|
|
|
|
|
|
def getParam(self, paramName):
|
|
|
|
"""
|
|
|
|
Gets a param by its name.
|
|
|
|
"""
|
|
|
|
param = getattr(self, paramName)
|
|
|
|
if isinstance(param, Param):
|
|
|
|
return param
|
|
|
|
else:
|
|
|
|
raise ValueError("Cannot find param with name %s." % paramName)
|
|
|
|
|
|
|
|
def isSet(self, param):
|
|
|
|
"""
|
|
|
|
Checks whether a param is explicitly set by user.
|
|
|
|
"""
|
|
|
|
param = self._resolveParam(param)
|
2015-05-18 15:02:18 -04:00
|
|
|
return param in self._paramMap
|
2015-04-16 02:49:42 -04:00
|
|
|
|
|
|
|
def hasDefault(self, param):
|
|
|
|
"""
|
|
|
|
Checks whether a param has a default value.
|
|
|
|
"""
|
|
|
|
param = self._resolveParam(param)
|
2015-05-18 15:02:18 -04:00
|
|
|
return param in self._defaultParamMap
|
2015-04-16 02:49:42 -04:00
|
|
|
|
|
|
|
def isDefined(self, param):
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
Checks whether a param is explicitly set by user or has
|
|
|
|
a default value.
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
|
|
|
return self.isSet(param) or self.hasDefault(param)
|
|
|
|
|
2015-05-18 15:02:18 -04:00
|
|
|
def hasParam(self, paramName):
|
|
|
|
"""
|
|
|
|
Tests whether this instance contains a param with a given
|
|
|
|
(string) name.
|
|
|
|
"""
|
2020-07-13 22:22:44 -04:00
|
|
|
if isinstance(paramName, str):
|
2016-02-11 19:42:44 -05:00
|
|
|
p = getattr(self, paramName, None)
|
|
|
|
return isinstance(p, Param)
|
|
|
|
else:
|
|
|
|
raise TypeError("hasParam(): paramName must be a string")
|
2015-05-18 15:02:18 -04:00
|
|
|
|
2015-04-16 02:49:42 -04:00
|
|
|
def getOrDefault(self, param):
|
|
|
|
"""
|
|
|
|
Gets the value of a param in the user-supplied param map or its
|
2015-05-20 18:16:12 -04:00
|
|
|
default value. Raises an error if neither is set.
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
param = self._resolveParam(param)
|
|
|
|
if param in self._paramMap:
|
|
|
|
return self._paramMap[param]
|
2015-04-16 02:49:42 -04:00
|
|
|
else:
|
2015-05-18 15:02:18 -04:00
|
|
|
return self._defaultParamMap[param]
|
2015-04-16 02:49:42 -04:00
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
def extractParamMap(self, extra=None):
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
|
|
|
Extracts the embedded default param values and user-supplied
|
|
|
|
values, and then merges them with extra values from input into
|
|
|
|
a flat param map, where the latter value is used if there exist
|
|
|
|
conflicts, i.e., with ordering: default param values <
|
2015-05-18 15:02:18 -04:00
|
|
|
user-supplied values < extra.
|
2015-09-21 17:24:19 -04:00
|
|
|
|
2020-11-09 19:33:48 -05:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
extra : dict, optional
|
|
|
|
extra param values
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
dict
|
|
|
|
merged param map
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
2015-08-14 15:46:05 -04:00
|
|
|
if extra is None:
|
|
|
|
extra = dict()
|
2015-05-18 15:02:18 -04:00
|
|
|
paramMap = self._defaultParamMap.copy()
|
|
|
|
paramMap.update(self._paramMap)
|
|
|
|
paramMap.update(extra)
|
2015-01-28 20:14:23 -05:00
|
|
|
return paramMap
|
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
def copy(self, extra=None):
|
2015-05-18 15:02:18 -04:00
|
|
|
"""
|
|
|
|
Creates a copy of this instance with the same uid and some
|
|
|
|
extra params. The default implementation creates a
|
|
|
|
shallow copy using :py:func:`copy.copy`, and then copies the
|
|
|
|
embedded and extra parameters over and returns the copy.
|
|
|
|
Subclasses should override this method if the default approach
|
|
|
|
is not sufficient.
|
2015-09-21 17:24:19 -04:00
|
|
|
|
2020-11-09 19:33:48 -05:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
extra : dict, optional
|
|
|
|
Extra parameters to copy to the new instance
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
:py:class:`Params`
|
|
|
|
Copy of this instance
|
2015-05-18 15:02:18 -04:00
|
|
|
"""
|
2015-08-14 15:46:05 -04:00
|
|
|
if extra is None:
|
|
|
|
extra = dict()
|
2015-05-18 15:02:18 -04:00
|
|
|
that = copy.copy(self)
|
2016-04-15 15:14:41 -04:00
|
|
|
that._paramMap = {}
|
2017-02-23 21:05:58 -05:00
|
|
|
that._defaultParamMap = {}
|
2016-04-15 15:14:41 -04:00
|
|
|
return self._copyValues(that, extra)
|
2015-05-18 15:02:18 -04:00
|
|
|
|
2017-08-07 20:03:20 -04:00
|
|
|
def set(self, param, value):
|
|
|
|
"""
|
|
|
|
Sets a parameter in the embedded param map.
|
|
|
|
"""
|
|
|
|
self._shouldOwn(param)
|
|
|
|
try:
|
|
|
|
value = param.typeConverter(value)
|
|
|
|
except ValueError as e:
|
|
|
|
raise ValueError('Invalid param value given for param "%s". %s' % (param.name, e))
|
|
|
|
self._paramMap[param] = value
|
|
|
|
|
2015-04-16 02:49:42 -04:00
|
|
|
def _shouldOwn(self, param):
|
|
|
|
"""
|
|
|
|
Validates that the input param belongs to this Params instance.
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
if not (self.uid == param.parent and self.hasParam(param.name)):
|
2015-04-16 02:49:42 -04:00
|
|
|
raise ValueError("Param %r does not belong to %r." % (param, self))
|
|
|
|
|
|
|
|
def _resolveParam(self, param):
|
|
|
|
"""
|
|
|
|
Resolves a param and validates the ownership.
|
2015-09-21 17:24:19 -04:00
|
|
|
|
2020-11-09 19:33:48 -05:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
param : str or :py:class:`Param`
|
|
|
|
param name or the param instance, which must
|
|
|
|
belong to this Params instance
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
:py:class:`Param`
|
|
|
|
resolved param instance
|
2015-04-16 02:49:42 -04:00
|
|
|
"""
|
|
|
|
if isinstance(param, Param):
|
|
|
|
self._shouldOwn(param)
|
|
|
|
return param
|
2020-07-13 22:22:44 -04:00
|
|
|
elif isinstance(param, str):
|
2015-04-16 02:49:42 -04:00
|
|
|
return self.getParam(param)
|
|
|
|
else:
|
2021-05-03 02:34:24 -04:00
|
|
|
raise TypeError("Cannot resolve %r as a param." % param)
|
2015-04-16 02:49:42 -04:00
|
|
|
|
[SPARK-33592] Fix: Pyspark ML Validator params in estimatorParamMaps may be lost after saving and reloading
### What changes were proposed in this pull request?
Fix: Pyspark ML Validator params in estimatorParamMaps may be lost after saving and reloading
When saving validator estimatorParamMaps, will check all nested stages in tuned estimator to get correct param parent.
Two typical cases to manually test:
~~~python
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression()
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
paramGrid = ParamGridBuilder() \
.addGrid(hashingTF.numFeatures, [10, 100]) \
.addGrid(lr.maxIter, [100, 200]) \
.build()
tvs = TrainValidationSplit(estimator=pipeline,
estimatorParamMaps=paramGrid,
evaluator=MulticlassClassificationEvaluator())
tvs.save(tvsPath)
loadedTvs = TrainValidationSplit.load(tvsPath)
# check `loadedTvs.getEstimatorParamMaps()` restored correctly.
~~~
~~~python
lr = LogisticRegression()
ova = OneVsRest(classifier=lr)
grid = ParamGridBuilder().addGrid(lr.maxIter, [100, 200]).build()
evaluator = MulticlassClassificationEvaluator()
tvs = TrainValidationSplit(estimator=ova, estimatorParamMaps=grid, evaluator=evaluator)
tvs.save(tvsPath)
loadedTvs = TrainValidationSplit.load(tvsPath)
# check `loadedTvs.getEstimatorParamMaps()` restored correctly.
~~~
### Why are the changes needed?
Bug fix.
### Does this PR introduce _any_ user-facing change?
No
### How was this patch tested?
Unit test.
Closes #30539 from WeichenXu123/fix_tuning_param_maps_io.
Authored-by: Weichen Xu <weichen.xu@databricks.com>
Signed-off-by: Ruifeng Zheng <ruifengz@foxmail.com>
2020-11-30 20:36:42 -05:00
|
|
|
def _testOwnParam(self, param_parent, param_name):
|
|
|
|
"""
|
|
|
|
Test the ownership. Return True or False
|
|
|
|
"""
|
|
|
|
return self.uid == param_parent and self.hasParam(param_name)
|
|
|
|
|
2015-01-28 20:14:23 -05:00
|
|
|
@staticmethod
|
|
|
|
def _dummy():
|
|
|
|
"""
|
2015-05-18 15:02:18 -04:00
|
|
|
Returns a dummy Params instance used as a placeholder to
|
|
|
|
generate docs.
|
2015-01-28 20:14:23 -05:00
|
|
|
"""
|
|
|
|
dummy = Params()
|
|
|
|
dummy.uid = "undefined"
|
|
|
|
return dummy
|
2015-02-15 23:29:26 -05:00
|
|
|
|
2015-04-16 02:49:42 -04:00
|
|
|
def _set(self, **kwargs):
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
2015-04-16 02:49:42 -04:00
|
|
|
Sets user-supplied params.
|
2015-02-15 23:29:26 -05:00
|
|
|
"""
|
2015-04-16 19:20:57 -04:00
|
|
|
for param, value in kwargs.items():
|
2016-01-06 13:43:03 -05:00
|
|
|
p = getattr(self, param)
|
2016-03-23 14:20:44 -04:00
|
|
|
if value is not None:
|
2016-01-06 13:43:03 -05:00
|
|
|
try:
|
2016-03-23 14:20:44 -04:00
|
|
|
value = p.typeConverter(value)
|
|
|
|
except TypeError as e:
|
|
|
|
raise TypeError('Invalid param value given for param "%s". %s' % (p.name, e))
|
|
|
|
self._paramMap[p] = value
|
2015-02-15 23:29:26 -05:00
|
|
|
return self
|
2015-04-16 02:49:42 -04:00
|
|
|
|
2019-10-17 20:02:31 -04:00
|
|
|
def clear(self, param):
|
2016-04-15 15:14:41 -04:00
|
|
|
"""
|
|
|
|
Clears a param from the param map if it has been explicitly set.
|
|
|
|
"""
|
|
|
|
if self.isSet(param):
|
|
|
|
del self._paramMap[param]
|
|
|
|
|
2015-04-16 02:49:42 -04:00
|
|
|
def _setDefault(self, **kwargs):
|
|
|
|
"""
|
|
|
|
Sets default params.
|
|
|
|
"""
|
2015-04-16 19:20:57 -04:00
|
|
|
for param, value in kwargs.items():
|
2016-04-15 15:14:41 -04:00
|
|
|
p = getattr(self, param)
|
|
|
|
if value is not None and not isinstance(value, JavaObject):
|
|
|
|
try:
|
|
|
|
value = p.typeConverter(value)
|
|
|
|
except TypeError as e:
|
|
|
|
raise TypeError('Invalid default param value given for param "%s". %s'
|
|
|
|
% (p.name, e))
|
|
|
|
self._defaultParamMap[p] = value
|
2015-04-16 02:49:42 -04:00
|
|
|
return self
|
2015-05-18 15:02:18 -04:00
|
|
|
|
2015-08-14 15:46:05 -04:00
|
|
|
def _copyValues(self, to, extra=None):
|
2015-05-18 15:02:18 -04:00
|
|
|
"""
|
|
|
|
Copies param values from this instance to another instance for
|
|
|
|
params shared by them.
|
2015-09-21 17:24:19 -04:00
|
|
|
|
2020-11-09 19:33:48 -05:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
to : :py:class:`Params`
|
|
|
|
the target instance
|
|
|
|
extra : dict, optional
|
|
|
|
extra params to be copied
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
:py:class:`Params`
|
|
|
|
the target instance with param values copied
|
2015-05-18 15:02:18 -04:00
|
|
|
"""
|
2017-02-23 21:05:58 -05:00
|
|
|
paramMap = self._paramMap.copy()
|
2019-11-19 17:15:00 -05:00
|
|
|
if isinstance(extra, dict):
|
|
|
|
for param, value in extra.items():
|
|
|
|
if isinstance(param, Param):
|
|
|
|
paramMap[param] = value
|
|
|
|
else:
|
|
|
|
raise TypeError("Expecting a valid instance of Param, but received: {}"
|
|
|
|
.format(param))
|
|
|
|
elif extra is not None:
|
|
|
|
raise TypeError("Expecting a dict, but received an object of type {}."
|
|
|
|
.format(type(extra)))
|
2017-02-23 21:05:58 -05:00
|
|
|
for param in self.params:
|
|
|
|
# copy default params
|
|
|
|
if param in self._defaultParamMap and to.hasParam(param.name):
|
|
|
|
to._defaultParamMap[to.getParam(param.name)] = self._defaultParamMap[param]
|
|
|
|
# copy explicitly set params
|
|
|
|
if param in paramMap and to.hasParam(param.name):
|
|
|
|
to._set(**{param.name: paramMap[param]})
|
2015-05-18 15:02:18 -04:00
|
|
|
return to
|
2016-01-29 12:22:24 -05:00
|
|
|
|
|
|
|
def _resetUid(self, newUid):
|
|
|
|
"""
|
|
|
|
Changes the uid of this instance. This updates both
|
|
|
|
the stored uid and the parent uid of params and param maps.
|
|
|
|
This is used by persistence (loading).
|
2020-11-09 19:33:48 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
newUid
|
|
|
|
new uid to use, which is converted to unicode
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
:py:class:`Params`
|
|
|
|
same instance, but with the uid and Param.parent values
|
|
|
|
updated, including within param maps
|
2016-01-29 12:22:24 -05:00
|
|
|
"""
|
2020-07-13 22:22:44 -04:00
|
|
|
newUid = str(newUid)
|
2016-01-29 12:22:24 -05:00
|
|
|
self.uid = newUid
|
|
|
|
newDefaultParamMap = dict()
|
|
|
|
newParamMap = dict()
|
|
|
|
for param in self.params:
|
|
|
|
newParam = copy.copy(param)
|
|
|
|
newParam.parent = newUid
|
|
|
|
if param in self._defaultParamMap:
|
|
|
|
newDefaultParamMap[newParam] = self._defaultParamMap[param]
|
|
|
|
if param in self._paramMap:
|
|
|
|
newParamMap[newParam] = self._paramMap[param]
|
|
|
|
param.parent = newUid
|
|
|
|
self._defaultParamMap = newDefaultParamMap
|
|
|
|
self._paramMap = newParamMap
|
|
|
|
return self
|