Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

There is no universal “save model” command. Save a framework-native artifact for normal reuse, a complete checkpoint when you must resume training, and a tested export such as ONNX or SavedModel when the model must run in another runtime. Always save preprocessing, configuration and compatibility metadata with the model.

Choose the artifact by its purpose

Need Preferred approach What it preserves Main limitation
Reuse a scikit-learn estimator in Python joblib or skops Fitted estimator, and preprocessing when saved as a pipeline Depends on compatible Python and library versions
Run PyTorch inference in the same codebase state_dict Learned parameters The model class and architecture code must be available
Resume PyTorch training Checkpoint dictionary Weights, optimizer, scheduler and training progress Larger and more coupled to the training setup
Reuse a Keras model .keras Configuration, weights, compilation information, optimizer state and metadata Requires a compatible Keras environment
Serve with TensorFlow TensorFlow SavedModel export A serving-oriented computation graph and signatures It is not the same thing as a training checkpoint
Share a Transformers model save_pretrained() plus the tokenizer Weights, configuration, vocabulary and tokenizer settings Creates a directory of files, not one universal file
Run inference outside the original framework ONNX or another supported export A portable inference representation Operator support, preprocessing and numerical behavior can vary
Manage versions across a team MLflow or a model hub Artifacts, metadata, revisions and governance Adds operational complexity

Serialization is not the same as saving only neural-network weights. A usable prediction system can also require the architecture, feature order, normalization values, tokenizer, vocabulary, label mapping, post-processing rules and dependency versions.

Decide what must be saved

Inference artifact

For prediction, save the learned parameters plus an independently reproducible architecture or complete native model artifact. Include the exact input schema, preprocessing and post-processing, output labels, model version and any tokenizer or vocabulary. Optimizer state is normally unnecessary for inference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Training checkpoint

To continue from a particular training step, save more than the model:

#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
  • Model parameters and architecture configuration
  • Optimizer state, including momentum and adaptive-learning-rate statistics
  • Learning-rate scheduler state
  • Current epoch or global step
  • Losses, validation metrics and best-score information
  • Early-stopping state
  • Mixed-precision gradient-scaler state, when used
  • Random-number-generator state and, where relevant, data-loader or sampler position
  • Distributed-training metadata

Without optimizer and scheduler state, a model may make correct predictions but cannot claim an identical training resume.

Input-processing state

Persist standardization and normalization parameters, imputation values, categorical encoders, feature names and order, image resize rules, sequence length and padding conventions, tokenizer files, vocabulary and label-index mappings. Saving weights alone does not preserve these decisions.

Security before loading anything

Never trust a model file merely because it ends in .pkl, .joblib, .pt or .pth. Pickle-based deserialization can execute arbitrary code. Scikit-learn warns that pickle, joblib and cloudpickle files should be loaded only from trusted sources and that persisted objects generally require compatible dependency versions (scikit-learn model persistence guidance).

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Obtain artifacts from a trusted publisher and verify a checksum or signature.
  • Inspect an unfamiliar file in a sandbox, not on a production host.
  • Prefer weights-only or safe formats where the framework supports them.
  • Pin framework and dependency versions.
  • Keep credentials, private training data and secrets out of model metadata.
  • Treat model repositories and archives as software supply-chain inputs.

Hugging Face documents safetensors as a safer and faster-to-load alternative when available for Transformers weights (Transformers model loading documentation). “Safer” does not mean that every parser, repository or surrounding script is risk-free.

Save a scikit-learn model

Save and reload an estimator

import joblib

joblib.dump(model, "model.joblib")
loaded_model = joblib.load("model.joblib")

This is a practical choice for many fitted scikit-learn objects when the loading environment has compatible Python and package versions. It is not a universal format for PyTorch, TensorFlow or Transformers, and it should not be used to load an untrusted file.

Save the complete pipeline

Put fitted preprocessing and the estimator in one Pipeline; otherwise a separately saved classifier can receive differently scaled or encoded data at inference time.

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import joblib

pipeline = Pipeline([
    ("scale", StandardScaler()),
    ("classifier", LogisticRegression())
])

pipeline.fit(X_train, y_train)
joblib.dump(pipeline, "classifier_pipeline.joblib")

loaded_pipeline = joblib.load("classifier_pipeline.joblib")
predictions = loaded_pipeline.predict(X_test)

Alternatives and portability

  • pickle: built into Python, but subject to the same arbitrary-code risk when loading.
  • cloudpickle: can serialize more custom Python code, with weaker portability and forward-compatibility guarantees.
  • skops: a scikit-learn-oriented option designed to reduce unsafe deserialization risk, subject to compatibility checks.
  • ONNX: useful for non-Python inference, but it does not recreate every Python estimator or custom component.

For a supported estimator, an ONNX export can look like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
  • Easily store and access 5TB of content on the go with the Seagate portable drive, a USB external hard Drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
from skl2onnx import to_onnx

onnx_model = to_onnx(
    pipeline,
    X_train[:1].astype("float32"),
    target_opset=12
)

with open("model.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

Check the converter for your exact estimator and test preprocessing, dynamic shapes and numerical equivalence; ONNX does not support every scikit-learn feature automatically. See the scikit-learn persistence documentation.

Save a PyTorch model

Weights for inference

The flexible, commonly recommended approach is to save the model’s state_dict, then reconstruct the same class before loading it.

import torch

torch.save(model.state_dict(), "model.pth")

model = MyModel()
state_dict = torch.load("model.pth", weights_only=True)
model.load_state_dict(state_dict)
model.eval()

load_state_dict() receives the dictionary, not the file path. Calling eval() matters because dropout and batch-normalization behave differently during inference. The architecture definition and compatible code must still be present.

Checkpoint for resuming training

torch.save({
    "epoch": epoch,
    "model_state_dict": model.state_dict(),
    "optimizer_state_dict": optimizer.state_dict(),
    "scheduler_state_dict": scheduler.state_dict()
        if scheduler is not None else None,
    "loss": loss,
}, "checkpoint.tar")

checkpoint = torch.load("checkpoint.tar", weights_only=True)
model = MyModel()
optimizer = torch.optim.Adam(model.parameters())

model.load_state_dict(checkpoint["model_state_dict"])
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])

if checkpoint["scheduler_state_dict"] is not None:
    scheduler.load_state_dict(checkpoint["scheduler_state_dict"])

start_epoch = checkpoint["epoch"] + 1
model.train()

Add configuration, validation metrics, random states and gradient-scaler state when those are needed to reproduce the run. A checkpoint is often larger than weights alone because it includes optimizer and other training state (PyTorch saving and loading tutorial).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not accidentally overwrite the best state

This reference can continue changing as training updates the model:

best_model_state = model.state_dict()

Preserve the state immediately or copy it:

from copy import deepcopy

best_model_state = deepcopy(model.state_dict())

Alternatively, write a checkpoint at the moment a new best validation score is found.

Full-object saves

torch.save(model, "model.pt")
model = torch.load("model.pt", weights_only=False)

This is tightly coupled to the original class location and Python code. Moving or renaming a module can make the file unloadable, and the serialization path uses pickle-based behavior. Prefer a state dictionary or a tested deployment export for artifacts that must outlive the current codebase. Current PyTorch loading options distinguish ordinary weights loading from arbitrary serialized objects; never load an untrusted file.

Rank #3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

CPU loading

checkpoint = torch.load(
    "model.pth",
    map_location="cpu",
    weights_only=True
)
model.load_state_dict(checkpoint)
model.to(device)

Loading tensors onto the CPU is separate from making a complete object’s custom classes and device assumptions compatible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Save a TensorFlow or Keras model

Keras whole-model format

model.save("my_model.keras")

from keras.models import load_model
model = load_model("my_model.keras")

The modern .keras format can contain model configuration, weights, compilation information, optimizer state and metadata (Keras serialization and saving guide).

Weights only

model.save_weights("model.weights.h5")
model.load_weights("model.weights.h5")

Recreate the identical architecture before loading weights. A weights file does not carry the model definition or custom preprocessing by itself.

Export for TensorFlow serving

model.export("exported_model", format="tf_saved_model")

import tensorflow as tf
artifact = tf.saved_model.load("exported_model")

Keras 3 can export to TensorFlow SavedModel, ONNX, OpenVINO, LiteRT and Torch when the backend and operators support the requested target (Keras export API). SavedModel is a serving/export artifact, not an interchangeable replacement for a training checkpoint. Older .h5 workflows remain compatibility-dependent; do not assume .h5, .keras, weights-only files and SavedModel have the same contents. See TensorFlow’s serialization guide.

Custom layers

Make custom layers importable, register custom objects where required, and package the source or dependency version. Test loading in a clean environment rather than relying on the process that created the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Save a Hugging Face Transformers model

Save model and tokenizer together

model.save_pretrained("./my_model")
tokenizer.save_pretrained("./my_model")

from transformers import AutoModelForSequenceClassification, AutoTokenizer

model = AutoModelForSequenceClassification.from_pretrained("./my_model")
tokenizer = AutoTokenizer.from_pretrained("./my_model")

save_pretrained() writes a configuration directory that from_pretrained() can reload. Save the tokenizer as well: vocabulary, special tokens, truncation and padding settings are part of the prediction contract (Transformers model API).

When available, Transformers can use safetensors weights; the documentation describes this format as safer and faster to load than traditional pickle-based PyTorch serialization (Transformers models documentation).

Rank #4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
  • Easily store and access 4TB of content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Publish to the Hub carefully

model.push_to_hub("username/my-model")
tokenizer.push_to_hub("username/my-model")

Authenticate first, choose public or private visibility deliberately, and include a model card with license, intended use, limitations, evaluation data and metrics. Pin a revision or commit when deploying. Check that no private or regulated training data has been placed in the repository. The Hub is available at huggingface.co; plan details and prices can change.

Native format versus deployment export

Native formats are usually best for continued development because they preserve framework-specific state and are easy to reload in the original ecosystem. Deployment exports are preferable when the serving runtime is different, the language is not Python, or you need a stable serving boundary. ONNX, SavedModel and other exports can have unsupported operators, dynamic-shape constraints, preprocessing gaps or small numerical differences. Export the complete prediction path where possible, then test the exported artifact with representative inputs.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Build a reproducible model package

Record the prediction contract

model format
framework and version
Python version
dependency versions
input feature names and order
input dtypes and shapes
preprocessing steps
output meaning and label mapping
training-data identifier
evaluation metrics
random seed
creation timestamp
license and usage restrictions

Use immutable, verifiable directories

models/
  classifier/
    2026-08-18/
      model.joblib
      metadata.json
      requirements.txt
      sha256.txt

Write to a temporary path, load and validate it, then rename or promote it. Do not overwrite the only known-good model. Capture the environment, for example:

python --version
pip freeze > requirements.txt

A lockfile or container image gives stronger reproducibility than an unconstrained requirements file.

Test a round trip in a fresh process

import numpy as np

original_output = model.predict(X_test[:10])
loaded_output = loaded_model.predict(X_test[:10])

np.testing.assert_allclose(
    original_output,
    loaded_output,
    rtol=1e-5,
    atol=1e-6
)
  1. Load the artifact in a fresh process or environment.
  2. Run fixed test inputs through the original and reloaded models.
  3. Compare outputs using an explicitly chosen tolerance.
  4. Confirm preprocessing, label decoding and inference mode.
  5. Test CPU loading if the deployment target may not have a GPU.

Byte-for-byte equality is not always appropriate because floating-point, backend, hardware and nondeterministic-operator differences can occur. A successful load alone proves only that the file is readable, not that its prediction contract is correct.

Use a registry or model hub when lifecycle matters

A local file is enough for a small experiment. Teams that need approvals, rollback, lineage and multiple framework types may use a registry. MLflow models are directories containing an MLmodel file and artifact files, with framework “flavors” for scikit-learn, PyTorch, Keras, TensorFlow and ONNX (MLflow model documentation). MLflow also documents pickle-free formats, including skops for scikit-learn and pt2 for certain PyTorch workflows, with stated restrictions or experimental status (MLflow pickle-free models).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a model hub for shareable transformer artifacts, MLflow for multi-experiment governance, or object storage such as Amazon S3 when durable artifact storage—not a registry—is the main requirement. None is required to save one local model.

Troubleshoot common failures

FileNotFoundError

A relative path may resolve from a different working directory, or the save directory may not exist. Create it explicitly and log the final location:

from pathlib import Path

path = Path("models") / "model.joblib"
path.parent.mkdir(parents=True, exist_ok=True)

Use absolute paths in production jobs and avoid temporary runtimes that disappear after execution.

ModuleNotFoundError or class-not-found errors

Pickle-based files and full PyTorch-object saves may require the original package and module path. Restore the compatible environment for a one-time recovery, then create a state-dictionary or portable export for future use. Do not edit or load unknown pickle files blindly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Shape mismatch

Compare saved metadata with the current schema. Check feature count and order, tokenizer vocabulary, image dimensions and the reconstructed architecture. Include preprocessing in the saved pipeline or package.

Missing optimizer state

Inference can still work, but exact training continuation is impossible without the optimizer and scheduler state. Use a documented warm-start procedure instead of claiming an identical resume.

Predictions changed after reload

  • Set inference models to evaluation mode.
  • Disable random preprocessing.
  • Check normalization, feature order, units and missing-value handling.
  • Verify tokenizer version and label-index mapping.
  • Check thresholds and post-processing.
  • Compare intermediate outputs and record software and hardware versions.
  • Use a justified tolerance for floating-point differences.

Practical recommendation

Save the framework-native artifact for development, save a complete checkpoint when resuming training, and export a tested deployment artifact when the model must run elsewhere. Package that artifact with preprocessing, metadata, versions, a checksum and a fresh-process round-trip test; otherwise a file that loads may still produce the wrong predictions.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$129.99
Bestseller No. 2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
Bestseller No. 3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80
Bestseller No. 4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$189.98

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.