MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

MACEst (Model Agnostic Confidence Estimator)

What is MACEst?

MACEst is a confidence estimator that can be used alongside any model (regression or classification) which uses previously seen data (i.e. any supervised learning model) to produce a point prediction.

In the regression case, MACEst produces a confidence interval about the point prediction, e.g. "the point prediction is 10 and I am 90% confident that the prediction lies between 8 and 12."

In Classification MACEst produces a confidence score for the point prediction. e.g. the point prediction is class 0 and I am 90% sure that the prediction is correct.

MACEst produces well-calibrated confidence estimates, i.e. 90% confidence means that you will on average be correct 90% of the time. It is also aware of the model limitations i.e. when a model is being asked to predict a point which it does not have the necessary knowledge (data) to predict confidently. In these cases MACEst is able to incorporate the (epistemic) uncertainty due to this and return a very low confidence prediction (in regression this means a large prediction interval).

Why use MACEst ?

Machine learning has become an integral part of many of the tools that are used every day. There has been a huge amount of progress on improving the global accuracy of machine learning models but calculating how likely a single prediction is to be correct has seen considerably less progress.

Most algorithms will still produce a prediction, even if this is in a part of the feature space the algorithm has no information about. This could be because the feature vector is unlike anything seen during training, or because the feature vector falls in a part of the feature space where there is a large amount of uncertainty such as if the border between two classes overlaps. In cases like this the prediction may well be meaningless. In most models, it is impossible to distinguish this sort of meaningless prediction from a sensible prediction. MACEst addresses this situation by providing an additional confidence estimate.

In some areas such as Finance, Infrastructure, or Healthcare, making a single bad prediction can have major consequences. It is important in these situations that a model is able to understand how likely any prediction it makes is to be correct before acting upon it. It is often even more important in these situations that any model knows what it doesn't know so that it will not blindly make bad predictions.

Summary of the Methodology

TL;DR

MACEst produces confidence estimates for a given point x by considering two factors:

  1. How accurate is the model when predicting previously seen points that are similar to x? Less confident if the model is less accurate in the region close to x.
  2. How similar is x to the points that we have seen previously? Less confident if x is not similar to the data used to train the model.

Longer Explanation

MACEst seeks to provide reliable confidence estimates for both regression and classification. It draws from ideas present in trust scores, conformal learning, Gaussian processes, and Bayesian modelling.

The general idea is that confidence is a local quantity. Even when the model is accurate globally, there are likely still some predictions about which it should not be very confident. Similarly, if the model is not accurate globally, there may still be some predictions for which the model can be very confident about.

To model this local confidence for a given prediction on a point x, we define the local neighbourhood by finding the k nearest neighbours to x. We then attempt to directly model the two causes of uncertainty, these are:

  1. Aleatoric Uncertainty: Even with lots of (possibly infinite) data there will be some variance/noise in the predictions. Our local approximation to this will be to define a local accuracy estimate. i.e. for the k nearest neighbours how accurate were the predictions?
  2. Epistemic Uncertainty: The model can only know relationships learnt from the training data. If the model has not seen any data point similar to x then it does not have as much knowledge about points like x, therefore the confidence estimate should be lower. MACEst estimates this by calculating how similar x is to the k nearest (most similar) points that it has previously seen.

We define a simple parametric function of these two quantities and calibrate this function so that our confidence estimates approximate the empirical accuracy, i.e. 90% confident -> 90% correct on average. By directly modelling these two effects, MACEst estimates are able to encapsulate the local variance accurately whilst also being aware of when the model is being asked to predict a point that is very different to what it has been trained on. This will make it robust to problems such as overconfident extrapolations and out of sample predictions.

Example

If a model has been trained to classify images of cats and dogs, and we want to predict an image of a poodle, we find the k most poodle-like cats and the k most poodle-like dogs. We then calculate how accurate the model was on these sets of images, and how similar the poodle is to each of these k cats and k dogs. We combine these two to produce a confidence estimate for each class.

As the poodle-like cats will likely be strange cats, they will be harder to classify and the accuracy will be lower for these than the poodle-like dogs this combined with the fact that image will be considerably more similar to poodle-like dogs the confidence of the dog prediction will be high.

If we now try to classify an image of a horse, we find that the new image is very dissimilar to both cats and dogs, so the similarity term dominates and the model will return an approximately uniform distribution, this can be interpreted as MACEst saying "I don't know what this is because I've never seen an image of a horse!".

Getting Started

We recommend using Python 3.10 for MACEst.

Create a virtual environment and source into it:

python3.10 -m venv venv
source venv/bin/activate

Install dependencies and MACEst:

pip install -r requirements.txt
pip install -r requirements_notebooks.txt
pip install macest

Or add macest to your project's requirements.txt file as a dependency.

Software Prerequisites

To import and use MACEst we recommend Python version >= 3.10.*.

Basic Usage

Below shows examples of using MACEst for classification and regression. For more examples, and advanced usage, please see the example notebooks.

Classification

To use MACEst for a classification task, the following example can be used:

importnumpyasnpfrommacest.classificationimportmodelsascl_modfromsklearn.ensembleimportRandomForestClassifierfromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitX,y=datasets.make_circles(n_samples=2*10**4, noise=0.4, factor=0.001)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train,
y_conf_train,
test_size=0.5,
random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=0)
point_pred_model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
point_pred_model.fit(X_pp_train,
y_pp_train)
macest_model=cl_mod.ModelWithConfidence(point_pred_model,
X_conf_train,
y_conf_train)
macest_model.fit(X_cal, y_cal)
conf_preds=macest_model.predict_confidence_of_point_prediction(X_test)

Regression

To use MACEst for a regression task, the following example can be used:

importnumpyasnpfrommacest.regressionimportmodelsasreg_modfromsklearn.linear_modelimportLinearRegressionfromsklearn.model_selectionimporttrain_test_splitX=np.linspace(0,1,10**3)
y=np.zeros(10**3)
y=2*X*np.sin(2*X)**2+np.random.normal(0 , 1 , len(X))
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X,
y,
test_size=0.66,
random_state=0)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal,
y_cal,
test_size=0.5,
random_state=1)
point_pred_model=LinearRegression()
point_pred_model.fit(X_pp_train[:,None], y_pp_train)
preds=point_pred_model.predict(X_conf_train[:,None])
test_error=abs(preds-y_conf_train)
y_conf_train_var=np.var(train_error)
macest_model=reg_mod.ModelWithPredictionInterval(point_pred_model,
X_conf_train[:,None],
test_error)
macest_model.fit(X_cal[:,None], y_cal)
conf_preds=confidence_model.predict_interval(X_test, conf_level=90)

MACEst with sparse data (see notebooks for more details)

importscipyfromscipy.sparseimportcsr_matrixfromscipy.sparseimportrandomassp_randfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierfrommacest.classificationimportmodelsasclmodimportnmslibn_rows=10**3n_cols=5*10**3X=csr_matrix(sp_rand(n_rows, n_cols))
y=np.random.randint(0, 2, n_rows)
X_pp_train, X_conf_train, y_pp_train, y_conf_train=train_test_split(X, y, test_size=0.66, random_state=10)
X_conf_train, X_cal, y_conf_train, y_cal=train_test_split(X_conf_train, y_conf_train,
test_size=0.5, random_state=0)
X_cal, X_test, y_cal, y_test, =train_test_split(X_cal, y_cal, test_size=0.5, random_state=0)
model=RandomForestClassifier(random_state=0,
n_estimators=800,
n_jobs=-1)
model.fit(csr_matrix(X_pp_train), y_pp_train)
param_bounds=clmod.SearchBounds(alpha_bounds=(0, 500), k_bounds=(5, 15))
neighbour_search_params=clmod.HnswGraphArgs(query_args=dict(ef=1100),
init_args=dict(method="hnsw",
space="cosinesimil_sparse",
data_type=nmslib.DataType.SPARSE_VECTOR))
macest_model=clmod.ModelWithConfidence(model,
X_conf_train,
y_conf_train,
search_method_args=neighbour_search_params)
macest_model.fit(X_cal, y_cal)
macest_point_prediction_conf=macest_model.predict_confidence_of_point_prediction(X_test)

Contributing

See the CONTRIBUTING.md file for information about contributing to MACEst.

Related Publications

For more information about the underlying methodology behind MACEst, then please refer to our accompanying research paper that has been shared on arXiv:

Security

Please consult the security guide for our responsible security vulnerability disclosure process

License

Copyright (c) 2021, 2023 Oracle and/or its affiliates. All rights reserved.

This library is licensed under Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl

See LICENSE.txt for more details.

About

Model Agnostic Confidence Estimator (MACEST) - A Python library for calibrating Machine Learning models' confidence scores

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

100 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages