SafeDecisionTree

An example Python Notebook is available Here

Privacy protected Decision Tree classifier.

class sacroml.safemodel.classifiers.safedecisiontreeclassifier.SafeDecisionTreeClassifier(**kwargs: dict)[source]

Privacy protected Decision Tree classifier.

Attributes:
feature_importances_

Return the feature importances.

Methods

additional_checks(curr_separate, saved_separate)

Decision Tree-specific checks.

apply(X[, check_input])

Return the index of the leaf that each sample is predicted as.

cost_complexity_pruning_path(X, y[, ...])

Compute the pruning path during Minimal Cost-Complexity Pruning.

decision_path(X[, check_input])

Return the decision path in the tree.

examine_seperate_items(curr_vals, saved_vals)

Check model-specific items exist in both current and saved copies.

fit(x, y)

Fit model and store k-anonymity and model dict.

get_current_and_saved_models()

Copy self.__dict__ and split into dicts for current and saved versions.

get_depth()

Return the depth of the decision tree.

get_metadata_routing()

Get metadata routing of this object.

get_n_leaves()

Return the number of leaves of the decision tree.

get_params([deep])

Get a dictionary of parameter values restricted to those expected.

posthoc_check()

Check whether model has been interfered with since fit() was last run.

predict(X[, check_input])

Predict class or regression value for X.

predict_log_proba(X)

Predict class log-probabilities of the input samples X.

predict_proba(X[, check_input])

Predict class probabilities of the input samples X.

preliminary_check([verbose, apply_constraints])

Check whether current model parameters violate the safe rules.

request_release(path, ext[, target])

Save model and create a report for the TRE output checkers.

run_attack(target, attack_name[, output_dir])

Run a specified attack on the trained model and save report to file.

save([name])

Write model to file in appropriate format.

score(X, y[, sample_weight])

Return the mean accuracy on the given test data and labels.

set_fit_request(*[, x])

Request metadata passed to the fit method.

set_params(**params)

Set the parameters of this estimator.

set_predict_proba_request(*[, check_input])

Request metadata passed to the predict_proba method.

set_predict_request(*[, check_input])

Request metadata passed to the predict method.

set_score_request(*[, sample_weight])

Request metadata passed to the score method.

__init__(**kwargs: dict) None[source]

Create model and apply constraints to params.

additional_checks(curr_separate: dict, saved_separate: dict) tuple[str, str][source]

Decision Tree-specific checks.

apply(X, check_input=True)

Return the index of the leaf that each sample is predicted as.

Added in version 0.17.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.

check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.

Returns:
X_leavesarray-like of shape (n_samples,)

For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.

cost_complexity_pruning_path(X, y, sample_weight=None)

Compute the pruning path during Minimal Cost-Complexity Pruning.

See minimal_cost_complexity_pruning for details on the pruning process.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

The target values (class labels) as integers or strings.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.

Returns:
ccp_pathBunch

Dictionary-like object, with the following attributes.

ccp_alphasndarray

Effective alphas of subtree during pruning.

impuritiesndarray

Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.

decision_path(X, check_input=True)

Return the decision path in the tree.

Added in version 0.18.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.

check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.

Returns:
indicatorsparse matrix of shape (n_samples, n_nodes)

Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.

examine_seperate_items(curr_vals: dict, saved_vals: dict) tuple[str, bool]

Check model-specific items exist in both current and saved copies.

fit(x: ndarray, y: ndarray) None[source]

Fit model and store k-anonymity and model dict.

get_current_and_saved_models() tuple[dict, dict]

Copy self.__dict__ and split into dicts for current and saved versions.

get_depth()

Return the depth of the decision tree.

The depth of a tree is the maximum distance between the root and any leaf.

Returns:
self.tree_.max_depthint

The maximum depth of the tree.

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_n_leaves()

Return the number of leaves of the decision tree.

Returns:
self.tree_.n_leavesint

Number of leaves.

get_params(deep: bool = True) dict

Get a dictionary of parameter values restricted to those expected.

posthoc_check() tuple[str, bool]

Check whether model has been interfered with since fit() was last run.

predict(X, check_input=True)

Predict class or regression value for X.

For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.

check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.

Returns:
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

The predicted classes, or the predict values.

predict_log_proba(X)

Predict class log-probabilities of the input samples X.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.

Returns:
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1

The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.

predict_proba(X, check_input=True)

Predict class probabilities of the input samples X.

The predicted class probability is the fraction of samples of the same class in a leaf.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.

check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.

Returns:
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1

The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.

preliminary_check(verbose: bool = True, apply_constraints: bool = False) tuple[str, bool]

Check whether current model parameters violate the safe rules.

Optionally fixes violations.

Parameters:
verbosebool

A boolean value to determine increased output level.

apply_constraintsbool

A boolean to determine whether identified constraints are to be upheld and applied.

Returns:
msgstring

A message string.

disclosivebool

A boolean value indicating whether the model is potentially disclosive.

request_release(path: str, ext: str, target: Target | None = None) None

Save model and create a report for the TRE output checkers.

Parameters:
pathstring

Path to save the outputs.

extstr

File extension defining the model saved format, e.g., “pkl” or “sav”.

targetattacks.target.Target

Contains model and dataset information.

Notes

If target is not null, then worst case MIA and attribute inference attacks are called via run_attack.

run_attack(target: Target, attack_name: str, output_dir: str = 'outputs_safemodel') dict

Run a specified attack on the trained model and save report to file.

Parameters:
targetTarget

The target in the form of a Target object.

attack_namestr

Name of the attack to run.

output_dirstr

Name of the directory to store JSON and PDF reports.

Returns:
dict

Metadata results.

save(name: str = 'undefined') None

Write model to file in appropriate format.

Note this is overloaded in SafeKerasClassifer to deal with tensorflow specifics.

Parameters:
namestring

The name of the file to save.

Notes

Optimizer is deliberately excluded to prevent possible restart to training and thus possible back door into attacks.

score(X, y, sample_weight=None)

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean accuracy of self.predict(X) w.r.t. y.

set_fit_request(*, x: bool | None | str = '$UNCHANGED$') SafeDecisionTreeClassifier

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
xstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for x parameter in fit.

Returns:
selfobject

The updated object.

set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_predict_proba_request(*, check_input: bool | None | str = '$UNCHANGED$') SafeDecisionTreeClassifier

Request metadata passed to the predict_proba method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict_proba if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict_proba.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
check_inputstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for check_input parameter in predict_proba.

Returns:
selfobject

The updated object.

set_predict_request(*, check_input: bool | None | str = '$UNCHANGED$') SafeDecisionTreeClassifier

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
check_inputstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for check_input parameter in predict.

Returns:
selfobject

The updated object.

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') SafeDecisionTreeClassifier

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns:
selfobject

The updated object.

property feature_importances_

Return the feature importances.

The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.

Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance() as an alternative.

Returns:
feature_importances_ndarray of shape (n_features,)

Normalized total reduction of criteria by feature (Gini importance).

sacroml.safemodel.classifiers.safedecisiontreeclassifier.decision_tree_internal_trees_are_equal(tree1_tree: Any, tree2_tree: Any) tuple[bool, str][source]

Test for equality of the internal structures in a sklearn.tree._tree.

For example, the structure, feature and threshold in each internal node etc.

sacroml.safemodel.classifiers.safedecisiontreeclassifier.decision_trees_are_equal(tree1: DecisionTreeClassifier, tree2: DecisionTreeClassifier) tuple[bool, str][source]

Compare two estimators of type sklearn.tree.

sacroml.safemodel.classifiers.safedecisiontreeclassifier.get_tree_k_anonymity(thetree: DecisionTreeClassifier, X: Any) int[source]

Return the smallest number of data items in any leaf.