Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 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

Repository files navigation

Tests

PyPI

Clearbox AI Wrapper

Clearbox AI Wrapper is a Python library to package and save a Machine Learning model built with common ML/DL frameworks. It is designed to wrap models trained on structured (tabular) data. It includes optional preprocessing and data preparation arguments which can be used to build ready-to-production pipelines.

Passing the original training set on which the model is trained as input_data parameter, a model signature will be generated. A signature is a description of the final pipeline's inputs and outputs. The signature is stored in JSON format in the MLmodel file, together with other model metadata.

Main Features

The wrapper was born as a fork from mlflow and it's based on its standard format. It adds the possibility to package, together with the fitted model, preprocessing and data preparation functions in order to create a production-ready pipeline able to receive new data, preprocess them and makes predictions. The resulting wrapped model/pipeline is saved as a zipped folder.

The library is designed to automatically detect the Python version, the model framework and its version adding this information to the requirements saved into the final folder. Additional dependencies (e.g. libraries used in preprocessing or data preparation) can also be added as a list parameter if necessary.

The resulting wrapped folder can be loaded via the Wrapper and the model will be ready to take input through the predict or predict_proba (if present) method.

IMPORTANT: Currently, it is necessary to load the wrapped model with the same Python version with which the model was saved.

No preprocessing

In the simplest case, the original dataset has already been preprocessed or it doesn't need any preprocessing. It contains only numerical values (ordinal features or one-hot encoded categorical features) and we can easily train a model on it. Then, we only need to save the model and it will be ready to receive new data to make predictions on it.

The following lines show how to wrap and save a simple Scikit-Learn model without preprocessing or data preparation:

importclearbox_wrapperascbwmodel=DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
cbw.save_model('wrapped_model_path', model, input_data=X_train)

Preprocessing

Typically, data are preprocessed before being fed into the model. It is almost always necessary to transform (e.g. scaling, binarizing,...) raw data values into a representation that is more suitable for the downstream model. Most kinds of ML models take only numeric data as input, so we must at least encode the non-numeric data, if any.

Preprocessing is usually written and performed separately, before building and training the model. We fit some transformers, transform the whole dataset(s) and train the model on the processed data. If the model goes into production, we need to ship the preprocessing as well. New raw data must be processed on the same way the training dataset was.

With Clearbox AI Wrapper it's possible to wrap and save the preprocessing along with the model so to have a pipeline Processing+Model ready to take raw data, pre-process them and make predictions.

All the preprocessing code must be wrapped in a single function so it can be passed as the preprocessing parameter to the save_model method. You can use your own custom code for the preprocessing, just remember to wrap all of it in a single function, save it along with the model and add any extra dependencies.

IMPORTANT: If the preprocessing includes any kind of fitting on the training dataset (e.g. Scikit Learn transformers), it must be performed outside the final preprocessing function to save. Fit the transformer(s) outside the function and put only the transform method inside it. Furthermore, if the entire preprocessing is performed with a single Scikit-Learn transformer, you can directly pass it (fitted) to the save_model method.

fromsklearn.preprocessingimportRobustScalerimportxgboostasxgbimportclearbox_wrapperascbwx, y=datasetx_preprocessor=RobustScaler()
x_preprocessed=x_preprocessor.fit_transform(x)
model=xgb.XGBClassifier(use_label_encoder=False)
fitted_model=model.fit(x_preprocessed, y)
cbw.save_model('wrapped_model_path',
fitted_model,
preprocessing=x_preprocessor,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2"])

Data Preparation (advanced usage)

For a complex task, a single-step preprocessing could be not enough. Raw data initially collected could be very noisy, contain useless columns or splitted into different dataframes/tables sources. A first data processing is usually performed even before considering any kind of model to feed the data in. The entire dataset is cleaned and the following additional processing and the model are built considering only the cleaned data. But this is not always the case. Sometimes, this situation still applies for data fed in real time to a model in production.

We believe that a two-step data processing is required to deal with this situation. We refer to the first additional step by the term Data Preparation. With Clearbox AI Wrapper it's possible to wrap a data preparation step as well, in order to save a final Data Preparation + Preprocessing + Model pipeline ready to takes input.

All the data preparation code must be wrapped in a single function so it can be passed as the data_preparation parameter to the save_model method. The same considerations wrote above for the preprocessing step still apply for data preparation.

importnumpyasnpfromsklearn.preprocessingimportMaxAbsScalerfromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialimportclearbox_wrapperascbwdefpreparation(x):
data_prepared=np.delete(x, 0, axis=1)
returndata_preparedx_preprocessor=RobustScaler()
x, y=datasetx_prepared=preparation(x)
x_preprocessed=x_preprocessor.fit_transform(x_prepared)
model=Sequential()
model.add(Dense(8, input_dim=x_preprocessed.shape[1], activation="relu"))
model.add(Dense(3, activation="softmax"))
model.compile(
optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(x_preprocessed, y)
cbw.save_model(
'wrapped_model_path',
model,
preprocessing=x_preprocessor,
data_preparation=preparation,
input_data=X_train,
additional_deps=["scikit-learn==0.23.2", "numpy==1.18.0"]
)

Data Preparation vs. Preprocessing

It is not always clear which are the differences between preprocessing and data preparation. It's not easy to understand where data preparation ends and preprocessing begins. There are no conditions that apply in any case, but in general you should build the data preparation step working only with the dataset, without considering the model your data will be fed into. Any kind of operation is allowed, but often preparing the raw data includes removing or normalizing some columns, replacing values, add a column based on other column values,... After this step, no matter what kind of transformation the data have been through, they should still be readable and understandable by a human user.

The preprocessing step, on the contrary, should be considered closely tied with the downstream ML model and adapted to its particular "needs". Typically processed data by this second step are only numeric and non necessarily understandable by a human.

Supported ML frameworks

  • Scikit-Learn
  • XGBoost
  • Keras
  • Pytorch

Installation

Install the latest relased version on the Python Package Index (PyPI) with

pip install clearbox-wrapper

Examples

The following Jupyter notebooks provide examples of simle and complex cases:

License

Apache License 2.0

About

An agnostic wrapper for the most common ML frameworks.

Resources

Stars

14 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages