SafeRandomForest

An example Python Notebook is available Here

Privacy protected Random Forest classifier.

class sacroml.safemodel.classifiers.saferandomforestclassifier.SafeRandomForestClassifier(**kwargs: dict)[source]

Privacy protected Random Forest classifier.

Attributes:
estimators_samples_

The subset of drawn samples for each base estimator.

feature_importances_

The impurity-based feature importances.

Methods

additional_checks(curr_separate, saved_separate)

Perform Random Forest specific checks.

apply(X)

Apply trees in the forest to X, return leaf indices.

decision_path(X)

Return the decision path in the forest.

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 model dict.

get_current_and_saved_models()

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

get_k_anonymity(x)

Calculate the k-anonymity of a random forest model.

get_metadata_routing()

Get metadata routing of this object.

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)

Predict class for X.

predict_log_proba(X)

Predict class log-probabilities for X.

predict_proba(X)

Predict class probabilities for 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_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]

Perform Random Forest specific checks.

NOTE: this is never called if the model has not been fitted.

apply(X)

Apply trees in the forest to X, return leaf indices.

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

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

Returns:
X_leavesndarray of shape (n_samples, n_estimators)

For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in.

decision_path(X)

Return the decision path in the forest.

Added in version 0.18.

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

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

Returns:
indicatorsparse matrix of shape (n_samples, n_nodes)

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

n_nodes_ptrndarray of shape (n_estimators + 1,)

The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator.

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 model dict.

get_current_and_saved_models() tuple[dict, dict]

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

get_k_anonymity(x: ndarray) int[source]

Calculate the k-anonymity of a random forest model.

The k-anonymity is the minimum of the anonymity for each record. That is defined as the size of the set of records which appear in the same leaf as the record in every 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_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)

Predict class for X.

The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees.

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

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

Returns:
yndarray of shape (n_samples,) or (n_samples, n_outputs)

The predicted classes.

predict_log_proba(X)

Predict class log-probabilities for X.

The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest.

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

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

Returns:
pndarray of shape (n_samples, n_classes), or a list of such arrays

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

predict_proba(X)

Predict class probabilities for X.

The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree 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, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.

Returns:
pndarray of shape (n_samples, n_classes), or a list of such arrays

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$') SafeRandomForestClassifier

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_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') SafeRandomForestClassifier

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 estimators_samples_

The subset of drawn samples for each base estimator.

Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples.

Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.

examine_seperately_items: list[str]
property feature_importances_

The impurity-based feature importances.

The higher, the more important the feature. 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,)

The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros.

filename: str
ignore_items: list[str]
model_load_file: str
model_save_file: str
model_type: str
researcher: str
timestamp: str