Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python machine learning libraries train models that make predictions from data. These libraries train the models behind forecasts, recommendations, fraud checks, and classification in apps.
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples
scikit-learn
scikit-learn is a machine learning module for Python built on NumPy and SciPy, which pip installs alongside it. Every model is an estimator with the same two methods. fit trains the estimator on rows of data, while predict returns its answers for new rows. Classification, regression, clustering, and preprocessing tools all share that interface. A Pipeline uses it to chain a scaler and a model into one estimator that cross-validation can score.
Downloads / mo
214.2M
Stars
68.1K
Last release
1.9.1
License
BSD-3-Clause
Strengths
Keeps preprocessing with prediction.Combine transformations and an estimator in a Pipeline.
Evaluates models across data splits.Use cross-validation tools to score models on unseen data.
Limitations
Saved models need matching versions.Load a saved model with the same scikit-learn version that trained it.
def fit(
self,
X,
y,
sample_weight=None,
X_validation=None,
y_validation=None,
sample_weight_validation=None,
log_to_file=None,
max_time=None,
):
rows_count = len(X) + (len(X_validation) if X_validation is not None else 0)
n_estimators = self.tree_count(rows_count)
# Validation labels do not select the forest size. Disable warm start # so fitting the same learner again cannot retain trees from old data. self.model.set_params(n_estimators=n_estimators, warm_start=False)
with warnings.catch_warnings():
warnings.simplefilter(action="ignore")
self.model.fit(X, np.ravel(y), sample_weight=sample_weight)
self.params["n_estimators"] = n_estimators
if log_to_file is not None:
train_score = self.log_metric(
y, self.predict_function(self.model, X), sample_weight=sample_weight
)
validation_score = np.nan
if X_validation is not None and y_validation is not None:
validation_score = self.log_metric(
y_validation,
self.predict_function(self.model, X_validation),
sample_weight=sample_weight_validation,
)
# Log the final forest only; there is no selected validation peak. df_result = pd.DataFrame({
"iteration": [n_estimators - 1],
"train": [train_score],
"validation": [validation_score],
})
if self.log_metric.is_negative():
df_result["train"] *= -1.0
df_result["validation"] *= -1.0
df_result.to_csv(log_to_file, index=False, header=False)
if self.params.get("ml_task") != REGRESSION:
self.classes_ = self.model.classes_
PyTorch
PyTorch pairs a tensor library with GPU support and an automatic differentiation engine, torch.autograd. The engine records operations as code runs and replays them backward to compute gradients. Neural network layers come from torch.nn, while DataLoader in torch.utils feeds batches during training. A model can change its structure from one input to the next, which the README contrasts with frameworks that fix a network before training. The install command differs for CUDA, ROCm, and CPU builds, so a selector on the PyTorch site generates it.
Downloads / mo
59.7M
Stars
105.4K
Last release
2.15.0
License
NOASSERTION
Strengths
Supports custom training loops.Combine neural-network modules and automatic differentiation in a custom training loop.
Runs tensor operations on GPUs.Move tensors to CUDA devices for GPU execution.
Limitations
Layers and loops only.Training loops, early stopping, and checkpointing are written by hand or added through a library such as Lightning.
def cos_sim(a: list | np.ndarray | Tensor, b: list | np.ndarray | Tensor) -> Tensor:
"""
Computes the cosine similarity between two tensors.
Args:
a (Union[list, np.ndarray, Tensor]): The first tensor.
b (Union[list, np.ndarray, Tensor]): The second tensor.
Returns:
Tensor: Matrix with res[i][j] = cos_sim(a[i], b[j])
"""
a = _convert_to_batch_tensor(a)
b = _convert_to_batch_tensor(b)
a_norm = normalize_embeddings(a)
b_norm = normalize_embeddings(b)
return torch.mm(a_norm, b_norm.transpose(0, 1)).to_dense()
XGBoost
XGBoost trains gradient-boosted decision trees on one machine or across Kubernetes, Hadoop, Dask, or Spark. XGBClassifier and XGBRegressor follow the scikit-learn fit and predict interface, so they work inside scikit-learn pipelines. Tree boosters learn which branch missing values take during training, so gaps in the data need no filling first. Like LightGBM, XGBoost builds trees from histograms of each feature when tree_method is set to hist.
Downloads / mo
32.7M
Stars
29.0K
Last release
3.4.1
License
Apache-2.0
Strengths
Learns routes for missing values.Tree boosters learn where missing values go during training.
Recodes categories during inference.Dataframe inputs retain category encodings for prediction and continued training.
Limitations
Categories need JSON or UBJSON.Save categorical models as JSON or UBJSON to retain category information.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import xgboost as xgb
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=94)
# Use "hist" for constructing the trees, with early stopping enabled.clf = xgb.XGBClassifier(tree_method="hist", early_stopping_rounds=2)
# Fit the model, test sets are used for early stopping.clf.fit(X_train, y_train, eval_set=[(X_test, y_test)])
def predict(self, X):
self.reload()
if self.model is None:
raise XgbAlgorithmException("Xgboost model is None")
dtrain = xgb.DMatrix(
X.values if isinstance(X, pd.DataFrame) else X, missing=np.nan
)
# xgboost > 2.0.0 version if hasattr(self.model, "best_iteration"):
a = self.model.predict(
dtrain, iteration_range=(0, self.model.best_iteration + 1)
)
else:
a = self.model.predict(dtrain)
return a
LightGBM
LightGBM is a gradient boosting framework, first released by Microsoft and now maintained at lightgbm-org. Before searching for splits, the library buckets each feature's values into histograms to lower memory use. Trees grow one leaf at a time, choosing the leaf with the largest drop in loss. On small datasets that growth can overfit, so the docs suggest capping max_depth. In Python, lgb.Dataset wraps the training arrays and labels, with categorical columns kept as integer codes instead of one-hot columns.
def fit(
self,
X,
y,
sample_weight=None,
X_validation=None,
y_validation=None,
sample_weight_validation=None,
log_to_file=None,
max_time=None,
):
lgb_train = lgb.Dataset(
X.values if isinstance(X, pd.DataFrame) else X,
y,
weight=sample_weight,
)
valid_sets = None
if self.early_stopping_rounds == 0:
self.model = lgb.train(
self.learner_params,
lgb_train,
num_boost_round=self.rounds,
init_model=self.model,
)
else:
valid_names = None
esr = None
if X_validation is not None and y_validation is not None:
valid_sets = [
lgb_train,
lgb.Dataset(
(
X_validation.values
if isinstance(X_validation, pd.DataFrame)
else X_validation
),
y_validation,
weight=sample_weight_validation,
),
]
valid_names = ["train", "validation"]
esr = self.early_stopping_rounds
evals_result = {}
# disable for now ... # boosting_rounds = self.get_boosting_rounds(lgb_train, valid_sets, esr, max_time) self.model = lgb.train(
self.learner_params,
lgb_train,
num_boost_round=self.rounds,
valid_sets=valid_sets,
valid_names=valid_names,
feval=self.custom_eval_metric,
callbacks=[
lgb.early_stopping(esr, verbose=False),
lgb.record_evaluation(evals_result),
],
)
del lgb_train
if valid_sets is not None:
del valid_sets[0]
del valid_sets
if log_to_file is not None:
metric_name = list(evals_result["train"].keys())[0]
result = pd.DataFrame(
{
"iteration": range(len(evals_result["train"][metric_name])),
"train": evals_result["train"][metric_name],
"validation": evals_result["validation"][metric_name],
}
)
result.to_csv(log_to_file, index=False, header=False)
if self.params["ml_task"] != REGRESSION:
self.classes_ = np.unique(y)
JAX
JAX runs NumPy-style array code on CPUs, GPUs, and TPUs and transforms Python functions. Three transformations do most of the work. jax.grad returns a function's gradient, jax.jit compiles a function with XLA, a compiler for accelerators, and jax.vmap maps a function over a batch dimension. Because the transformations compose, jax.jit(jax.grad(loss)) is a compiled gradient function. GPU and TPU builds install as extras of the jax package.
Downloads / mo
12.6M
Stars
36.6K
Last release
0.12.0.1
License
Apache-2.0
Strengths
Runs on GPUs and TPUs.The same code runs on CPU, GPU, and TPU backends.
Differentiates Python control flow.jax.grad takes gradients through loops, branches, recursion, and closures.
Limitations
Needs pure functions.Pass every input as an argument and return every result, or transformed functions can behave unexpectedly.
No neural-network layers.Add Flax, Equinox, or Keras to build and train networks.
TensorFlow is a machine learning platform first built by the Google Brain team, with stable Python and C++ APIs. pip install tensorflow includes CUDA support for NVIDIA GPUs. A smaller package, tensorflow-cpu, leaves GPU support out. Trained models export as a SavedModel for serving, and LiteRT runs them on Android. Models are usually built with Keras, which runs on TensorFlow as one of its backends.
Downloads / mo
12.4M
Stars
201.6K
Last release
2.21.0
License
Apache-2.0
Strengths
Uses available GPUs automatically.Compatible TensorFlow operations and Keras models run on an available GPU.
Exports models for deployment.Export a SavedModel for serving without the original model-building code.
Limitations
Windows GPUs need WSL.Use WSL2 for supported NVIDIA GPU training on Windows.
def ResNet34() -> Model:
"""
ResNet34 model
Returns:
model (Model)
"""
img_input = Input(shape=(112, 112, 3))
x = ZeroPadding2D(padding=1, name="conv1_pad")(img_input)
x = Conv2D(
64, 3, strides=1, use_bias=False, kernel_initializer="glorot_normal", name="conv1_conv"
)(x)
x = BatchNormalization(axis=3, epsilon=2e-5, momentum=0.9, name="conv1_bn")(x)
x = PReLU(shared_axes=[1, 2], name="conv1_prelu")(x)
x = stack_fn(x)
model = Model(img_input, x, name="ResNet34")
return model
Keras
Keras is a deep learning API that runs on JAX, TensorFlow, or PyTorch, and on OpenVINO for inference only. The backend comes from the KERAS_BACKEND environment variable or the keras.json config file. Models are built from layers, for example with keras.Sequential. Training goes through fit, which accepts tf.data datasets, PyTorch DataLoader objects, and NumPy arrays. Code written for tf.keras runs on Keras when models are saved in the .keras format.
Downloads / mo
12.0M
Stars
64.4K
Last release
3.15.1
License
Apache-2.0
Strengths
Exports to each framework.Use a Keras model as a PyTorch Module, a TensorFlow SavedModel, or a JAX function.
Trains from any data pipeline.fit() accepts tf.data datasets, PyTorch DataLoaders, NumPy arrays, and pandas dataframes.
Limitations
Set the backend first.Set KERAS_BACKEND before importing Keras. It can't change afterward.
Needs a backend installed.Install a backend such as JAX, PyTorch, or TensorFlow alongside Keras.
Windows through WSL.The README supports Linux and macOS and recommends the Windows Subsystem for Linux on Windows.
import os
os.environ["KERAS_BACKEND"] = "jax"
import keras
model = keras.Sequential()
model.add(keras.Input(shape=(16,)))
model.add(keras.layers.Dense(8))
def create_mlp(hidden_units, dropout_rate, activation, normalization_layer, name=None):
mlp_layers = []
for units in hidden_units:
mlp_layers.append(normalization_layer())
mlp_layers.append(layers.Dense(units, activation=activation))
mlp_layers.append(layers.Dropout(dropout_rate))
return keras.Sequential(mlp_layers, name=name)
CatBoost
CatBoost is Yandex's gradient boosting library for decision trees. Categorical columns go into training without one-hot encoding. The docs warn against encoding them first, because CatBoost builds numeric features from the categories and their combinations itself. Text and embedding columns are accepted too. CatBoostClassifier trains on a CPU or a GPU, with a Pool object containing the data, labels, and feature types.
Downloads / mo
6.9M
Stars
9.2K
Last release
1.2.10
License
Apache-2.0
Strengths
Handles mixed feature types.Use numeric, categorical, text, and embedding features together.
Limitations
GPU training is nondeterministic.Repeated GPU training does not guarantee identical model results.
ONNX export needs numeric features.Categorical, text, and embedding features cannot use ONNX-ML export.
def _assess_iterations(self, X, y, sample_weight, eval_set, max_time=None):
if max_time is None:
max_time = 3600
try:
model = copy.deepcopy(self.model)
model.set_params(iterations=self.warmup_iterations)
start_time = time.time()
model.fit(
X,
y,
sample_weight=sample_weight,
cat_features=self.cat_features,
init_model=None if self.model.tree_count_ is None else self.model,
eval_set=eval_set,
early_stopping_rounds=self.early_stopping_rounds,
verbose_eval=False,
)
elapsed_time = (time.time() - start_time) / float(self.warmup_iterations)
# print(max_time, elapsed_time, max_time / elapsed_time, np.round(time.time() - start_time, 2)) new_rounds = int(min(10000, max_time / elapsed_time))
new_rounds = max(new_rounds, 10)
return model, new_rounds
except Exception as e:
# print(str(e)) return None, 1000
FAQ
Use scikit-learn, with 214.2M downloads a month, for classical models, preprocessing, and evaluation. For gradient-boosted trees, use XGBoost, LightGBM, or CatBoost, and for neural networks, use PyTorch.
Use PyTorch for most new neural-network work. It has far more downloads, at 59.7M a month against 12.4M for TensorFlow, and a training loop is written by hand with its modules and autograd. Choose TensorFlow to deploy to mobile or the browser, because a SavedModel exports to TFLite and TensorFlow.js.
Neither wins everywhere. Both train gradient-boosted trees, run on GPUs, handle missing values, and support early stopping. LightGBM's histogram-based learning speeds up training and reduces memory use, but its leaf-wise trees can overfit small datasets unless max_depth is set.
Use PyTorch for neural-network layers and training in one library. JAX compiles NumPy-style code with XLA and composes grad, jit, and vmap, but it is narrowly scoped, so building networks takes Flax, Equinox, or Keras on top.
Pick CatBoost when the data has many categorical or text columns. It accepts numeric, categorical, text, and embedding features directly and builds numeric features from the categories automatically. Its ONNX export works only for models with numeric features, and GPU training doesn't give identical results between runs.
No. Keras is a deep learning API that runs on JAX, TensorFlow, or PyTorch, so an install needs Keras and one backend. TensorFlow also ships its own Keras API as tf.keras.
For coding agents
Found your machine learning library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.