Markov model library for Rust
Add markov
as a dependency:
[dependencies]
markov = { git = "https://github.com/mandykoh/rs-markov", tag = "v0.1.0" }
Create a model for holding your Markov data. The Model needs the order to be specified—a 1st order model tracks probabilities of future symbols based on one prior symbol, whilst a 3rd order model tracks probabilities of future symbols based on three prior symbols.
Here we’re specifying a 1st order model:
let mut model = markov::Model::empty(1);
Use an Accumulator to train the model:
let mut acc = markov::Accumulator::new(&mut model);
Symbols can be added in sequence to the accumulator, which will update the underlying model. Symbols can represent characters, words, events, or any abstract element in an ordered sequence. If your use case has sequences with logical endings, use end
to indicate this.
acc.add("the");
acc.add("quick");
acc.add("brown");
acc.add("fox");
acc.end();
Use a Generator to generate new sequences from the model. The Generator needs a rand_source
which returns numbers in the [0, 1) range and determines how samples are drawn (here, we use a pseudorandom number generator):
use rand::Rng;
let mut rng = rand::thread_rng();
let mut gen = markov::Generator::new(&model, Box::new(move || rng.gen::<f64>()));
Sequences of symbols can be generated by sampling from the Generator:
while let Some(symbol) = gen.next() {
print!(" {}", symbol);
}
println!();
Use a Predictor to predict the most likely following symbols based on a model:
let mut pre = markov::Predictor::new(&model);
pre.given("the");
pre.given("quick");
pre.given("brown");
let prediction = pre.predict(); // returns Some(&"fox")
Predictors can also produce entire most-likely sequences (similarly to Generators but without a random element):
while let Some(symbol) = pre.next() {
print!(" {}", symbol);
}
println!();
This software is make available under an MIT license.