Skip to content

Instantly share code, notes, and snippets.

@mdabir1203
Created August 16, 2025 22:56
Show Gist options
  • Select an option

  • Save mdabir1203/f307903698f327418bf7927388203521 to your computer and use it in GitHub Desktop.

Select an option

Save mdabir1203/f307903698f327418bf7927388203521 to your computer and use it in GitHub Desktop.
"Rust Model Inference Example"
use ndarray::prelude::*;
use ndarray_rand::RandomExt;
use ndarray_rand::rand::distributions::Uniform;
fn sigmoid(x: &Array2<f64>) -> Array2<f64> {
x.mapv(|v| 1.0 / (1.0 + (-v).exp()))
}
// Pretrained weights
struct Model {
weights: Array2<f64>,
}
impl Model {
fn predict(&self, input: &Array2<f64>) -> Array2<f64> {
sigmoid(&input.dot(&self.weights))
}
}
fn main() {
// Example: 3 input features
let x = array![
[0.0, 0.0, 1.0],
[0.0, 1.0, 1.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 1.0]
];
let unseen_patterns = array![
[0.0, 1.0, 0.0], // feature3 flipped
[1.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0] // all zeros
];
let edge_cases = array![
[1.0, 1.0, 1.0], // all ones
[0.0, 0.0, 0.0], // all zeros
[0.5, 0.5, 0.5], // intermediate values
[1.0, 0.0, 1.0] // training sample
];
let noisy_inputs = array![
[0.1, 0.0, 1.0],
[0.0, 0.9, 1.0],
[0.95, 0.05, 1.0],
[0.5, 0.5, 1.0]
];
// Load pretrained weights (random for demo)
let weights = Array::random((3,1), Uniform::new(-1.0, 1.0));
let model = Model { weights };
let output = model.predict(&x);
let unseen_output = model.predict(&unseen_patterns);
let edge_output = model.predict(&edge_cases);
let noisy_output = model.predict(&noisy_inputs);
println!("Inference output:\n{:?}", output);
println!("Unseen patterns output:\n{:?}", unseen_output);
println!("Edge cases output:\n{:?}", edge_output);
println!("Noisy inputs output:\n{:?}", noisy_output);
let all_samples = vec![output, unseen_patterns, edge_cases, noisy_inputs];
for (i, batch) in all_samples.iter().enumerate() {
let output = model.predict(batch);
println!("Batch {} prediction:\n{:?}", i + 1, output);
}
}
@mdabir1203
Copy link
Author

Had an interesting observation explanation through claude :

tensor_error_flowchart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment