Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:LaurentMazare Tch rs Mnist Load Dir

From Leeroopedia


Knowledge Sources
Domains Computer_Vision, Data_Loading
Last Updated 2026-02-08 14:00 GMT

Overview

Concrete tool for loading the MNIST dataset from IDX binary files provided by the tch vision module.

Description

The vision::mnist::load_dir function reads the four standard MNIST IDX files from a specified directory, parses the binary format, and returns a Dataset struct containing train/test images and labels as tensors. Images are normalized to [0, 1] as float32 tensors of shape [N, 784], and labels are int64 tensors.

Usage

Import this function when you need to load the MNIST dataset for training or evaluating handwritten digit classifiers. The directory must contain the four standard MNIST files: train-images-idx3-ubyte, train-labels-idx1-ubyte, t10k-images-idx3-ubyte, t10k-labels-idx1-ubyte.

Code Reference

Source Location

  • Repository: tch-rs
  • File: src/vision/mnist.rs
  • Lines: 62-69

Signature

pub fn load_dir<T: AsRef<std::path::Path>>(dir: T) -> Result<Dataset>

Import

use tch::vision::mnist;

I/O Contract

Inputs

Name Type Required Description
dir T: AsRef<Path> Yes Path to directory containing the 4 MNIST IDX files

Outputs

Name Type Description
Result<Dataset> Dataset Contains train_images [60000, 784] f32, train_labels [60000] i64, test_images [10000, 784] f32, test_labels [10000] i64, labels: 10

Usage Examples

Basic MNIST Loading

use tch::vision::mnist;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load MNIST from the data directory
    let m = mnist::load_dir("data/mnist")?;

    println!("Train images shape: {:?}", m.train_images.size());  // [60000, 784]
    println!("Train labels shape: {:?}", m.train_labels.size());  // [60000]
    println!("Test images shape: {:?}", m.test_images.size());    // [10000, 784]
    println!("Number of classes: {}", m.labels);                   // 10

    Ok(())
}

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment