use rusting_brain::{Activation, Dataset, Loss, Network, Optimizer, TrainConfig};
const SIZE: u32 = 16;
const PER_CLASS: usize = 120;
fn build_corpus(root: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
for (class, vertical) in [("vertical", true), ("horizontal", false)] {
let directory = root.join(class);
std::fs::create_dir_all(&directory)?;
for index in 0..PER_CLASS {
let phase = index % 4;
let contrast = 120 + (index % 5) as u8 * 25;
let image = image::GrayImage::from_fn(SIZE, SIZE, |x, y| {
let along = if vertical { x } else { y } as usize;
let lit = (along + phase) % 4 < 2;
image::Luma([if lit { contrast } else { 20 }])
});
image.save(directory.join(format!("{index}.png")))?;
}
}
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join("rusting_brain_stripes");
build_corpus(&root)?;
let (mut dataset, classes) = Dataset::from_image_folder(&root, SIZE, SIZE, true)?;
println!(
"{} images of {}x{}, classes {classes:?}",
dataset.len(),
SIZE,
SIZE
);
dataset.shuffle(Some(42));
let (mut train, test) = dataset.split_stratified(0.8);
train.flip_horizontal(SIZE as usize)?;
println!("{} training images after mirroring", train.len());
let mut model = Network::builder()
.input_size((SIZE * SIZE) as usize)
.dense(32, Activation::Relu)
.dense(classes.len(), Activation::Softmax)
.loss(Loss::CrossEntropy)
.optimizer(Optimizer::adam(0.01))
.seed(42)
.build();
model.fit(
&train,
TrainConfig {
epochs: 40,
batch_size: 16,
shuffle: true,
seed: Some(7),
},
)?;
println!(
"train {:.1}% test {:.1}%",
100.0 * model.accuracy(&train)?,
100.0 * model.accuracy(&test)?
);
println!("\nactual \\ predicted {}", classes.join(" "));
for (class, row) in classes.iter().zip(model.confusion_matrix(&test)?) {
println!("{class:>18} {row:?}");
}
std::fs::remove_dir_all(&root)?;
Ok(())
}