Python sklearn.__version__() Examples

The following are 30 code examples of sklearn.__version__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sklearn , or try the search function .
Example #1
Source File: utility.py    From pyod with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def _get_sklearn_version():  # pragma: no cover
    """ Utility function to decide the version of sklearn.
    PyOD will result in different behaviors with different sklearn version

    Returns
    -------
    sk_learn version : int

    """

    sklearn_version = str(sklearn.__version__)
    if int(sklearn_version.split(".")[1]) < 19 or int(
            sklearn_version.split(".")[1]) > 23:
        raise ValueError("Sklearn version error")

    return int(sklearn_version.split(".")[1]) 
Example #2
Source File: nanotron.py    From picasso with MIT License 6 votes vote down vote up
def save_model(self):

        if self.mlp is not None:

            fname, ext = QtWidgets.QFileDialog.getSaveFileName(
                self,
                "Save mode file",
                "model.sav",
                ".sav",
            )

            base, ext = _ospath.splitext(fname)
            fname = base + ".sav"

            self.train_log["Model"] = fname
            self.train_log["Generated by"] = "Picasso nanoTRON : Train"
            import sklearn
            self.train_log["Scikit-Learn Version"] = sklearn.__version__
            self.train_log["Created on"] = datetime.datetime.now()

            if fname:
                joblib.dump(self.mlp, fname)
                print("Saving complete.")
                info_path = base + ".yaml"
                io.save_info(info_path, [self.train_log]) 
Example #3
Source File: dispatcher.py    From daal4py with Apache License 2.0 6 votes vote down vote up
def enable(name=None, verbose=True):
    if LooseVersion(sklearn_version) < LooseVersion("0.20.0"):
        raise NotImplementedError("daal4py patches apply  for scikit-learn >= 0.20.0 only ...")
    elif LooseVersion(sklearn_version) > LooseVersion("0.23.1"):
        warn_msg = ("daal4py {daal4py_version} has only been tested " +
                    "with scikit-learn 0.23.1, found version: {sklearn_version}")
        warnings.warn(warn_msg.format(
            daal4py_version=daal4py_version,
            sklearn_version=sklearn_version)
        )

    if name is not None:
        do_patch(name)
    else:
        for key in _mapping:
            do_patch(key)
    if verbose and sys.stderr is not None:
        sys.stderr.write("Intel(R) Data Analytics Acceleration Library (Intel(R) DAAL) solvers for sklearn enabled: "
                         "https://intelpython.github.io/daal4py/sklearn.html\n") 
Example #4
Source File: utility.py    From pyod with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _sklearn_version_21():  # pragma: no cover
    """ Utility function to decide the version of sklearn
    In sklearn 21.0, LOF is changed. Specifically, _decision_function
    is replaced by _score_samples

    Returns
    -------
    sklearn_21_flag : bool
        True if sklearn.__version__ is newer than 0.21.0

    """
    sklearn_version = str(sklearn.__version__)
    if int(sklearn_version.split(".")[1]) > 20:
        return True
    else:
        return False 
Example #5
Source File: sklearn.py    From mlflow with Apache License 2.0 6 votes vote down vote up
def get_default_conda_env(include_cloudpickle=False):
    """
    :return: The default Conda environment for MLflow Models produced by calls to
             :func:`save_model()` and :func:`log_model()`.
    """
    import sklearn
    pip_deps = None
    if include_cloudpickle:
        import cloudpickle
        pip_deps = ["cloudpickle=={}".format(cloudpickle.__version__)]
    return _mlflow_conda_env(
        additional_conda_deps=[
            "scikit-learn={}".format(sklearn.__version__),
        ],
        additional_pip_deps=pip_deps,
        additional_conda_channels=None
    ) 
Example #6
Source File: extra_trees.py    From mljar-supervised with MIT License 6 votes vote down vote up
def __init__(self, params):
        super(ExtraTreesAlgorithm, self).__init__(params)
        logger.debug("ExtraTreesAlgorithm.__init__")

        self.library_version = sklearn.__version__
        self.trees_in_step = additional.get("trees_in_step", 100)
        self.max_steps = additional.get("max_steps", 50)
        self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
        self.model = ExtraTreesClassifier(
            n_estimators=self.trees_in_step,
            criterion=params.get("criterion", "gini"),
            max_features=params.get("max_features", 0.6),
            min_samples_split=params.get("min_samples_split", 30),
            warm_start=True,
            n_jobs=-1,
            random_state=params.get("seed", 1),
        ) 
Example #7
Source File: random_forest.py    From mljar-supervised with MIT License 6 votes vote down vote up
def __init__(self, params):
        super(RandomForestAlgorithm, self).__init__(params)
        logger.debug("RandomForestAlgorithm.__init__")

        self.library_version = sklearn.__version__
        self.trees_in_step = additional.get("trees_in_step", 5)
        self.max_steps = additional.get("max_steps", 3)
        self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
        self.model = RandomForestClassifier(
            n_estimators=self.trees_in_step,
            criterion=params.get("criterion", "gini"),
            max_features=params.get("max_features", 0.8),
            min_samples_split=params.get("min_samples_split", 4),
            warm_start=True,
            n_jobs=-1,
            random_state=params.get("seed", 1),
        ) 
Example #8
Source File: random_forest.py    From mljar-supervised with MIT License 6 votes vote down vote up
def __init__(self, params):
        super(RandomForestRegressorAlgorithm, self).__init__(params)
        logger.debug("RandomForestRegressorAlgorithm.__init__")

        self.library_version = sklearn.__version__
        self.trees_in_step = regression_additional.get("trees_in_step", 5)
        self.max_steps = regression_additional.get("max_steps", 3)
        self.early_stopping_rounds = regression_additional.get(
            "early_stopping_rounds", 50
        )
        self.model = RandomForestRegressor(
            n_estimators=self.trees_in_step,
            criterion=params.get("criterion", "mse"),
            max_features=params.get("max_features", 0.8),
            min_samples_split=params.get("min_samples_split", 4),
            warm_start=True,
            n_jobs=-1,
            random_state=params.get("seed", 1),
        ) 
Example #9
Source File: RobustScaler.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, options):
        self.handle_options(options)

        out_params = convert_params(
            options.get('params', {}),
            bools=['with_centering', 'with_scaling'],
            strs=['quantile_range'], 
        )

        if StrictVersion(sklearn_version) < StrictVersion(quantile_range_required_version) and 'quantile_range' in out_params.keys():
            out_params.pop('quantile_range')
            msg = 'The quantile_range option is ignored in this version of scikit-learn ({}): version {} or higher required'
            msg = msg.format(sklearn_version, quantile_range_required_version)
            messages.warn(msg)

        if 'quantile_range' in out_params.keys():
            try:
                out_params['quantile_range'] = tuple(int(i) for i in out_params['quantile_range'].split('-'))
                assert len(out_params['quantile_range']) == 2
            except:
                raise RuntimeError('Syntax Error: quantile_range requires a range, e.g., quantile_range=25-75')

        self.estimator = _RobustScaler(**out_params) 
Example #10
Source File: configuration.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def set_configuration():
    # set python version
    config.ExternalDepFound('python', '.'.join([str(x)
                                                for x in sys.version_info]))
    version = mdp.__version__
    if mdp.__revision__:
        version += ', ' + mdp.__revision__
    config.ExternalDepFound('mdp', version)

    # parallel python dependency
    try:
        import pp
        # set pp secret if not there already
        # (workaround for debian patch to pp that disables pp's default password)
        pp_secret = os.getenv('MDP_PP_SECRET') or 'mdp-pp-support-password'
        # module 'user' has been deprecated since python 2.6 and deleted
        # completely as of python 3.0.
        # Basically pp can not work on python 3 at the moment.
        import user
        if not hasattr(user, 'pp_secret'):
            user.pp_secret = pp_secret
    except ImportError, exc:
        config.ExternalDepFailed('parallel_python', exc) 
Example #11
Source File: MLPClassifier.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def raise_import_error():
    msg = 'MLP Classifier is not available in this version of scikit-learn ({}): version {} or higher required'
    msg = msg.format(sklearn_version, required_version)
    raise ImportError(msg) 
Example #12
Source File: MLPClassifier.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def has_required_version():
    return StrictVersion(sklearn_version) >= StrictVersion(required_version) 
Example #13
Source File: driver_tests.py    From tpot with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_driver_5():
    """Assert that the tpot_driver() in TPOT driver outputs normal result with exported python file and verbosity = 0."""

    # Catch FutureWarning https://github.com/scikit-learn/scikit-learn/issues/11785
    if (np.__version__ >= LooseVersion("1.15.0") and
            sklearn.__version__ <= LooseVersion("0.20.0")):
        raise nose.SkipTest("Warning raised by scikit-learn")

    args_list = [
                'tests/tests.csv',
                '-is', ',',
                '-target', 'class',
                '-o', 'test_export.py',
                '-g', '1',
                '-p', '2',
                '-cv', '3',
                '-s', '42',
                '-config', 'TPOT light',
                '-v', '0'
                ]
    args = _get_arg_parser().parse_args(args_list)
    with captured_output() as (out, err):
        tpot_driver(args)
    ret_stdout = out.getvalue()

    assert ret_stdout == ""
    assert path.isfile("test_export.py")
    remove("test_export.py") # clean up exported file 
Example #14
Source File: _svm_0_23.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def _compute_gamma(*args):
    global no_older_than_0_20_3
    global no_older_than_0_22
    if no_older_than_0_20_3 is None:
        no_older_than_0_20_3 = (LooseVersion(sklearn_version) >= LooseVersion("0.20.3"))
    if no_older_than_0_22 is None:
        no_older_than_0_22 = (LooseVersion(sklearn_version) < LooseVersion("0.22"))
    return __compute_gamma__(*args, use_var=no_older_than_0_20_3, deprecation=no_older_than_0_22) 
Example #15
Source File: decision_forest.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def predict(self, X):
        if LooseVersion(sklearn_version) >= LooseVersion("0.22"):
            check_is_fitted(self)
        else:
            check_is_fitted(self, 'daal_model_')
        return self._daal_predict(X) 
Example #16
Source File: decision_forest.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def _more_tags(self):
        if LooseVersion(sklearn_version) >= LooseVersion("0.22"):
            return {'multioutput': False}
        else:
            return dict() 
Example #17
Source File: decision_forest.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def estimators_(self):
        if hasattr(self, '_cached_estimators_'):
            if self._cached_estimators_:
                return self._cached_estimators_
        if LooseVersion(sklearn_version) >= LooseVersion("0.22"):
            check_is_fitted(self)
        else:
            check_is_fitted(self, 'daal_model_')
        # convert model to estimators
        est = DecisionTreeRegressor(
            criterion=self.criterion,
            max_depth=self.max_depth,
            min_samples_split=self.min_samples_split,
            min_samples_leaf=self.min_samples_leaf,
            min_weight_fraction_leaf=self.min_weight_fraction_leaf,
            max_features=self.max_features,
            max_leaf_nodes=self.max_leaf_nodes,
            min_impurity_decrease=self.min_impurity_decrease,
            min_impurity_split=self.min_impurity_split,
            random_state=None)

        # we need to set est.tree_ field with Trees constructed from Intel(R) DAAL solution
        estimators_ = []
        for i in range(self.n_estimators):
            est_i = clone(est)
            est_i.n_features_ = self.n_features_
            est_i.n_outputs_ = self.n_outputs_

            tree_i_state_class = daal4py.getTreeState(self.daal_model_, i)
            tree_i_state_dict = {
                'max_depth' : tree_i_state_class.max_depth,
                'node_count' : tree_i_state_class.node_count,
                'nodes' : tree_i_state_class.node_ar,
                'values': tree_i_state_class.value_ar }

            est_i.tree_ = Tree(self.n_features_, np.array([1], dtype=np.intp), self.n_outputs_)
            est_i.tree_.__setstate__(tree_i_state_dict)
            estimators_.append(est_i)

        return estimators_ 
Example #18
Source File: decision_forest.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def _daal_predict(self, X):
        if LooseVersion(sklearn_version) >= LooseVersion("0.22"):
            check_is_fitted(self)
        else:
            check_is_fitted(self, 'daal_model_')
        X = self._validate_X_predict(X)

        dfr_alg = daal4py.decision_forest_regression_prediction(fptype='float')
        dfr_predictionResult = dfr_alg.compute(X, self.daal_model_)

        pred = dfr_predictionResult.prediction

        return pred.ravel() 
Example #19
Source File: _svm_0_22.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def _compute_gamma(*args):
    global no_older_than_0_20_3
    global no_older_than_0_22
    if no_older_than_0_20_3 is None:
        no_older_than_0_20_3 = (LooseVersion(sklearn_version) >= LooseVersion("0.20.3"))
    if no_older_than_0_22 is None:
        no_older_than_0_22 = (LooseVersion(sklearn_version) < LooseVersion("0.22"))
    return __compute_gamma__(*args, use_var=no_older_than_0_20_3, deprecation=no_older_than_0_22) 
Example #20
Source File: fixes.py    From fairlearn with MIT License 5 votes vote down vote up
def get_sklearn_expected_1d_message():
    # Handle change of message for sklearn
    if sklearn.__version__ < "0.23.0":
        expected_message = "bad input shape"
    else:
        expected_message = "y should be a 1d array"
    return expected_message 
Example #21
Source File: _svm_0_21.py    From daal4py with Apache License 2.0 5 votes vote down vote up
def _compute_gamma(*args):
    global no_older_than_0_20_3
    global no_older_than_0_22
    if no_older_than_0_20_3 is None:
        no_older_than_0_20_3 = (LooseVersion(sklearn_version) >= LooseVersion("0.20.3"))
    if no_older_than_0_22 is None:
        no_older_than_0_22 = (LooseVersion(sklearn_version) < LooseVersion("0.22"))
    return __compute_gamma__(*args, use_var=no_older_than_0_20_3, deprecation=no_older_than_0_22) 
Example #22
Source File: sphinx_skl2onnx_extension.py    From sklearn-onnx with MIT License 5 votes vote down vote up
def run(self):
        from sklearn import __version__ as skver
        found = missing_ops()
        nbconverters = 0
        supported = set(build_sklearn_operator_name_map())
        rows = [".. list-table::", "    :header-rows: 1", "    :widths: 10 7 4",
                "", "    * - Name", "      - Package", "      - Supported"]
        for name, sub, cl in found:
            rows.append("    * - " + name)
            rows.append("      - " + sub)
            if cl in supported:
                rows.append("      - Yes")
                nbconverters += 1
            else:
                rows.append("      -")
            
        rows.append("")
        rows.append("scikit-learn's version is **{0}**.".format(skver))
        rows.append("{0}/{1} models are covered.".format(nbconverters, len(found)))

        node = nodes.container()
        st = StringList(rows)
        nested_parse_with_titles(self.state, st, node)
        main = nodes.container()
        main += node
        return [main] 
Example #23
Source File: test_metrics.py    From python-dlpy with Apache License 2.0 5 votes vote down vote up
def test_average_precision_score(self):

        try:
            from sklearn.metrics import average_precision_score as skaps
        except:
            unittest.TestCase.skipTest(self, "sklearn is not found in the libraries")

        try:
            from distutils.version import StrictVersion
        except:
            unittest.TestCase.skipTest(self, "StrictVersion issue")

        import sklearn
        if StrictVersion(sklearn.__version__) < StrictVersion('0.20.3'):
            unittest.TestCase.skipTest(self, "There is an API change in sklearn, "
                                             "this test is skipped with old versions of sklearn")

        skaps_score1 = skaps(self.local_class3.target, self.local_class3.p_1, pos_label=1)
        dlpyaps_score1 = average_precision_score('target', 'p_1', pos_label=1, castable=self.class_table3,
                                                 cutstep=0.0001)
        dlpyaps_score1_inter = average_precision_score(self.class_table3.target,self.class_table3.p_1,
                                                       pos_label=1, interpolate=True)
        self.assertAlmostEqual(skaps_score1, dlpyaps_score1, places=4)

        skaps_score2 = skaps(self.local_class3.target, self.local_class4.p_1, pos_label=1)
        dlpyaps_score2 = average_precision_score(self.class_table3.target,self.class_table4.p_1, pos_label=1,
                                                 cutstep=0.0001, id_vars=['id1', 'id2'])

        self.assertAlmostEqual(skaps_score2, dlpyaps_score2, places=4) 
Example #24
Source File: ABuFixes.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _parse_version(version_string):
    """
    根据库中的__version__字段,转换为tuple,eg. '1.11.3'->(1, 11, 3)
    :param version_string: __version__字符串对象
    :return: tuple 对象
    """
    version = []
    for x in version_string.split('.'):
        try:
            version.append(int(x))
        except ValueError:
            version.append(x)
    return tuple(version) 
Example #25
Source File: matplot_helper.py    From CVPR_paper_search_tool with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show_lib_versions():
	print('Python Interpreter version:%s' % sys.version[:3])
	print('numpy version', np.__version__)
	print('sklearn version', sklearn.__version__) 
Example #26
Source File: TimeSeriesModel.py    From pyaf with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getVersions(self):
        
        import os, platform, pyaf
        lVersionDict = {};
        lVersionDict["PyAF_version"] = pyaf.__version__;
        lVersionDict["system_platform"] = platform.platform();
        lVersionDict["system_uname"] = platform.uname();
        lVersionDict["system_processor"] = platform.processor();
        lVersionDict["python_implementation"] = platform.python_implementation();
        lVersionDict["python_version"] = platform.python_version();

        import sklearn
        lVersionDict["sklearn_version"] = sklearn.__version__;

        import pandas as pd
        lVersionDict["pandas_version"] = pd.__version__;
    
        import numpy as np
        lVersionDict["numpy_version"] = np.__version__;
    
        import scipy as sc
        lVersionDict["scipy_version"] = sc.__version__;

        import matplotlib
        lVersionDict["matplotlib_version"] = matplotlib.__version__

        import pydot
        lVersionDict["pydot_version"] = pydot.__version__

        import sqlalchemy
        lVersionDict["sqlalchemy_version"] = sqlalchemy.__version__

        # print([(k, lVersionDict[k]) for k in sorted(lVersionDict)]);
        return lVersionDict; 
Example #27
Source File: display_version_info.py    From pyaf with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getVersions():
        
    import os, platform, pyaf
    lVersionDict = {};
    lVersionDict["PyAF_version"] = pyaf.__version__;
    lVersionDict["system_platform"] = platform.platform();
    lVersionDict["system_uname"] = platform.uname();
    lVersionDict["system_processor"] = platform.processor();
    lVersionDict["python_implementation"] = platform.python_implementation();
    lVersionDict["python_version"] = platform.python_version();
    
    import sklearn
    lVersionDict["sklearn_version"] = sklearn.__version__;
    
    import pandas as pd
    lVersionDict["pandas_version"] = pd.__version__;
    
    import numpy as np
    lVersionDict["numpy_version"] = np.__version__;
    
    import scipy as sc
    lVersionDict["scipy_version"] = sc.__version__;
    
    import matplotlib
    lVersionDict["matplotlib_version"] = matplotlib.__version__

    import pydot
    lVersionDict["pydot_version"] = pydot.__version__

    import sqlalchemy
    lVersionDict["sqlalchemy_version"] = sqlalchemy.__version__
    
    print([(k, lVersionDict[k]) for k in sorted(lVersionDict)]);
    return lVersionDict; 
Example #28
Source File: validation.py    From sk-dist with Apache License 2.0 5 votes vote down vote up
def _check_is_fitted(estimator, attributes=None):
    from sklearn import __version__
    if __version__ < '0.22':
        return check_is_fitted(estimator, attributes)
    else:
        return check_is_fitted(estimator) 
Example #29
Source File: test_base.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_pickle_version_warning_is_issued_upon_different_version():
    iris = datasets.load_iris()
    tree = TreeBadVersion().fit(iris.data, iris.target)
    tree_pickle_other = pickle.dumps(tree)
    message = pickle_error_message.format(estimator="TreeBadVersion",
                                          old_version="something",
                                          current_version=sklearn.__version__)
    assert_warns_message(UserWarning, message, pickle.loads, tree_pickle_other) 
Example #30
Source File: test_base.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_pickle_version_warning_is_issued_when_no_version_info_in_pickle():
    iris = datasets.load_iris()
    # TreeNoVersion has no getstate, like pre-0.18
    tree = TreeNoVersion().fit(iris.data, iris.target)

    tree_pickle_noversion = pickle.dumps(tree)
    assert_false(b"version" in tree_pickle_noversion)
    message = pickle_error_message.format(estimator="TreeNoVersion",
                                          old_version="pre-0.18",
                                          current_version=sklearn.__version__)
    # check we got the warning about using pre-0.18 pickle
    assert_warns_message(UserWarning, message, pickle.loads,
                         tree_pickle_noversion)