def get_scipy_status():
"""
Returns a dictionary containing a boolean specifying whether SciPy
is up-to-date, along with the version string (empty string if
not installed).
"""
scipy_status = {}
try:
import scipy
scipy_version = scipy.__version__
scipy_status['up_to_date'] = parse_version(
scipy_version) >= parse_version(scipy_min_version)
scipy_status['version'] = scipy_version
except ImportError:
scipy_status['up_to_date'] = False
scipy_status['version'] = ""
return scipy_status
python类__version__()的实例源码
def get_numpy_status():
"""
Returns a dictionary containing a boolean specifying whether NumPy
is up-to-date, along with the version string (empty string if
not installed).
"""
numpy_status = {}
try:
import numpy
numpy_version = numpy.__version__
numpy_status['up_to_date'] = parse_version(
numpy_version) >= parse_version(numpy_min_version)
numpy_status['version'] = numpy_version
except ImportError:
numpy_status['up_to_date'] = False
numpy_status['version'] = ""
return numpy_status
def get_pandas_status():
try:
import pandas as pd
return _check_version(pd.__version__, pandas_min_version)
except ImportError:
traceback.print_exc()
return default_status
def get_sklearn_status():
try:
import sklearn as sk
return _check_version(sk.__version__, sklearn_min_version)
except ImportError:
traceback.print_exc()
return default_status
def get_numpy_status():
try:
import numpy as np
return _check_version(np.__version__, numpy_min_version)
except ImportError:
traceback.print_exc()
return default_status
def get_scipy_status():
try:
import scipy as sc
return _check_version(sc.__version__, scipy_min_version)
except ImportError:
traceback.print_exc()
return default_status
def get_h2o_status():
try:
import h2o
return _check_version(h2o.__version__, h2o_min_version)
except ImportError:
traceback.print_exc()
return default_status
def test_valid_estimator():
"""Test whether ovk.ONORMA is a valid sklearn estimator."""
from sklearn import __version__
# Adding patch revision number cause crash
if LooseVersion(__version__) >= LooseVersion('0.18'):
check_estimator(ovk.ONORMA)
else:
warn('sklearn\'s check_estimator seems to be broken in __version__ <='
' 0.17.x... skipping')
def test_valid_estimator():
"""Test whether ovk.OVKRidge is a valid sklearn estimator."""
from sklearn import __version__
# Adding patch revision number causes crash
if LooseVersion(__version__) >= LooseVersion('0.18'):
check_estimator(ovk.OVKRidge)
else:
warn('sklearn\'s check_estimator seems to be broken in __version__ <='
' 0.17.x... skipping')
def check_version(library, min_version):
"""Check minimum library version required
Parameters
----------
library : str
The library name to import. Must have a ``__version__`` property.
min_version : str
The minimum version string. Anything that matches
``'(\\d+ | [a-z]+ | \\.)'``
Returns
-------
ok : bool
True if the library exists with at least the specified version.
"""
ok = True
try:
library = __import__(library)
except ImportError:
ok = False
else:
this_version = LooseVersion(library.__version__)
if this_version < min_version:
ok = False
return ok
def _fit_multiclass(self, X, y, verbose=False):
"""Fit the calibrated model in multiclass setting
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,)
Target values.
Returns
-------
self : object
Returns an instance of self.
"""
class_list = np.unique(y)
num_classes = len(class_list)
y_mod = np.zeros(len(y))
for i in range(num_classes):
y_mod[y==class_list[i]]=i
y_mod = y_mod.astype(int)
if ((type(self.cv)==str) and (self.cv=='prefit')):
self.uncalibrated_classifier = self.base_estimator
y_pred = self.uncalibrated_classifier.predict_proba(X)
else:
y_pred = np.zeros((len(y_mod),num_classes))
if sklearn.__version__ < '0.18':
skf = StratifiedKFold(y_mod, n_folds=self.cv,shuffle=True)
else:
skf = StratifiedKFold(n_splits=self.cv, shuffle=True).split(X, y)
for idx, (train_idx, test_idx) in enumerate(skf):
if verbose:
print("training fold {} of {}".format(idx+1, self.cv))
X_train = np.array(X)[train_idx,:]
X_test = np.array(X)[test_idx,:]
y_train = np.array(y_mod)[train_idx]
# We could also copy the model first and then fit it
this_estimator = clone(self.base_estimator)
this_estimator.fit(X_train,y_train)
y_pred[test_idx,:] = this_estimator.predict_proba(X_test)
if verbose:
print("Training Full Model")
self.uncalibrated_classifier = clone(self.base_estimator)
self.uncalibrated_classifier.fit(X, y_mod)
# calibrating function
if verbose:
print("Determining Calibration Function")
if self.method=='logistic':
self.calib_func, self.cf_list = prob_calibration_function_multiclass(y_mod, self.pre_transform(y_pred), verbose=verbose, **self.calib_kwargs)
if self.method=='ridge':
self.calib_func, self.cf_list = prob_calibration_function_multiclass(y_mod, self.pre_transform(y_pred), verbose=verbose, method='ridge', **self.calib_kwargs)
# training full model
return self
def fit(self, X, y, verbose=False):
"""Fit the calibrated model
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,)
Target values.
Returns
-------
self : object
Returns an instance of self.
"""
class_list = np.unique(y)
num_classes = len(class_list)
y_mod = np.zeros(len(y))
for i in range(num_classes):
y_mod[np.where(y==class_list[i])]=i
y_mod = y_mod.astype(int)
if ((type(self.cv)==str) and (self.cv=='prefit')):
self.uncalibrated_classifier = self.base_estimator
y_pred = self.uncalibrated_classifier.predict_proba(X)[:,1]
else:
y_pred = np.zeros((len(y_mod),num_classes))
if sklearn.__version__ < '0.18':
skf = StratifiedKFold(y_mod, n_folds=self.cv,shuffle=True)
else:
skf = StratifiedKFold(n_splits=self.cv, shuffle=True).split(X, y)
for idx, (train_idx, test_idx) in enumerate(skf):
if verbose:
print("training fold {} of {}".format(idx+1, self.cv))
X_train = np.array(X)[train_idx,:]
X_test = np.array(X)[test_idx,:]
y_train = np.array(y_mod)[train_idx]
# We could also copy the model first and then fit it
this_estimator = clone(self.base_estimator)
this_estimator.fit(X_train,y_train)
y_pred[test_idx,:] = this_estimator.predict_proba(X_test)
if verbose:
print("Training Full Model")
self.uncalibrated_classifier = clone(self.base_estimator)
self.uncalibrated_classifier.fit(X, y_mod)
# calibrating function
if verbose:
print("Determining Calibration Function")
if self.method=='logistic':
self.calib_func = prob_calibration_function_multiclass(y_mod, y_pred, verbose=verbose, **self.calib_kwargs)
if self.method=='ridge':
self.calib_func = prob_calibration_function_multiclass(y_mod, y_pred, verbose=verbose, method='ridge', **self.calib_kwargs)
# training full model
return self
def test_dump():
Xs, y = load_svmlight_file(datafile)
Xd = Xs.toarray()
# slicing a csr_matrix can unsort its .indices, so test that we sort
# those correctly
Xsliced = Xs[np.arange(Xs.shape[0])]
for X in (Xs, Xd, Xsliced):
for zero_based in (True, False):
for dtype in [np.float32, np.float64, np.int32]:
f = BytesIO()
# we need to pass a comment to get the version info in;
# LibSVM doesn't grok comments so they're not put in by
# default anymore.
dump_svmlight_file(X.astype(dtype), y, f, comment="test",
zero_based=zero_based)
f.seek(0)
comment = f.readline()
try:
comment = str(comment, "utf-8")
except TypeError: # fails in Python 2.x
pass
assert_in("scikit-learn %s" % sklearn.__version__, comment)
comment = f.readline()
try:
comment = str(comment, "utf-8")
except TypeError: # fails in Python 2.x
pass
assert_in(["one", "zero"][zero_based] + "-based", comment)
X2, y2 = load_svmlight_file(f, dtype=dtype,
zero_based=zero_based)
assert_equal(X2.dtype, dtype)
assert_array_equal(X2.sorted_indices().indices, X2.indices)
if dtype == np.float32:
assert_array_almost_equal(
# allow a rounding error at the last decimal place
Xd.astype(dtype), X2.toarray(), 4)
else:
assert_array_almost_equal(
# allow a rounding error at the last decimal place
Xd.astype(dtype), X2.toarray(), 15)
assert_array_equal(y, y2)