use oa::data::{Dataset, MatrixDataset, Sample};
use oa::matrix::Matrix;
use oa::{Engine, Error, Result};
use crate::decode::{Decoded, MatrixData};
use crate::extract;
use crate::idx::{self, IdxSplit};
use crate::pack::{self, FetchProgress};
#[path = "mnist.gen.rs"]
mod generated;
pub(crate) use generated::MNIST_PACK;
pub use generated::{MnistConfig, MnistSplit};
pub struct Mnist {
dataset: MatrixDataset,
split: MnistSplit,
}
impl Mnist {
pub fn decode(config: &MnistConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &MnistConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Decoded> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
let dir = pack::ensure_pack_with_progress(&MNIST_PACK, &root, progress)?;
let (images_name, labels_name) = match config.split {
IdxSplit::Train => ("train-images-idx3-ubyte.gz", "train-labels-idx1-ubyte.gz"),
IdxSplit::Test => ("t10k-images-idx3-ubyte.gz", "t10k-labels-idx1-ubyte.gz"),
};
let (shape, values) = idx::decode_images(
"mnist",
&extract::gunzip(&dir.join(images_name))?,
config.normalize,
)?;
let images = MatrixData {
name: "images",
shape,
values,
};
let (shape, values) = idx::decode_labels("mnist", &extract::gunzip(&dir.join(labels_name))?)?;
let labels = MatrixData {
name: "labels",
shape,
values,
};
let (count, label_count) = (images.shape[0], labels.shape[0]);
if count != label_count {
return Err(Error::data_loss(format!(
"mnist split has {count} images but {label_count} labels"
)));
}
Ok(Decoded {
matrices: vec![images, labels],
text: None,
seq_len: 0,
})
}
pub fn load_with_progress_on(
engine: &Engine,
config: &MnistConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
let decoded = Self::decode_with_progress(config, progress)?;
Self::new(
decoded.upload("images", engine)?,
decoded.upload("labels", engine)?,
config.split,
)
}
pub fn new(images: Matrix, labels: Matrix, split: MnistSplit) -> Result<Self> {
if images.shape().len() != 4 {
return Err(Error::invalid_argument(
"mnist requires [N, C, H, W] images",
));
}
Ok(Self {
dataset: MatrixDataset::new(images, labels)?,
split,
})
}
#[must_use]
pub const fn images(&self) -> &Matrix {
self.dataset.x()
}
#[must_use]
pub const fn labels(&self) -> &Matrix {
self.dataset.y()
}
#[must_use]
pub const fn split(&self) -> MnistSplit {
self.split
}
}
impl Dataset for Mnist {
fn len(&self) -> i64 {
self.dataset.len()
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.dataset.get_item(index)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.dataset.get_sample(index)
}
}