Skip to main content

bridgescaler

Bridge your scikit-learn-style scaler parameters between Python sessions and users. Bridgescaler allows you to save the properties of a scikit-learn-style scaler object to a json file, and then repopulate a new scaler object with the same properties.

Dependencies

  • scikit-learn
  • numpy
  • pandas
  • xarray
  • pytdigest

Installation

For a stable version of bridgescaler, you can install from PyPI.

pip install bridgescaler

For the latest version of bridgescaler, install from github.

git clone https://github.com/NCAR/bridgescaler.git
cd bridgescaler
pip install .

Usage

bridgescaler supports all the common scikit-learn scaler classes:

  • StandardScaler
  • RobustScaler
  • MinMaxScaler
  • MaxAbsScaler
  • QuantileTransformer
  • PowerTransformer
  • SplineTransformer

First, create some synthetic data to transform.

import numpy as np
import pandas as pd

# specify distribution parameters for each variable
locs = np.array([0, 5, -2, 350.5], dtype=np.float32)
scales = np.array([1.0, 10, 0.1, 5000.0])
names = ["A", "B", "C", "D"]
num_examples = 205
x_data_dict = {}
for l in range(locs.shape[0]):
    # sample from random normal with different parameters
    x_data_dict[names[l]] = np.random.normal(loc=locs[l], scale=scales[l], size=num_examples)
x_data = pd.DataFrame(x_data_dict)

Now, let's fit and transform the data with StandardScaler.

from sklearn.preprocessing import StandardScaler
from bridgescaler import save_scaler, load_scaler

scaler = StandardScaler()
scaler.fit_transform(x_data)
filename = "x_standard_scaler.json"
# save to json file
save_scaler(scaler, filename)

# create new StandardScaler from json file information.
new_scaler = load_scaler(filename) # new_scaler is a StandardScaler object

Distributed Scaler

The distributed scalers allow you to calculate scaling parameters on different subsets of a dataset and then combine the scaling factors together to get representative scaling values for the full dataset. Distributed Standard Scalers, MinMax Scalers, and Quantile Transformers have been implemented and work with both tabular and muliti-dimensional patch data in numpy, pandas DataFrame, and xarray DataArray formats. By default, the scaler assumes your channel/variable dimension is the last dimension, but if channels_last=False is set in the __init__, transform, or inverse_transform methods, then the 2nd dimension is assumed to be the variable dimension. It is possible to fit data with one ordering and then transform it with a different one.

For large datasets, it may be expensive to redo the scalers if you want to use a subset or different ordering of variables. However, in bridgescaler, the Distributed Scalers all support arbitrary ordering and subsets of variables for transforms if the input data are in a Xarray DataArray or Pandas DataFrame with variable names that match the original data.

Example:

from bridgescaler.distributed import DStandardScaler
import numpy as np

x_1 = np.random.normal(0, 2.2, (20, 5, 4, 8))
x_2 = np.random.normal(1, 3.5, (25, 4, 8, 5))

dss_1 = DStandardScaler(channels_last=False)
dss_2 = DStandardScaler(channels_last=True)
dss_1.fit(x_1)
dss_2.fit(x_2)
dss_combined = np.sum([dss_1, dss_2])

dss_combined.transform(x_1, channels_last=False)

PyTorch Tensor Scalers

If PyTorch (>= 2.0) is installed, tensor versions of the distributed scalers are available in bridgescaler.distributed_tensor (DStandardScalerTensor, DMinMaxScalerTensor, DQuantileScalerTensor). They operate directly on torch.Tensor inputs and run on CPU or GPU, mirroring the numpy API (fit/transform/inverse_transform, summing to combine, and channels-last or channels-first layouts). Variable names are carried on a variable_names attribute of the tensor so subsets and reordering work as with pandas/xarray.

DQuantileScalerTensor supports two performance options:

  • compile=True wraps the vmapped per-variable kernel in torch.compile for a sizable speedup on CPU/CUDA (skipped on MPS).
  • fast_transform=True replaces the exact TDigest CDF/quantile evaluation in both transform and inverse_transform with a per-variable monotone-cubic (PCHIP) approximation fit to the fitted quantile curve. This trades a small, tail-concentrated approximation error (typically well below the TDigest's own error) for roughly a 3x transform speedup. n_knots (default 256) controls the number of interpolation knots. The knots are derived from the digest and rebuilt automatically when the scaler is re-fit or combined.
from bridgescaler.distributed_tensor import DQuantileScalerTensor
import torch

x = torch.rand(10000, 4)
scaler = DQuantileScalerTensor(distribution="normal", fast_transform=True)
x_transformed = scaler.fit_transform(x)
x_restored = scaler.inverse_transform(x_transformed)

Group Scaler

The group scalers use the same scaling parameters for a group of similar variables rather than scaling each column independently. This is useful for situations where variables are related, such as temperatures at different height levels.

Groups are specified as a list of column ids, which can be column names for pandas dataframes or column indices for numpy arrays.

For example:

from bridgescaler.group import GroupStandardScaler
import pandas as pd
import numpy as np
x_rand = np.random.random(size=(100, 5))
data = pd.DataFrame(data=x_rand, 
                    columns=["a", "b", "c", "d", "e"])
groups = [["a", "b"], ["c", "d"], "e"]
group_scaler = GroupStandardScaler()
x_transformed = group_scaler.fit_transform(data, groups=groups)

"a" and "b" are a single group and all values of both will be included when calculating the mean and standard deviation for that group.

Deep Scaler

The deep scalers are designed to scale 2 or 3-dimensional fields input into a deep learning model such as a convolutional neural network. The scalers assume that the last dimension is the channel/variable dimension and scales the values accordingly. The scalers can support 2D or 3D patches with no change in code structure. Support is provided for DeepStandardScaler and DeepQuantileTransformer.

Example:

from bridgescaler.deep import DeepStandardScaler
import numpy as np
np.random.seed(352680)
n_ex = 5000
n_channels = 4
dim = 32
means = np.array([1, 5, -4, 2.5], dtype=np.float32)
sds = np.array([10, 2, 43.4, 32.], dtype=np.float32)
x = np.zeros((n_ex, dim, dim, n_channels), dtype=np.float32)
for chan in range(n_channels):
    x[..., chan] = np.random.normal(means[chan], sds[chan], (n_ex, dim, dim))
dss = DeepStandardScaler()
dss.fit(x)
x_transformed = dss.transform(x)

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bridgescaler-0.8.6.tar.gz (4.0 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bridgescaler-0.8.6-py3-none-any.whl (44.2 kB view details)

Uploaded Python 3

File details

Details for the file bridgescaler-0.8.6.tar.gz.

File metadata

  • Download URL: bridgescaler-0.8.6.tar.gz
  • Upload date:
  • Size: 4.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for bridgescaler-0.8.6.tar.gz
Algorithm Hash digest
SHA256 52ad2e66213fd1d08f759b4a4edfa0d310c649dac17e5ee59d4f72eec6710d77
MD5 ed82dca66e180af76e66494f0f44f30a
BLAKE2b-256 23005aa6afb8ec65e29a5de869463e09a7edfbe07b5dcf1b51327633b2917c2d

See more details on using hashes here.

File details

Details for the file bridgescaler-0.8.6-py3-none-any.whl.

File metadata

  • Download URL: bridgescaler-0.8.6-py3-none-any.whl
  • Upload date:
  • Size: 44.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for bridgescaler-0.8.6-py3-none-any.whl
Algorithm Hash digest
SHA256 43acd07c7f3e732ecd0c4f876c9528f60949848af93190011758d253d55fe7ef
MD5 abc00e4cd66f18953ddda0c44262029f
BLAKE2b-256 855f80ad8c12dce2da93be6c1c900966c980ca3a961647d50dc54417d490a4a8

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.8.6 This release

2 files

0.8.5

2 files

0.8.4

2 files

0.8.3

2 files

0.8.2

2 files

0.8.1

2 files

0.8.0

2 files

0.7.1

2 files

0.7.0

2 files

0.6.0

2 files

0.5.1

2 files

0.5.0

2 files

0.4.2

2 files

0.4.1

2 files

0.4

2 files

0.3

2 files

0.2

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page