Perceptron
perceptron.nr50 lines
perceptron.nr· neuro
// A two-neuron feed-forward pass. Integration example: structs, `impl` blocks
// with an associated function and `&self` methods, `f64` arithmetic, `if`/`else` as a
// value, `while`, and `as`. A hidden neuron feeds an output neuron. A ramp of inputs runs
// through both, the fired outputs are summed, and the truncated sum is the exit code.
struct Neuron {
weight: f64,
bias: f64
}
impl Neuron {
func new(weight: f64, bias: f64) -> Neuron {
Neuron { weight: weight, bias: bias }
}
// Weighted pre-activation: w * x + b.
func preact(&self, input: f64) -> f64 {
(input * self.weight) + self.bias
}
// ReLU activation.
func activate(&self, input: f64) -> f64 {
val z = self.preact(input)
if z > 0.0 { return z }
return 0.0
}
}
func main() -> i32 {
val hidden = Neuron::new(0.5, -0.2)
val output = Neuron::new(2.0, 0.1)
// Feed inputs 0.0, 1.0, ... 4.0 through hidden -> output, summing outputs.
mut total: f64 = 0.0
mut x: f64 = 0.0
while x < 5.0 {
val h = hidden.activate(x)
val y = output.activate(h)
println("x {x:.1} -> hidden {h:.2} -> output {y:.2}")
total += y
x += 1.0
}
println("summed output = {total:.2}")
// total == 8.9; truncating toward zero yields 8.
val code = total as i32
println("truncated exit code = {code}")
return code
}
neuroc run perceptron.nr
x 0.0 -> hidden 0.00 -> output 0.10
x 1.0 -> hidden 0.30 -> output 0.70
x 2.0 -> hidden 0.80 -> output 1.70
x 3.0 -> hidden 1.30 -> output 2.70
x 4.0 -> hidden 1.80 -> output 3.70
summed output = 8.90
truncated exit code = 8