// 今天天气的概率:晴天0.9,不是晴天0.1
val sunnyToday =Flip(0.9)
val greetToday =If(sunnyToday,// 如果今天是晴天:说Hello的概率是0.6,说Howdy的概率是0.4Select(0.6->"Hello World!",0.4->"Howdy, universe!"),// 如果今天不是晴天:说Hello的概率是0.2,说Howdy的概率是0.8Select(0.2->"Hello World!",0.8->"Howdy, universe!"))
val sunnyTomorrow =If(sunnyToday,// 如果今天是晴天:明天是晴天的概率是0.8Flip(0.8),// 如果今天是晴天:明天是晴天的概率是0.05Flip(0.05))
val greetingTomorrow =If(sunnyTomorrow,// 如果明天是晴天:说Hello的概率是0.6,说Howdy的概率是0.4Select(0.6->"Hello World!",0.4->"Howdy, universe!"),// 如果明天是晴天:说Hello的概率是0.2,说Howdy的概率是0.8Select(0.2->"Hello World!",0.8->"Howdy, universe!"))
2. 推测方法
预测今天的问候语
def predict(): Unit ={
val result = VariableElimination.probability(greetToday,"Hello World!")println(s"Today's greeting is \'Hello World\' with probability $result.")}
根据今天问候语是Hello World这一事实,推断今天的天气
def infer(): Unit ={
greetToday.observe("Hello World!")
val result = VariableElimination.probability(sunnyToday,true)println("If today's greeting is \'Hello World\', "+
s"today's weather is sunny with probability $result.")}
根据今天问候语是Hello World这一事实,预测明天的问候语
def learnAndPredict(): Unit ={
greetToday.observe("Hello World!")
val result = VariableElimination.probability(greetingTomorrow,"Hello World!")println("If today's greeting is \'Hello World\', "+
s"tomorrow's greeting will be \'Hello World\' with probability $result.")}
3. Main 预测
def main(args: Array[String]): Unit ={predict()infer()learnAndPredict()}