计算条件概率 Python

Calculate Conditional Probability Python

我正在尝试使用分层树结构计算结果的概率

The top is computer Computer A, the next 2 are Computer B & C, and the last 4 are Computer BD, BE, and CD, CE. I am trying to find the probability that if computer A gets infected with a virus what is the probability that B or C gets infected with a virus. And if B or C gets infected what is the probability that BD, BE, CD, CE gets infected with a virus

我要运行试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???

据我了解,这就是您要实现的目标:

#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

来自 mabe02 的精彩代码,也许值得对核心功能添加非常小的改进,避免 confusion/future 错误:

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 会变大。

尽管要了解有关条件概率的更多细节,您绝对应该看看这个 post:A simple explanation of Naive Bayes Classification