Created
July 24, 2014 01:45
-
-
Save mtomwing/934776e4e302635696fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Perceptron { | |
weights: Vec<f64>, | |
threshold: f64, | |
learning_rate: f64, | |
} | |
impl Perceptron { | |
pub fn new(n: uint, rate: f64) -> Perceptron { | |
let weights = Vec::from_elem(n, 1f64); | |
Perceptron { | |
weights: weights, | |
threshold: 0f64, | |
learning_rate: rate, | |
} | |
} | |
pub fn apply(&self, inputs: &[f64]) -> f64 { | |
let mut sum = 0f64; | |
for (&input, &weight) in inputs.iter().zip(self.weights.iter()) { | |
sum += input * weight; | |
} | |
if sum >= self.threshold { | |
return 1 as f64; | |
} | |
else { | |
return 0 as f64; | |
} | |
} | |
pub fn learn_with_output(&mut self, inputs: &[f64], output: f64) { | |
let error = output - self.apply(inputs); | |
self.threshold += -error * self.learning_rate; | |
for (&input, weight) in inputs.iter().zip(self.weights.mut_iter()) { | |
*weight += error * self.learning_rate * input; | |
} | |
} | |
} | |
fn main() { | |
let mut neuron = Perceptron::new(2, 0.5); | |
println!("perceptron([1, 1]) = {}", neuron.apply([1f64, 1f64])); | |
println!("perceptron([1, 0]) = {}", neuron.apply([1f64, 0f64])); | |
println!("perceptron([0, 1]) = {}", neuron.apply([0f64, 1f64])); | |
println!("perceptron([0, 0]) = {}", neuron.apply([0f64, 0f64])); | |
neuron.learn_with_output([1f64, 1f64], 1f64); | |
neuron.learn_with_output([1f64, 0f64], 0f64); | |
neuron.learn_with_output([0f64, 1f64], 0f64); | |
neuron.learn_with_output([0f64, 0f64], 0f64); | |
println!("perceptron([1, 1]) = {}", neuron.apply([1f64, 1f64])); | |
println!("perceptron([1, 0]) = {}", neuron.apply([1f64, 0f64])); | |
println!("perceptron([0, 1]) = {}", neuron.apply([0f64, 1f64])); | |
println!("perceptron([0, 0]) = {}", neuron.apply([0f64, 0f64])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment