计算Python的条件概率
计算Python的条件概率
我试图计算一种具有层次结构树的结果的概率
图中最上面的是计算机A,接下来是计算机B和C,最后是计算机BD、BE、CD、CE。我试图找到的概率是,如果计算机A感染了病毒,B或C会感染病毒的概率。如果B或C感染了病毒,BD、BE、CD、CE会感染病毒的概率是多少。
我想运行100次试验来得到答案。我是第一次在python上进行概率运算。然而,这是目前为止我写出的代码:
import random, time #prob that computers will get virus CompA = 0.50 CompB = .25 CompC = .25 CompBD = .125 CompBE= .125 CompCD= .125 CompCE= .125 def generate(): x = random.random() if x =< CompA: #Computer A has virus prob_compa= sum(generate() for i in range(100)) #prob that Comp A has virus in a 100 rounds print (prob_compa/100 + 'percent chance of getting virus') try: if CompB<.125: prob_compa sum(generate() for i in range(100)) #prob that Comp B has virus in a 100 rounds print (prob_compa/100 + 'percent chance of getting virus') elif CompB<.125: prob_compa= sum(generate() for i in range(100)) #prob that Comp C is sick in a 100 rounds print (prob_compa/100 + 'percent chance of getting virus') #I continue this method for the rest of the tree
我有没有更好、更简单地获得结果的方法?random.uniform?
admin 更改状态以发布 2023年5月21日
非常棒的代码来自mabe02,或许值得在核心函数中增加一个非常小的改进,以避免混淆/未来的错误:
def check_probability(computer_name, n_repetitions): prob_comp, repetitions = 0, 0 p_computer = virus_probabilities[computer_name] while repetitions < n_repetitions: x = random.random() if x <= p_computer: prob_comp += 1 repetitions += 1 print ("{0} % changes of getting virus on {1}".format(round(prob_comp/n_repetitions, 2), computer_name))
这样做实际上会使概率更接近开始时的概率,随着n_repetitions越来越大,这是预期的。
虽然有关条件概率更具体的信息,您应该一定要查看这篇文章:Naive Bayes分类的简单解释
据我理解,您想要达到的目标是:
#python_test2.py import random, time virus_probabilities= { "CompA" : 0.50, "CompB" : .25, "CompC" : .25, "CompBD" : .125, "CompBE" : .125, "CompCD" : .125, "CompCE" : .125} def check_probability(computer_name, n_repetitions = 100): prob_comp, repetitions = 0, 0 p_computer = virus_probabilities[computer_name] while repetitions < n_repetitions: x = random.random() if x <= p_computer: prob_comp += 1 repetitions += 1 print ("{0} % chance of getting virus on {1}".format(round(prob_comp/100.0, 2), computer_name)) for key in virus_probabilities: check_probability(key, 1000)
当我从控制台运行文件时,我得到:
mabe@ubuntu:~/Desktop $ python test_2.py 2.49 % chance of getting virus on CompB 2.6 % chance of getting virus on CompC 5.07 % chance of getting virus on CompA 1.38 % chance of getting virus on CompBE 1.16 % chance of getting virus on CompBD 1.18 % chance of getting virus on CompCD 1.36 % chance of getting virus on CompCE