Classify clothing with Fashion-MNIST in Rust
Train a clothing classifier in Rust or Python and explore its predictions.
Start the walkthrough · Jump to complete source
Train a small classifier to recognize ten kinds of clothing. This OA walkthrough follows the experiment in TensorFlow's original Fashion-MNIST classification tutorial. Both programs use the official 60,000 training images and 10,000 test images, the same model topology, and ten epochs of shuffled 32-image training batches. The figures below were generated by the Rust run with OA 0.18.0 on Intel Iris Xe with Mesa 26.3.1.
Run in Rust
Run the example from the OASDK checkout.
cargo run --release --example tu_ml_fashion_mnist
The example writes dark-theme PNGs to var/tutorials/fashion_mnist/rust/.
Use -- --epochs 1 for a shorter run or -- --output DIR to choose a directory.
1. Load and inspect the images
OADS fetches and caches the four members of the official Fashion-MNIST pack.
Use OA_DATA_DIR to select a shared cache. OADS decodes pixel intensities into
normalized FP32 [N, 1, 28, 28] matrices and labels as FP32 [N] matrices
holding exact integer IDs. The programs check split sizes, label range, class
frequencies, and the first few sample labels before training.
Fashion-MNIST dataset
Load the normalized training split on the tutorial's runtime and examine its shapes.
1let data = FashionMnist::load_on(2 &runtime,3 &FashionMnistConfig {4 split: FashionMnistSplit::Train,5 normalize: true,6 ..FashionMnistConfig::default()7 },8)?;9println!("{:?} {:?}", data.images().shape(), data.labels().shape());10// [60000, 1, 28, 28] [60000]11
The IDs in order are T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, and Ankle boot. The first training image is an ankle boot.
2. Inspect normalized pixels and labels
The source pixels are 8-bit values. Convert the first normalized preview back to the nearest 0–255 integer for the colorbar and check the conversion against the normalized image. The tutorial displays the first 25 normalized training images with their class names.
3. Build the classifier and set up training
| Layer | Output per image | Trainable values |
|---|---|---|
| Flatten | 784 pixel values | 0 |
| Linear with bias | 128 activations | 100,480 |
| ReLU | 128 activations | 0 |
| Linear with bias | 10 logits | 1,290 |
Flatten preserves the leading batch dimension. The final layer produces raw
scores for sparse cross-entropy. The programs check for four parameter tensors
and 101,770 scalar parameters. Both use OA's seeded Glorot-uniform initialization
and zero biases. OA captures AdamW updates, so both examples set weight decay
to zero for the Adam workload. The learning rate is 0.001, the betas are
0.9 and 0.999, and epsilon is 1e-7. Register the layers in Sequential so it runs them
in order and collects the trainable parameters for the optimizer.
1let mut model = Sequential::new();2model.add(Rc::new(Flatten::new(1, -1)))?;3model.add(Rc::new(Linear::new_with_seed_on(&runtime, 784, 128, 42)?))?;4model.add(Rc::new(Relu::new()))?;5model.add(Rc::new(Linear::new_with_seed_on(&runtime, 128, 10, 43)?))?;6
4. Train, validate and select a checkpoint
Use the first 55,000 rows of the official training split to fit the model and reserve its last 5,000 rows for validation. The official 10,000-row test split is evaluated after the best epoch has been selected.
The classification loaders share the dense training matrix. Each loader selects its own row range, then shuffles or reads those rows with the same epoch seed in Rust and Python. Each batch uses one device gather and a vector of U32 class indices. At batch size 32, the training, validation, and test tails contain 24, 8, and 16 rows respectively.
1let history = training.fit_with_options(2 &model,3 &mut train_batches,4 epochs,5 loss::cross_entropy,6 TrainingFitOptions {7 categorical_accuracy: true,8 validation: Some(&mut evaluate_validation),9 checkpoint: Some((&mut manager, &model)),10 },11)?;12
The managed trainer records forward, backward, and the optimizer update. Training history contains sample-weighted mean loss, categorical accuracy, and the validation result for each complete epoch. Accuracy sums exact device counts and reads them in groups. The checkpoint manager saves improvements in validation loss and restores the best model and optimizer state before test evaluation. Test loss remains sample-weighted across partial batches.
Ten epochs produce 17,190 updates. The tutorial checks that training loss falls, test accuracy reaches 85%, and test loss is below 0.6. The training curve below is from the earlier OA 0.18.0 run on all 60,000 training rows.
5. Inspect predictions
Apply softmax to the final logits along the ten-class axis. Each of the
10,000 rows must contain ten probabilities in [0, 1] summing to one within
floating-point tolerance. Independently compute accuracy and mean
negative log probability for the true labels on the host and compare them
with OA's device metrics.
Inspect test rows 0 and 12 individually, then the first fifteen in a 5×3 grid. Each image caption gives the predicted class, its probability, and the true class in parentheses. Blue captions indicate correct predictions. Red captions indicate incorrect predictions. The bars mark the true class in blue and a wrong predicted class in red. Since all fifteen fixed previews can be correct, also show the highest-confidence incorrect prediction in the test set to illustrate how this model can be confident and wrong.
In the recorded run, test image 4394 was a dress that the classifier labeled as a bag with 99.9994% confidence.
6. Predict one image
Take test image 1, a pullover, and reshape it from [28, 28] to
[1, 28, 28] to include a batch axis. Run the same classifier and softmax.
The result must agree with row 1 from the full test prediction. The
single-image chart spells out all ten class names.
1let image = test.slice(0, 1, 2)?.reshape([28, 28])?;2let single = image.reshape([1, 28, 28])?;3let single_scores = model.forward(&single)?.softmax(-1)?.read_f32()?;4
Plots and API checks
| File | Contents |
|---|---|
01_raw_image.png | Raw training image 0 and the 0–255 color scale |
02_training_images.png | First 25 labeled training images |
03_training_history.png | Loss and accuracy by epoch |
04_prediction_00.png | Test image 0 and its ten probabilities |
04_prediction_12.png | Test image 12 and its ten probabilities |
05_prediction_grid.png | First fifteen test examples and probability charts |
05_confident_error.png | Highest-confidence error in the test split, if any |
06_single_image.png | Class-labeled probability chart for the one-image batch |
Each results.json contains training and validation history, the selected
epoch, test loss and accuracy, labels, and the probability rows.
Compare matching runs on the same device:
python src/py/tutorials/ml/tu_ml_fashion_mnist/compare_runs.py
The comparison checks split sizes, optimizer update counts, the selected epoch, validation and test metrics, every test prediction, and the single-image probability vector. Compare matching runs with the same epoch count and device.
A separate one-epoch Rust run passed with the Khronos Vulkan validation layer enabled on the same device:
VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \cargo run --release --example tu_ml_fashion_mnist -- --epochs 1 \--output var/tutorials/fashion_mnist/validation
Attribution
Google's original TensorFlow tutorial was last updated on 2026-11-05 UTC. Its page content is licensed under CC BY 4.0 and its code samples under Apache 2.0, except where the page states otherwise. Original tutorial · CC BY 4.0 · Apache 2.0 · Google Developers Site Policies
The figures contain samples from Fashion-MNIST by Zalando Research. Fashion-MNIST dataset license
Source
Rust example · Plot helpers · Full Python walkthrough
Example
1//! Train and inspect the Fashion-MNIST dense classifier with OA and OADS.23mod plots;45use std::{fs, path::PathBuf, rc::Rc};67use anyhow::{Context, Result, bail, ensure};8use oa::data::{DataLoader, DataLoaderConfig};9use oa::ml::nn::{Flatten, Linear, Relu, Sequential};10use oa::ml::{11 AdamW, CheckpointManager, CheckpointManagerConfig, Module, ProgressBarCallback, SummaryCallback,12 Training, TrainingConfig, TrainingFitOptions, loss,13};14use oa::plot::{Figure, LineStyle};15use oa::{DeviceSelection, Matrix, Runtime};16use oads::image::{FashionMnist, FashionMnistConfig, FashionMnistSplit};17use serde_json::json;1819const SIDE: usize = 28;20const PIXELS: usize = SIDE * SIDE;21const CLASSES: [&str; 10] = [22 "T-shirt/top",23 "Trouser",24 "Pullover",25 "Dress",26 "Coat",27 "Sandal",28 "Shirt",29 "Sneaker",30 "Bag",31 "Ankle boot",32];33const BATCH_SIZE: usize = 32;34const TRAIN_COUNT: usize = 55_000;35const SEED: u64 = 42;36type Scores = [f32; CLASSES.len()];3738fn argmax(row: &Scores) -> usize {39 let mut best = 0;40 for index in 1..row.len() {41 if row[index] > row[best] {42 best = index;43 }44 }45 best46}4748fn load_split(49 runtime: &Runtime,50 split: FashionMnistSplit,51 count: usize,52) -> Result<(Matrix, Vec<usize>)> {53 let data = FashionMnist::decode(&FashionMnistConfig {54 split,55 normalize: true,56 ..FashionMnistConfig::default()57 })?;58 let images = data.matrix("images")?;59 let raw_labels = data.matrix("labels")?;60 ensure!(61 images.shape == [count, 1, SIDE, SIDE],62 "unexpected {split:?} image shape"63 );64 ensure!(65 raw_labels.shape == [count],66 "unexpected {split:?} label shape"67 );68 ensure!(69 raw_labels70 .values71 .iter()72 .all(|&value| (0.0..CLASSES.len() as f32).contains(&value) && value.fract() == 0.0),73 "invalid class index in {split:?}",74 );75 let labels = raw_labels76 .values77 .iter()78 .map(|&value| value as usize)79 .collect::<Vec<_>>();80 let mut frequencies = [0; CLASSES.len()];81 for &label in &labels {82 frequencies[label] += 1;83 }84 ensure!(85 frequencies == [count / CLASSES.len(); CLASSES.len()],86 "unexpected {split:?} class frequencies"87 );88 println!(89 "{split:?}: {:?}, {} labels, {:?}",90 images.shape,91 labels.len(),92 &labels[..10]93 );94 Ok((95 Matrix::new_from_f32_on(runtime, [count, PIXELS], &images.values)?,96 labels,97 ))98}99100fn loader(101 runtime: &Runtime,102 images: Matrix,103 labels: &[usize],104 start: usize,105 shuffle: bool,106) -> Result<DataLoader<'static>> {107 Ok(DataLoader::classification_subset(108 runtime,109 images,110 start,111 labels.iter().map(|&label| label as u32).collect(),112 DataLoaderConfig {113 batch_size: BATCH_SIZE as i32,114 shuffle,115 seed: SEED,116 drop_last: false,117 },118 )?)119}120121fn evaluate(122 model: &Sequential,123 batches: &mut DataLoader<'_>,124 labels: &[usize],125) -> Result<(f64, f64, Vec<Scores>)> {126 let _mode = model.scoped_eval();127 let mut probabilities = Vec::with_capacity(labels.len());128 let result = Training::evaluate_prediction_batches(129 batches,130 |batch| {131 let logits = model.forward(batch)?;132 let scores = logits.softmax(-1)?.read_f32()?;133 for row in scores.as_chunks::<{ CLASSES.len() }>().0 {134 if !row.iter().all(|value| (0.0..=1.0).contains(value))135 || (row.iter().sum::<f32>() - 1.0).abs() > 2e-5136 {137 return Err(oa::Error::invalid_argument(138 "softmax did not return a normalized distribution",139 ));140 }141 probabilities.push(*row);142 }143 Ok(logits)144 },145 loss::cross_entropy,146 true,147 )?;148 let host_correct = probabilities149 .iter()150 .zip(labels)151 .filter(|(row, label)| argmax(row) == **label)152 .count();153 let host_loss = -probabilities154 .iter()155 .zip(labels)156 .map(|(row, &label)| f64::from(row[label]).ln())157 .sum::<f64>()158 / labels.len() as f64;159 ensure!(160 result.summary.samples == labels.len() as u64161 && probabilities.len() == labels.len()162 && result.correct == Some(host_correct as u64)163 && (host_loss - result.summary.loss).abs() <= 2e-5,164 "device metrics disagree with host metrics from the probability rows",165 );166 Ok((167 result.summary.loss,168 result.accuracy().context("missing test accuracy")?,169 probabilities,170 ))171}172173fn main() -> Result<()> {174 let mut epochs = 10_u64;175 let mut device = None;176 let mut output = PathBuf::from("var/tutorials/fashion_mnist/rust");177 let mut args = std::env::args().skip(1);178 while let Some(arg) = args.next() {179 match arg.as_str() {180 "--epochs" => epochs = args.next().context("missing --epochs value")?.parse()?,181 "--device" => device = Some(args.next().context("missing --device index")?.parse()?),182 "--output" => output = args.next().context("missing --output path")?.into(),183 "--help" | "-h" => {184 println!("Usage: tu_ml_fashion_mnist [--epochs N] [--device INDEX] [--output DIR]");185 return Ok(());186 }187 _ => bail!("unknown option {arg}"),188 }189 }190 ensure!(epochs > 0, "--epochs must be positive");191 fs::create_dir_all(&output)?;192 let runtime = match device {193 Some(index) => Runtime::builder()194 .devices(DeviceSelection::Index(index))195 .build()?,196 None => Runtime::new()?,197 };198 let save = |figure: Figure, name: &str| -> Result<()> {199 let path = output.join(format!("{name}.png"));200 figure.save_to_on(&runtime, path.to_str().context("plot path must be UTF-8")?)?;201 Ok(())202 };203204 // 1. Load both official OADS splits as normalized floats.205 let (train, train_classes) = load_split(&runtime, FashionMnistSplit::Train, 60_000)?;206 let (test, test_classes) = load_split(&runtime, FashionMnistSplit::Test, 10_000)?;207 ensure!(208 train_classes[..3] == [9, 0, 0] && test_classes[..2] == [9, 2],209 "unexpected sample order"210 );211 let first = train212 .slice(0, 0, 1)?213 .read_f32()?214 .into_iter()215 .map(|value| (value * 255.0).round())216 .collect::<Vec<_>>();217 ensure!(218 first.contains(&0.0) && first.contains(&255.0),219 "expected the first raw image to span 0 to 255"220 );221 let mut raw_plot = plots::figure("First training image · raw pixel values", 1, 1, 407, 400);222 plots::image_plot(raw_plot.ax(0, 0), &first, true);223 save(raw_plot, "01_raw_image")?;224225 // 2. Reconstruct the raw pixel preview and compare it with its normalized values.226 let preview = train.slice(0, 0, 25)?.read_f32()?;227 ensure!(228 first229 .iter()230 .zip(&preview)231 .all(|(&raw, &scaled)| (raw / 255.0 - scaled).abs() <= 1e-7),232 "raw and normalized pixels disagree",233 );234 let mut grid = plots::figure("First 25 training images", 5, 5, 990, 1135);235 for (index, pixels) in preview.as_chunks::<PIXELS>().0.iter().enumerate() {236 let axes = grid.ax(index as i32 / 5, index as i32 % 5);237 plots::image_plot(axes, pixels, false);238 axes.caption(CLASSES[train_classes[index]]);239 }240 save(grid, "02_training_images")?;241242 // 3. Build Flatten → Dense(128) → ReLU → Dense(10) with trainable biases.243 let mut model = Sequential::new();244 model.add(Rc::new(Flatten::new(1, -1)))?;245 model.add(Rc::new(Linear::new_with_seed_on(246 &runtime, PIXELS, 128, SEED,247 )?))?;248 model.add(Rc::new(Relu::new()))?;249 model.add(Rc::new(Linear::new_with_seed_on(250 &runtime,251 128,252 CLASSES.len(),253 SEED + 1,254 )?))?;255 let parameters = model.all_parameters()?;256 let parameter_count: usize = parameters257 .iter()258 .map(|parameter| parameter.data().num_elements())259 .sum();260 ensure!(261 parameters.len() == 4 && parameter_count == 101_770,262 "unexpected classifier parameter count"263 );264 let mut optimizer = AdamW::new_with_hyperparameters(parameters, 0.001, 0.9, 0.999, 1e-7, 0.0)?;265 println!("Flatten (784) → Linear (128) → ReLU → Linear (10), {parameter_count} parameters");266267 // 4. Select the best validation epoch using only the official training split.268 let mut train_batches = loader(269 &runtime,270 train.clone(),271 &train_classes[..TRAIN_COUNT],272 0,273 true,274 )?;275 let mut validation_batches = loader(276 &runtime,277 train.clone(),278 &train_classes[TRAIN_COUNT..],279 TRAIN_COUNT,280 false,281 )?;282 let mut test_batches = loader(&runtime, test.clone(), &test_classes, 0, false)?;283 let mut evaluate_validation =284 || Training::evaluate_supervised(&model, &mut validation_batches, loss::cross_entropy, true);285 let mut manager = CheckpointManager::new(286 &runtime,287 CheckpointManagerConfig {288 directory: output.join("checkpoints"),289 model_name: "fashion_mnist".into(),290 metric_name: "val_loss".into(),291 ..CheckpointManagerConfig::new()292 },293 )?;294 let mut summary = SummaryCallback::new();295 let mut progress = ProgressBarCallback::default();296 let mut training = Training::new(&runtime, &mut optimizer, TrainingConfig::new())?;297 training.add_callback(&mut progress);298 training.add_callback(&mut summary);299 let history = training.fit_with_options(300 &model,301 &mut train_batches,302 epochs,303 loss::cross_entropy,304 TrainingFitOptions {305 categorical_accuracy: true,306 validation: Some(&mut evaluate_validation),307 checkpoint: Some((&mut manager, &model)),308 ..TrainingFitOptions::new()309 },310 )?;311 let best_epoch = history312 .best_epoch313 .context("missing best validation checkpoint")?;314 let history_rows = history.epochs.iter().map(|row| -> Result<_> {315 let validation = row.validation.context("missing validation history")?;316 let accuracy = row.metrics.iter().find(|(name, _)| name == "accuracy")317 .context("missing training accuracy")?.1;318 ensure!(row.samples == TRAIN_COUNT as u64319 && validation.summary.samples == (train_classes.len() - TRAIN_COUNT) as u64320 && row.loss.is_finite() && validation.summary.loss.is_finite());321 Ok(json!({"epoch": row.epoch, "loss": row.loss, "accuracy": accuracy,322 "val_loss": validation.summary.loss, "val_accuracy": validation.accuracy().context("missing validation accuracy")?}))323 }).collect::<Result<Vec<_>>>()?;324 let mut plot = plots::figure("Training history", 1, 2, 840, 300);325 let x = history326 .epochs327 .iter()328 .map(|epoch| epoch.epoch as f32)329 .collect::<Vec<_>>();330 for (column, (title, key)) in [("Loss", "loss"), ("Accuracy", "accuracy")]331 .into_iter()332 .enumerate()333 {334 let axes = plot.ax(0, column as i32);335 axes.title(title);336 axes.x_label("Epoch");337 let y = history_rows338 .iter()339 .map(|row| row[key].as_f64().expect("numeric metric") as f32)340 .collect::<Vec<_>>();341 axes.plot_xy(&x, &y, LineStyle::default());342 }343 save(plot, "03_training_history")?;344 let (test_loss, test_accuracy, probabilities) =345 evaluate(&model, &mut test_batches, &test_classes)?;346 println!(347 "Best validation epoch {best_epoch} · test loss={test_loss:.5} accuracy={:.2}%",348 100.0 * test_accuracy349 );350351 // 5. Inspect test probabilities. Captions show predicted class, confidence, and truth.352 println!(353 "test[0]: {:?} → {} ({})",354 probabilities[0],355 CLASSES[argmax(&probabilities[0])],356 CLASSES[test_classes[0]]357 );358 let preview = test.slice(0, 0, 15)?.read_f32()?;359 for index in [0, 12] {360 save(361 plots::prediction_grid(362 &preview,363 &test_classes,364 &probabilities,365 &[index],366 1,367 &format!("Test image {index}"),368 ),369 &format!("04_prediction_{index:02}"),370 )?;371 }372 save(373 plots::prediction_grid(374 &preview,375 &test_classes,376 &probabilities,377 &(0..15).collect::<Vec<_>>(),378 3,379 "First 15 test predictions",380 ),381 "05_prediction_grid",382 )?;383384 // A fixed preview can contain only correct predictions. Show the most confident error too.385 let error = probabilities386 .iter()387 .zip(&test_classes)388 .enumerate()389 .filter_map(|(index, (row, &label))| {390 let predicted = argmax(row);391 (predicted != label).then_some((index, row[predicted]))392 })393 .max_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0)));394 if let Some((index, _)) = error {395 let pixels = test.slice(0, index as i64, index as i64 + 1)?.read_f32()?;396 save(397 plots::prediction_grid(398 &pixels,399 &test_classes[index..index + 1],400 &probabilities[index..index + 1],401 &[0],402 1,403 &format!("Most confident error · test image {index}"),404 ),405 "05_confident_error",406 )?;407 }408409 // 6. Insert an explicit batch axis and predict test image 1 on its own.410 let image = test.slice(0, 1, 2)?.reshape([SIDE, SIDE])?;411 let single = image.reshape([1, SIDE, SIDE])?;412 let single_scores: Scores = model413 .forward(&single)?414 .softmax(-1)?415 .read_f32()?416 .try_into()417 .map_err(|_| anyhow::anyhow!("unexpected singleton softmax shape"))?;418 ensure!(419 single_scores420 .iter()421 .zip(probabilities[1])422 .all(|(&a, b)| (a - b).abs() <= 2e-5),423 "singleton prediction disagrees with batched test row 1",424 );425 println!(426 "test[1]: {:?} → {:?} → {}",427 image.shape(),428 single.shape(),429 CLASSES[argmax(&single_scores)]430 );431 let mut plot = plots::figure("Single image · test image 1", 1, 1, 1100, 330);432 plots::probability_plot(plot.ax(0, 0), &single_scores, test_classes[1], true);433 save(plot, "06_single_image")?;434435 let results = json!({436 "class_names": CLASSES, "parameter_count": parameter_count, "batch_size": BATCH_SIZE,437 "optimizer_steps": history.snapshot.step_count(), "restored_steps": optimizer.step_count(),438 "train_samples": TRAIN_COUNT, "validation_samples": train_classes.len() - TRAIN_COUNT,439 "best_epoch": best_epoch, "history": history_rows, "test_loss": test_loss,440 "test_accuracy": test_accuracy, "test_labels": test_classes, "probabilities": probabilities,441 "single_probabilities": single_scores,442 });443 fs::write(output.join("results.json"), serde_json::to_vec(&results)?)?;444 println!("Wrote plots and results to {}", output.display());445 if epochs == 10 {446 let first_loss = history.epochs[0].loss;447 let last_loss = history.epochs[9].loss;448 ensure!(449 last_loss < first_loss && test_accuracy >= 0.85 && test_loss < 0.6,450 "the 10-epoch run missed the Fashion-MNIST convergence gate"451 );452 }453 Ok(())454}455
plots.rs
1use oa::Color;2use oa::plot::{Axes, BarStyle, Figure, FigureConfig, HeatmapStyle, Theme};34use super::{CLASSES, PIXELS, SIDE, Scores, argmax};56const BLUE: Color = Color::new(0.35, 0.62, 1.0, 1.0);7const RED: Color = Color::new(1.0, 0.40, 0.43, 1.0);8const GRAY: Color = Color::new(0.47, 0.47, 0.47, 1.0);9const CLASS_IDS: [&str; CLASSES.len()] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];1011pub(super) fn figure(title: &str, rows: i32, cols: i32, width: u32, height: u32) -> Figure {12 Figure::new(FigureConfig {13 title: title.into(),14 rows,15 cols,16 width,17 height,18 theme: Theme::Dark,19 ..FigureConfig::default()20 })21}2223pub(super) fn image_plot(axes: &mut Axes, pixels: &[f32], raw: bool) {24 let grayscale;25 let values = if raw {26 pixels27 } else {28 grayscale = pixels.iter().map(|pixel| 1.0 - pixel).collect::<Vec<_>>();29 &grayscale30 };31 axes.heatmap(32 values,33 SIDE as i32,34 SIDE as i32,35 HeatmapStyle {36 v_max: if raw { 255.0 } else { 1.0 },37 colormap: if raw { 1 } else { 3 },38 auto_scale: false,39 show_grid: false,40 colorbar: raw,41 ..HeatmapStyle::default()42 },43 );44 axes.grid(false);45}4647pub(super) fn probability_plot(axes: &mut Axes, scores: &Scores, label: usize, names: bool) {48 let predicted = argmax(scores);49 let mut bars = [[f32::NAN; CLASSES.len()]; 3];50 for (index, &score) in scores.iter().enumerate() {51 let series = if index == label {52 253 } else if index == predicted {54 155 } else {56 057 };58 bars[series][index] = score;59 }60 for (values, color) in bars.iter().zip([GRAY, RED, BLUE]) {61 axes.bar(62 values,63 BarStyle {64 color,65 ..BarStyle::default()66 },67 );68 }69 axes.categories(if names { &CLASSES } else { &CLASS_IDS });70 axes.limits(-0.5, 9.5, 0.0, 1.0);71 axes.yticks(&[0.0, 0.5, 1.0]);72 axes.grid(false);73 axes.legend(false);74}7576pub(super) fn prediction_grid(77 images: &[f32],78 labels: &[usize],79 probabilities: &[Scores],80 indices: &[usize],81 columns: i32,82 title: &str,83) -> Figure {84 let rows = indices.len() as i32 / columns;85 let mut figure = figure(86 title,87 rows,88 2 * columns,89 600 * columns as u32,90 312 * rows as u32 + 54,91 );92 for (position, &index) in indices.iter().enumerate() {93 let (row, col) = (position as i32 / columns, position as i32 % columns);94 let (scores, label) = (&probabilities[index], labels[index]);95 let predicted = argmax(scores);96 let axes = figure.ax(row, 2 * col);97 image_plot(axes, &images[index * PIXELS..(index + 1) * PIXELS], false);98 axes.caption_color(99 &format!(100 "{} {:.0}% ({})",101 CLASSES[predicted],102 scores[predicted] * 100.0,103 CLASSES[label]104 ),105 if predicted == label { BLUE } else { RED },106 );107 probability_plot(figure.ax(row, 2 * col + 1), scores, label, false);108 }109 figure110}111
Run Rust tutorials from the OA SDK checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.