In [1]:
classpath.addPath("../figaro_2.11-4.1.0.0.jar")
In [3]:
import com.cra.figaro.language.{Flip, Select}
import com.cra.figaro.library.compound.If
import com.cra.figaro.algorithm.factored.VariableElimination // 变量消除算法
In [4]:
// 定义模型
val sunnyToday = Flip(0.2)
val greetingToday = If(sunnyToday,
Select(0.6 -> "Hello, world!", 0.4 -> "Howdy, universe!"),
Select(0.2 -> "Hello, world!", 0.8 -> "Oh no, not again"))
val sunnyTomorrow = If(sunnyToday, Flip(0.8), Flip(0.05))
val greetingTomorrow = If(sunnyTomorrow,
Select(0.6 -> "Hello, world!", 0.4 -> "Howdy, universe!"),
Select(0.2 -> "Hello, world!", 0.8 -> "Oh no, not again"))
In [5]:
// 用推测算法预测今天的问候语
def predict() {
val result = VariableElimination.probability(greetingToday, "Hello, world!")
println("Today's greeting is \"Hello, world!\" " +
"with probability " + result + ".")
}
In [6]:
// 根据今天的问候语是hello world,使用推理算法推理今天的天气
def infer() {
greetingToday.observe("Hello, world!")
val result = VariableElimination.probability(sunnyToday, true)
println("If today's greeting is \"Hello, world!\", today's " +
"weather is sunny with probability " + result + ".")
}
In [7]:
// 从今天的问候语是hello world这一观测中学习,用推理算法预测明天的问候语
def learnAndPredict() {
greetingToday.observe("Hello, world!")
val result = VariableElimination.probability(greetingTomorrow, "Hello, world!")
println("If today's greeting is \"Hello, world!\", " +
"tomorrow's greeting will be \"Hello, world!\" " +
"with probability " + result + ".")
}
In [8]:
// 执行所有任务
predict()
infer()
learnAndPredict()
In [ ]: