code
stringlengths
17
6.64M
def test_prepare_data_pick_regexp(): 'Test picking columns by regexp.' data = np.random.rand(5, 10) columns = ['_a_b_c1_', '_a_b_c2_', '_a_b2_c3_', '_a_b2_c4_', '_a_b3_c5_', '_a_b3_c6_', '_a3_b2_c7_', '_a2_b_c7_', '_a2_b_c8_', '_a2_b_c9_'] X = columns[:(- 1)] y = columns[(- 1)] df = pd.DataFra...
def test_check_consistency() -> None: 'Test check_consistency function.' y = pd.Series(np.random.randint(0, 2, size=10)) problem_type = 'classification' groups = None cv = 5 with warnings.catch_warnings(): warnings.simplefilter('error') check_consistency(y=y, cv=cv, groups=grou...
def test__check_x_types() -> None: 'Test checking for valid X types.' X = ['a', 'b', 'c'] X_types = {'categorical': ['a', 'b'], 'continuous': ['c']} with warnings.catch_warnings(): warnings.simplefilter('error') checked_X_types = _check_x_types(X=X, X_types=X_types) assert (X_t...
def test__check_x_types_regexp() -> None: 'Test checking for valid X types using regexp.' X = ['_a_b_c1_', '_a_b_c2_', '_a_b2_c3_', '_a_b2_c4_', '_a_b3_c5_', '_a_b3_c6_', '_a3_b2_c7_', '_a2_b_c7_', '_a2_b_c8_', '_a2_b_c9_'] X_types = {'categorical': ['.*a_b.*', '_a2.*'], 'continuous': ['_a3.*']} with ...
def list_transformers() -> List[str]: 'List all the available transformers.\n\n Returns\n -------\n list of str\n A list will all the available transformer names.\n\n ' return list(_available_transformers.keys())
def get_transformer(name: str, **params: Any) -> TransformerLike: 'Get a transformer.\n\n Parameters\n ----------\n name : str\n The transformer name.\n **params : dict\n Parameters to get transformer.\n\n Returns\n -------\n scikit-learn compatible transformer\n The tran...
def register_transformer(transformer_name, transformer_cls, overwrite=None): 'Register a transformer to julearn.\n\n This function allows you to add a transformer to julearn.\n Afterwards, it behaves like every other julearn transformer and can\n be referred to by name.\n\n Parameters\n ----------\...
def reset_transformer_register(): 'Reset the transformer register to its initial state.' global _available_transformers _available_transformers = deepcopy(_available_transformers_reset) return _available_transformers
class ChangeColumnTypes(JuTransformer): "Transformer to change the column types.\n\n Parameters\n ----------\n X_types : dict, optional\n A dictionary with the column types to set. The keys are the column\n types and the values are the columns to set the type to. If None, will\n set ...
class DropColumns(JuTransformer): "Drop columns of a DataFrame.\n\n Parameters\n ----------\n apply_to : ColumnTypesLike\n The feature types ('X_types') to drop.\n row_select_col_type : str or list of str or set of str or ColumnTypes\n The column types needed to select rows (default is N...
class FilterColumns(JuTransformer): "Filter columns of a DataFrame.\n\n Parameters\n ----------\n keep : ColumnTypesLike, optional\n Which feature types ('X_types') to keep. If not specified, 'keep'\n defaults to 'continuous'.\n row_select_col_type : str or list of str or set of str or C...
class SetColumnTypes(JuTransformer): 'Transformer to set the column types.\n\n Parameters\n ----------\n X_types : dict, optional\n A dictionary with the column types to set. The keys are the column\n types and the values are the columns to set the type to. If None, will\n set all th...
def test_DropColumns() -> None: 'Test DropColumns.' drop_columns = DropColumns(apply_to=['confound']) drop_columns.fit(X_with_types) X_trans = drop_columns.transform(X_with_types) support = drop_columns.get_support() non_confound = ['a__:type:__continuous', 'b__:type:__continuous', 'e__:type:_...
def test_FilterColumns() -> None: 'Test FilterColumns.' filter = FilterColumns(keep=['continuous']) kept_columns = ['a__:type:__continuous', 'b__:type:__continuous'] filter.set_output(transform='pandas').fit(X_with_types) X_expected = X_with_types.copy()[kept_columns] X_trans = filter.transfor...
def test_SetColumnTypes(X_iris: pd.DataFrame, X_types_iris: Optional[Dict]) -> None: 'Test SetColumnTypes.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset.\n X_types_iris : dict, optional\n The types to set in the iris dataset.\n ' _X_types_iris = ({} if (X_...
def test_SetColumnTypes_input_validation(X_iris: pd.DataFrame) -> None: 'Test SetColumnTypes input validation.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset.\n\n ' with pytest.raises(ValueError, match='Each value of X_types must be a list.'): SetColumnTypes(...
def test_SetColumnTypes_array(X_iris: pd.DataFrame, X_types_iris: Optional[Dict]) -> None: 'Test SetColumnTypes.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset.\n X_types_iris : dict, optional\n The types to set in the iris dataset.\n ' _X_types_iris = ({} ...
class JuColumnTransformer(JuTransformer): 'Column transformer that can be used in a julearn pipeline.\n\n This column transformer is a wrapper around the sklearn column transformer,\n so it can be used directly with julearn pipelines.\n\n Parameters\n ----------\n name : str\n Name of the tr...
def list_target_transformers() -> List[str]: 'List all the available target transformers.\n\n Returns\n -------\n out : list of str\n A list will all the available transformer names.\n ' return list(_available_target_transformers.keys())
def get_target_transformer(name: str, **params: Any) -> JuTargetTransformer: 'Get a target transformer by name.\n\n Parameters\n ----------\n name : str\n The target transformer name\n **params\n Parameters for the transformer.\n\n Returns\n -------\n JuTargetTransformer\n ...
def register_target_transformer(transformer_name: str, transformer_cls: Type[JuTargetTransformer], overwrite: Optional[bool]=None): 'Register a target transformer to julearn.\n\n Parameters\n ----------\n transformer_name : str\n Name by which the transformer will be referenced by\n transformer...
def reset_target_transformer_register() -> None: 'Reset the target transformer register to its initial state.' global _available_target_transformers _available_target_transformers = deepcopy(_available_target_transformers_reset)
class JuTargetTransformer(): 'Base class for target transformers.\n\n Unlike the scikit-learn transformer, this fits and transforms using both\n X and y. This is useful for pipelines that work on the target but require\n information from the input data, such as the TargetConfoundRemover or\n a target ...
def _wrapped_model_has(attr): 'Create a function to check if self.model_ has a given attribute.\n\n This function is usable by\n :func:`sklearn.utils.metaestimators.available_if`\n\n Parameters\n ----------\n attr : str\n The attribute to check for.\n\n Returns\n -------\n check : f...
class TransformedTargetWarning(RuntimeWarning): 'Warning used to notify the user that the target has been transformed.'
class JuTransformedTargetModel(JuBaseEstimator): 'Class that provides a model that supports transforming the target.\n\n This _model_ is a wrapper that will transform the target before fitting.\n\n Parameters\n ----------\n model : ModelLike\n The model to be wrapped. Can be a pipeline.\n tr...
def test_register_target_transformer() -> None: 'Test registering target transformers.' with pytest.raises(ValueError, match='\\(useless\\) is not available'): get_target_transformer('useless') first = list_target_transformers() class MyTransformer(JuTargetTransformer): pass regis...
def test_reset_target_transformer() -> None: 'Test resetting the target transformers registry.' with pytest.raises(ValueError, match='\\(useless\\) is not available'): get_target_transformer('useless') class MyTransformer(JuTargetTransformer): pass register_target_transformer('useless...
def test_JuTargetTransformer_abstractness() -> None: 'Test JuTargetTransformer is abstract base class.' with pytest.raises(NotImplementedError, match='fit'): JuTargetTransformer().fit('1', '2')
class Fish(BaseEstimator, TransformerMixin): 'A (flying) fish.\n\n Parameters\n ----------\n can_it_fly : bool\n Whether the fish can fly.\n\n ' def __init__(self, can_it_fly: bool): self.can_it_fly = can_it_fly def fit(self, X: DataLike, y: Optional[DataLike]=None) -> 'Fish':...
def test_register_reset() -> None: 'Test the register reset.' reset_transformer_register() with pytest.raises(ValueError, match='The specified transformer'): get_transformer('passthrough') register_transformer('passthrough', PassThroughTransformer) assert (get_transformer('passthrough').__...
def test_register_class_no_default_params(): 'Test the register with a class that has no default params.' reset_transformer_register() register_transformer('fish', Fish) get_transformer('fish', can_it_fly='dont_be_stupid')
def test_register_warnings_errors(): 'Test the register warning / error.' with pytest.warns(RuntimeWarning, match='Transformer name'): register_transformer('zscore', Fish) reset_transformer_register() with pytest.raises(ValueError, match='Transformer name'): register_transformer('zscor...
def test_CBPM_posneg_correlated_features(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with posneg correlated features.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' ...
def test_CBPM_pos_correlated_features(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with positive correlated features.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' ...
def test_CBPM_neg_correlated_features(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with positive correlated features.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' ...
def test_CBPM_warnings(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer warnings.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' X_pos = ['sepal_length', 'petal_lengt...
def test_CBPM_lower_sign_threshhold(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with lower significance threshold.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' ...
def test_CBPM_lower_sign_threshhold_no_sig(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with an even lower significance threshold.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset ta...
def test_CBPM_spearman(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer with spearman correlation.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features\n y_iris : pd.Series\n The iris dataset target\n ' X_pos = ['sepal_leng...
def test_CBPM_set_output_posneg(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer for setting posneg output.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features.\n y_iris : pd.Series\n The iris dataset target.\n\n ' X_pos =...
def test_CBPM_set_output_pos(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer for setting pos output.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features.\n y_iris : pd.Series\n The iris dataset target.\n\n ' X_pos = ['sep...
def test_CBPM_set_output_neg(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: 'Test the CBPM transformer for setting neg output.\n\n Parameters\n ----------\n X_iris : pd.DataFrame\n The iris dataset features.\n y_iris : pd.Series\n The iris dataset target.\n\n ' X_neg = ['sep...
@fixture def df_X_confounds() -> pd.DataFrame: 'Create a dataframe with confounds.\n\n Returns\n -------\n pd.DataFrame\n A dataframe with confounds.\n\n ' X = pd.DataFrame({'a__:type:__continuous': (np.arange(10) + np.random.rand(10)), 'b__:type:__continuous': (np.arange(10, 20) + np.rando...
@pytest.mark.parametrize('name, klass, params', [('zscore', StandardScaler, {}), ('scaler_robust', RobustScaler, {}), ('scaler_minmax', MinMaxScaler, {}), ('scaler_maxabs', MaxAbsScaler, {}), ('scaler_normalizer', Normalizer, {}), ('scaler_quantile', QuantileTransformer, {'n_quantiles': 10}), ('scaler_power', PowerTr...
def test_JuColumnTransformer_row_select(): 'Test row selection for JuColumnTransformer.' X = pd.DataFrame({'a__:type:__continuous': [0, 0, 1, 1], 'b__:type:__healthy': [1, 1, 0, 0]}) transformer_healthy = JuColumnTransformer(name='zscore', transformer=StandardScaler(), apply_to='continuous', row_select_co...
def _recurse_to_list(a): 'Recursively convert a to a list.' if isinstance(a, (list, tuple)): return [_recurse_to_list(i) for i in a] elif isinstance(a, np.ndarray): return a.tolist() else: return a
def _compute_cvmdsum(cv): 'Compute the sum of the CV generator.' params = dict(vars(cv).items()) params['class'] = cv.__class__.__name__ out = None if ('random_state' in params): if (params['random_state'] is None): if (params.get('shuffle', True) is True): out ...
def is_nonoverlapping_cv(cv) -> bool: _valid_instances = (KFold, GroupKFold, RepeatedKFold, RepeatedStratifiedKFold, StratifiedKFold, LeaveOneOut, LeaveOneGroupOut, StratifiedGroupKFold, ContinuousStratifiedGroupKFold, RepeatedContinuousStratifiedGroupKFold) return isinstance(cv, _valid_instances)
def check_scores_df(*scores: pd.DataFrame, same_cv: bool=False) -> pd.DataFrame: 'Check the output of `run_cross_validation`.\n\n Parameters\n ----------\n *scores : pd.DataFrame\n DataFrames containing the scores of the models. The DataFrames must\n be the output of `run_cross_validation`\...
def _get_git_head(path: Path) -> str: 'Aux function to read HEAD from git.\n\n Parameters\n ----------\n path : pathlib.Path\n The path to read git HEAD from.\n\n Returns\n -------\n str\n Empty string if timeout expired for subprocess command execution else\n git HEAD infor...
def get_versions() -> Dict: 'Import stuff and get versions if module.\n\n Returns\n -------\n module_versions : dict\n The module names and corresponding versions.\n\n ' module_versions = {} for (name, module) in sys.modules.items(): if ('.' in name): continue ...
def _safe_log(versions: Dict, name: str) -> None: 'Log with safety.\n\n Parameters\n ----------\n versions : dict\n The dictionary with keys as dependency names and values as the\n versions.\n name : str\n The dependency to look up in `versions`.\n\n ' if (name in versions)...
def log_versions() -> None: 'Log versions of the core libraries, for reproducibility purposes.' versions = get_versions() logger.info('===== Lib Versions =====') _safe_log(versions, 'numpy') _safe_log(versions, 'scipy') _safe_log(versions, 'sklearn') _safe_log(versions, 'pandas') _safe...
def configure_logging(level: Union[(int, str)]='WARNING', fname: Optional[Union[(str, Path)]]=None, overwrite: Optional[bool]=None, output_format=None) -> None: 'Configure the logging functionality.\n\n Parameters\n ----------\n level : int or {"DEBUG", "INFO", "WARNING", "ERROR"}\n The level of t...
def _close_handlers(logger: logging.Logger) -> None: 'Safely close relevant handlers for logger.\n\n Parameters\n ----------\n logger : logging.logger\n The logger to close handlers for.\n\n ' for handler in list(logger.handlers): if isinstance(handler, (logging.FileHandler, logging...
def raise_error(msg: str, klass: Type[Exception]=ValueError, exception: Optional[Exception]=None) -> NoReturn: 'Raise error, but first log it.\n\n Parameters\n ----------\n msg : str\n The message for the exception.\n klass : subclass of Exception, optional\n The subclass of Exception to...
def warn_with_log(msg: str, category: Optional[Type[Warning]]=RuntimeWarning) -> None: 'Warn, but first log it.\n\n Parameters\n ----------\n msg : str\n Warning message.\n category : subclass of Warning, optional\n The warning subclass (default RuntimeWarning).\n\n ' this_filters...
class WrapStdOut(logging.StreamHandler): 'Dynamically wrap to sys.stdout.\n\n This makes packages that monkey-patch sys.stdout (e.g.doctest,\n sphinx-gallery) work properly.\n\n ' def __getattr__(self, name: str) -> str: 'Implement attribute fetch.' if hasattr(sys.stdout, name): ...
def compare_models(clf1: EstimatorLike, clf2: EstimatorLike) -> None: 'Compare two models.\n\n Parameters\n ----------\n clf1 : EstimatorLike\n The first model.\n clf2 : EstimatorLike\n The second model.\n\n Raises\n ------\n AssertionError\n If the models are not equal.\...
def do_scoring_test(X: List[str], y: str, data: pd.DataFrame, api_params: Dict[(str, Any)], sklearn_model: EstimatorLike, scorers: List[str], groups: Optional[str]=None, X_types: Optional[Dict[(str, List[str])]]=None, cv: int=5, sk_y: Optional[np.ndarray]=None, decimal: int=5): 'Test scoring for a model, using th...
class PassThroughTransformer(TransformerMixin, BaseEstimator): 'A transformer doing nothing.' def __init__(self): pass def fit(self, X: DataLike, y: Optional[DataLike]=None) -> 'PassThroughTransformer': 'Fit the transformer.\n\n Parameters\n ----------\n X : DataLike...
class TargetPassThroughTransformer(PassThroughTransformer): 'A target transformer doing nothing.' def __init__(self): super().__init__() def transform(self, X: Optional[DataLike]=None, y: Optional[DataLike]=None) -> Optional[DataLike]: 'Transform the data.\n\n Parameters\n ...
def _get_coef_over_versions(clf: EstimatorLike) -> np.ndarray: 'Get the coefficients of a model, skipping warnings.\n\n Parameters\n ----------\n clf : EstimatorLike\n The model.\n\n Returns\n -------\n np.ndarray\n The coefficients.\n ' if isinstance(clf, (BernoulliNB, Comp...
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_log_file() -> None: 'Test logging to a file.' with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) configure_logging(fname=(tmpdir / 'test1.log')) logger.debug('Debug message') logger.info('Info message...
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_log() -> None: 'Simple log test.' configure_logging() logger.info('Testing')
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_lib_logging() -> None: 'Test logging versions.' import numpy as np import pandas import scipy import sklearn with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) configure_logging(fname=(tmpdir / 'test1...
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_log_file_warning_filter() -> None: 'Test filtering warning when logging to a file.' with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) configure_logging(fname=(tmpdir / 'test_filter.log')) warn_with_log('Warn...
def test_major_true() -> None: 'Test major version check.' assert check_version('3.5.1', (lambda x: (int(x) > 1)))
def test_major_false() -> None: 'Test major version check false.' assert (check_version('1.5.1', (lambda x: (int(x) > 1))) is False)
def test_minor_true() -> None: 'Test minor version check.' assert check_version('3.5.1', minor_check=(lambda x: (int(x) > 2)))
def test_minor_false() -> None: 'Test minor version check false.' assert (check_version('3.1.1', minor_check=(lambda x: (int(x) >= 2))) is False)
def test_patch_true() -> None: 'Test patch version check.' assert check_version('3.1.5', patch_check=(lambda x: (int(x) > 2)))
def test_patch_false() -> None: 'Test patch version check false.' assert (check_version('3.1.1', patch_check=(lambda x: (int(x) >= 2))) is False)
def test_multiple_true() -> None: 'Test multiple checks.' assert check_version('3.2.1', major_check=(lambda x: (int(x) == 3)), minor_check=(lambda x: (int(x) == 2)), patch_check=(lambda x: (int(x) >= 1)))
def test_multiple_false() -> None: 'Test multiple checks false.' assert (check_version('3.2.1', major_check=(lambda x: (int(x) == 3)), minor_check=(lambda x: (int(x) == 3)), patch_check=(lambda x: (int(x) >= 2))) is False)
def test_joblib_args_higer_1(monkeypatch: MonkeyPatch) -> None: 'Test joblib args for sklearn >= 1.0.' with monkeypatch.context() as m: m.setattr('sklearn.__version__', '2.2.11') kwargs = _joblib_parallel_args(prefer='threads') assert (kwargs['prefer'] == 'threads')
def test_joblib_args_lower_1(monkeypatch: MonkeyPatch) -> None: 'Test joblib args for sklearn < 1.0.' with monkeypatch.context() as m: import sklearn m.setattr('sklearn.__version__', '0.24.2') m.setattr(sklearn.utils.fixes, '_joblib_parallel_args', (lambda prefer: {'backend': 'threads'...
@runtime_checkable class EstimatorLikeFit1(Protocol): 'Class for estimator-like fit 1.' def fit(self, X: List[str], y: str, **kwargs: Any) -> 'EstimatorLikeFit1': 'Fit estimator.\n\n Parameters\n ----------\n X : list of str\n The features to use.\n y : str\n ...
@runtime_checkable class EstimatorLikeFit2(Protocol): 'Class for estimator-like fit 2.' def fit(self, X: List[str], y: str) -> 'EstimatorLikeFit2': 'Fit estimator.\n\n Parameters\n ----------\n X : list of str\n The features to use.\n y : str\n The ta...
@runtime_checkable class EstimatorLikeFity(Protocol): 'Class for estimator-like fit y.' def fit(self, y: str) -> 'EstimatorLikeFity': 'Fit estimator.\n\n Parameters\n ----------\n y : str\n The target to use.\n\n Returns\n -------\n EstimatorLikeFi...
@runtime_checkable class TransformerLike(EstimatorLikeFit1, Protocol): 'Class for transformer-like.' def fit(self, X: List[str], y: Optional[str]=None, **fit_params: Any) -> None: 'Fit transformer.\n\n Parameters\n ----------\n X : list of str\n The features to use.\n ...
@runtime_checkable class ModelLike(EstimatorLikeFit1, Protocol): 'Class for model-like.' classes_: np.ndarray def predict(self, X: pd.DataFrame) -> DataLike: 'Predict using the model.\n\n Parameters\n ----------\n X : pd.DataFrame\n The data to predict on.\n\n ...
@runtime_checkable class JuEstimatorLike(EstimatorLikeFit1, Protocol): 'Class for juestimator-like.' def get_needed_types(self) -> ColumnTypes: 'Get the column types needed by the estimator.\n\n Returns\n -------\n ColumnTypes\n The column types needed by the estimator...
@runtime_checkable class JuModelLike(ModelLike, Protocol): 'Class for jumodel-like.' def get_needed_types(self) -> ColumnTypes: 'Get the column types needed by the estimator.\n\n Returns\n -------\n ColumnTypes\n The column types needed by the estimator.\n\n ' ...
def check_version(version: str, major_check: Optional[Callable]=None, minor_check: Optional[Callable]=None, patch_check: Optional[Callable]=None): 'Check a version following major.minor.patch version numbers.\n\n The version is checked according to checks as functions major, minor and\n patch. This function...
def _joblib_parallel_args(**kwargs: Any) -> Any: 'Get joblib parallel args depending on scikit-learn version.\n\n Parameters\n ----------\n **kwargs : dict\n keyword arguments to pass to joblib.Parallel\n ' sklearn_version = sklearn.__version__ higher_than_11 = check_version(sklearn_ver...
class _JulearnScoresViewer(param.Parameterized): 'A class to visualize the scores for model comparison.\n\n Parameters\n ----------\n *scores : pd.DataFrame\n DataFrames containing the scores of the models. The DataFrames must\n be the output of `run_cross_validation`\n width : int\n ...
def plot_scores(*scores: pd.DataFrame, width: int=800, height: int=600, ci: float=0.95) -> pn.layout.Panel: 'Plot the scores of the models on a panel dashboard.\n\n Parameters\n ----------\n *scores : pd.DataFrame\n DataFrames containing the scores of the models. The DataFrames must\n be th...
class Normalize(nn.Module): def __init__(self, mean, std): super(Normalize, self).__init__() self.register_buffer('mean', torch.Tensor(mean)) self.register_buffer('std', torch.Tensor(std)) def forward(self, x): mean = self.mean.reshape(1, 3, 1, 1) std = self.std.resha...
def add_data_normalization(model, mean, std): norm_layer = Normalize(mean=mean, std=std) model_ = torch.nn.Sequential(norm_layer, model) return model_
def apply_attack_on_dataset(model, dataloader, attack, epsilons, device, verbose=True): robust_accuracy = [] c_a = [] for (images, labels) in dataloader: (images, labels) = (images.to(device), labels.to(device)) outputs = model(images) (_, pre) = torch.max(outputs.data, 1) ...
def apply_attack_on_batch(model, images, labels, attack, device): (images, labels) = (images.to(device), labels.to(device)) outputs = model(images) (_, pre) = torch.max(outputs.data, 1) correct_predictions = (pre == labels) correct_predictions = correct_predictions.cpu().numpy() clean_accuracy...
def plot_accuracy(x, accuracy, methods, title, xlabel='x', ylabel='accuracy'): for i in range(len(methods)): plt.plot(x, accuracy[i], label=methods[i]) plt.legend() plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.show()
def imshow(img, title): npimg = img.numpy() fig = plt.figure(figsize=(15, 15)) plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.title(title) plt.show()
class Conv2dGrad(autograd.Function): @staticmethod def forward(context, input, weight, bias, stride, padding, dilation, groups): (context.stride, context.padding, context.dilation, context.groups) = (stride, padding, dilation, groups) context.save_for_backward(input, weight, bias) out...
class LinearGrad(autograd.Function): @staticmethod def forward(context, input, weight, bias=None): context.save_for_backward(input, weight, bias) output = torch.nn.functional.linear(input, weight, bias) return output @staticmethod def backward(context, grad_output): (...
class Conv2dGrad(autograd.Function): '\n Autograd Function that Does a backward pass using the weight_backward matrix of the layer\n ' @staticmethod def forward(context, input, weight, weight_backward, bias, bias_backward, stride, padding, dilation, groups): (context.stride, context.padding...
class LinearGrad(autograd.Function): '\n Autograd Function that Does a backward pass using the weight_backward matrix of the layer\n ' @staticmethod def forward(context, input, weight, weight_backward, bias=None, bias_backward=None): context.save_for_backward(input, weight, weight_backward,...
def select_loss_function(loss_function_config): if (loss_function_config['name'] == 'cross_entropy'): return torch.nn.CrossEntropyLoss()