python 逻辑编程

mno*_*awi 3 python prolog logic-programming

我正在做一个主要基于逻辑编程的项目。我已经预先定义了程序用来计算概率的相关规则和事实,然后将这些概率附加到数据中并输入到进一步的机器学习模型中。计算概率的程序可以在序言中轻松定义,例如:

has_lot_work(daniel, 8). %number of lets say urgent tasks
has_lot_work(david, 3).
stress(X, P) :- has_lot_work(X, P2), P is P2 / 100.
to_smoke(X, Prob) :- stress(X, P1), friends(Y, X), influences(Y, X, P2), smokes(Y), Prob is P1 + P2.
to_have_asthma(X, 0.3) :- smokes(X). %30 percent of current smokers get asthma
to_have_asthma(X, Prob) :- to_smoke(X, P2), Prob is P2 * 0.25. %25 percent of smokers-to-be will get asthma
friends(X, Y) :- friend(X, Y).
friends(X, Y) :- friend(Y, X).
influences(X, Y, 0.4) :- friends(X, Y). %friends influence each other by 40 percent
friend(peter, david).
friend(peter, rebecca).
friend(daniel, rebecca).
smokes(peter).
smokes(rebecca).
Run Code Online (Sandbox Code Playgroud)

在该示例中,我有兴趣计算某人吸烟 (to_smoke(Who, Prob)) 和患哮喘 (to_have_asthma(Who, Prob)) 的概率。我使用 python 来获取和清理数据以及之后的 ML 模型,所以我也想在 python 中应用这个逻辑。但找不到一种方法来进行这种逻辑计算,也找不到一种正确的方法来将 python 与 prolog 连接起来,而不会出现错误和问题。

mno*_*awi 6

我尝试开发一些使用 python 中的 prolog 语法、方法和回溯来解决问题的东西。我写了pytholog库。我正在分享答案以获取评论以及是否有更好的方法。

在 pytholog 中,我启动了一个知识库并对其进行查询。

import pytholog as pl
friends_kb = pl.KnowledgeBase("friends")
friends_kb([
    "has_lot_work(daniel, 8)",
    "has_lot_work(david, 3)",
    "stress(X, P) :- has_lot_work(X, P2), P is P2 / 100",
    "to_smoke(X, Prob) :- stress(X, P1), friends(Y, X), influences(Y, X, P2), smokes(Y), Prob is P1 + P2",
    "to_have_asthma(X, 0.3) :- smokes(X)",
    "to_have_asthma(X, Prob) :- to_smoke(X, P2), Prob is P2 * 0.25",
    "friends(X, Y) :- friend(X, Y)",
    "friends(X, Y) :- friend(Y, X)",
    "influences(X, Y, 0.4) :- friends(X, Y)",
    "friend(peter, david)",
    "friend(peter, rebecca)",
    "friend(daniel, rebecca)",
    "smokes(peter)",
    "smokes(rebecca)"
])
print(friends_kb.query(pl.Expr("to_smoke(Who, P)")))
# [{'Who': 'daniel', 'P': 0.48000000000000004}, {'Who': 'david', 'P': 0.43000000000000005}]
print(friends_kb.query(pl.Expr("to_have_asthma(Who, P)")))
# [{'Who': 'peter', 'P': '0.3'}, {'Who': 'rebecca', 'P': '0.3'}, {'Who': 'daniel', 'P': 0.12000000000000001}, {'Who': 'david', 'P': 0.10750000000000001}]
Run Code Online (Sandbox Code Playgroud)


Guy*_*der 5

您有几个选择,但据我所知,Python 没有内置方法或谓词,因此您需要将其作为库来访问。

  1. 一种流行的方法是使用miniKanren。我没有用过这个,但光看它的语法就足以让我惊恐地逃跑。

  2. 另一种方法是在 Python 和 Prolog 之间找到一个接口,一个流行的方法是在 Python 和 SWI-Prolog 之间找到一个接口,例如pyswip。其中有很多,因此您必须寻找并检查哪一个最适合您的需求。再说一遍,我没有使用过这些。

如果您确实选择使用库连接到 SWI-Prolog,我确实知道SWI-Prolog 论坛上会不时出现这些问题。

这是我会选择的一个,因为你可以访问带有剪切、回溯、制表等功能的全功能 Prolog。

  1. 一种更难但最能提供洞察力的方法是自己用 Python 实现逻辑。请参阅:在 Python 中实现 Prolog 统一算法?回溯