pub struct Neuron {
pub threshold: f64,
}
impl Neuron {
pub fn new(threshold: f64) -> Self {
Self { threshold }
}
pub fn activate(&self, inputs: &[f64]) -> f64 {
let sum: f64 = inputs.iter().sum();
if sum >= self.threshold {
1.0
} else {
0.0
}
}
}
pub mod utils {
pub fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
pub fn relu(x: f64) -> f64 {
x.max(0.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn neuron_activates_above_threshold() {
let neuron = Neuron::new(0.5);
let result = neuron.activate(&[0.3, 0.4]);
assert_eq!(result, 1.0);
}
#[test]
fn neuron_does_not_activate_below_threshold() {
let neuron = Neuron::new(0.5);
let result = neuron.activate(&[0.1, 0.2]);
assert_eq!(result, 0.0);
}
#[test]
fn sigmoid_function_works() {
let result = utils::sigmoid(0.0);
assert!((result - 0.5).abs() < f64::EPSILON);
}
#[test]
fn relu_function_works() {
assert_eq!(utils::relu(-1.0), 0.0);
assert_eq!(utils::relu(1.0), 1.0);
}
}