Python 代码实现了一系列与贝叶斯网络相关的功能

python 复制代码
import sys

'''
WRITE YOUR CODE BELOW.
'''
 #想和大神交朋友或想软件开发兼职接项目,请通过手机端搜小#程#序: "黄页小艺"或公#众#号:"卧看星河"
from numpy import zeros, float32
#  pgmpy͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
import pgmpy
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
#You are not allowed to use following set of modules from 'pgmpy' Library.͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
#
# pgmpy.sampling.*͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
# pgmpy.factors.*͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
# pgmpy.estimators.*͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌

def make_security_system_net():
    """
        Create a Bayes Net representation of the above security system problem. 
        Use the following as the name attribute: "H","C", "M","B", "Q", 'K",
        "D"'. (for the tests to work.)
    """
    BayesNet = BayesianNetwork()
    BayesNet.add_edges_from([ # add relationships/dependencies
        ('H', 'Q'),   
        ('C', 'Q'),   
        ('M', 'K'),   
        ('B', 'K'),   
        ('Q', 'D'),   
        ('K', 'D')])

    #raise NotImplementedError
    return BayesNet


def set_probability(bayes_net):
    """
        Set conditional probability distribution (cpd) for each node in the security system.
        Use the following as the name attribute: "H","C", "M","B", "Q", 'K",
        "D"'. (for the tests to work.)
    """
    cpd_H = TabularCPD('H', 2, values=[[0.5], [0.5]]) 
    cpd_C = TabularCPD('C', 2, values=[[0.7], [0.3]])
    cpd_M = TabularCPD('M', 2, values=[[0.2], [0.8]])
    cpd_B = TabularCPD('B', 2, values=[[0.5], [0.5]])

    cpd_Q = TabularCPD('Q', 2, 
                       values = [[0.95, 0.75, 0.45, 0.1],  # false
                                 [0.05, 0.25, 0.55, 0.9]], # true 
                       evidence=['H', 'C'], evidence_card=[2, 2])
    cpd_K = TabularCPD('K', 2,
                       values=[[0.99, 0.85, 0.5, 0.25],  # false (safe) 
                               [0.01, 0.15, 0.5, 0.75]], # true 
                       evidence=['M', 'B'], evidence_card=[2, 2])
    cpd_D = TabularCPD('D', 2,
                       values=[[0.98, 0.35, 0.6, 0.01],  # false (fail to get files)
                               [0.02, 0.65, 0.4, 0.99]], # true (success tp get files)
                       evidence=['Q', 'K'], evidence_card=[2, 2])
    
    bayes_net.add_cpds(cpd_H, cpd_C, cpd_M, cpd_B, cpd_Q, cpd_K, cpd_D) # add cpd to the network
    assert bayes_net.check_model()
    #raise NotImplementedError    
    return bayes_net


def get_marginal_double0(bayes_net):
    """
        Calculate the marginal probability that Double-0 gets compromised.
    """
    # Create an inference object
    solver = VariableElimination(bayes_net)
    marginal_prob = solver.query(variables=['D'], joint=False) # marginal inference on the D node
    double0_prob = marginal_prob.values[1]  # extract the probability that D = True and index 1 corresponds to that

    #raise NotImplementedError
    return double0_prob


def get_conditional_double0_given_no_contra(bayes_net):
    """
        Calculate the conditional probability that Double-0 gets compromised
        given Contra is shut down.
    """
    solver = VariableElimination(bayes_net)
    conditional_prob = solver.query(variables=['D'], evidence={'C': 0}, joint=False)
    double0_prob = conditional_prob.values[1]
    # raise NotImplementedError
    return double0_prob


def get_conditional_double0_given_no_contra_and_bond_guarding(bayes_net):
    """
        Calculate the conditional probability that Double-0 gets compromised
        given Contra is shut down and Bond is reassigned to protect M.
    """
    solver = VariableElimination(bayes_net)
    conditional_prob = solver.query(variables=['D'], evidence={'C': 0, 'B': 1}, joint=False)
    double0_prob = conditional_prob.values[1]
    # raise NotImplementedError
    return double0_prob


def get_game_network():
    """
        Create a Bayes Net representation of the game problem.
        Name the nodes as "A","B","C","AvB","BvC" and "CvA".  
    """
    BayesNet = BayesianNetwork()
    # BayesNet.add_edges_from([ # add relationships/dependencies
    #     ('H', 'Q'),   
    #     ('C', 'Q'),   
    #     ('M', 'K'),   
    #     ('B', 'K'),   
    #     ('Q', 'D'),   
    #     ('K', 'D')])
    raise NotImplementedError    
    return BayesNet


def calculate_posterior(bayes_net):
    """
        Calculate the posterior distribution of the BvC match given that A won against B and tied C. 
        Return a list of probabilities corresponding to win, loss and tie likelihood.
    """
    posterior = [0,0,0]
    # TODO: finish this function͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌    
    raise NotImplementedError
    return posterior # list 


def Gibbs_sampler(bayes_net, initial_state):
    """
        Complete a single iteration of the Gibbs sampling algorithm 
        given a Bayesian network and an initial state value. 
        
        initial_state is a list of length 6 where: 
        index 0-2: represent skills of teams A,B,C (values lie in [0,3] inclusive)
        index 3-5: represent results of matches AvB, BvC, CvA (values lie in [0,2] inclusive)
        
        Returns the new state sampled from the probability distribution as a tuple of length 6.
        Return the sample as a tuple. 

        Note: You are allowed to calculate the probabilities for each potential variable
        to be sampled. See README for suggested structure of the sampling process.
    """
    sample = tuple(initial_state)    
    # TODO: finish this function͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌

    variable_index = None # Your chosen variable

    if variable_index == 0:
        # Sample A͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
        raise NotImplementedError
    elif variable_index == 1:
        # Sample B͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
        raise NotImplementedError
    elif variable_index == 2:
        # Sample C͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
        raise NotImplementedError

    elif variable_index == 4:
        # Sample BvC͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
        raise NotImplementedError
    
    else:
        raise ValueError("Variable index out of range")


    return sample


def MH_sampler(bayes_net, initial_state):
    """
        Complete a single iteration of the MH sampling algorithm given a Bayesian network and an initial state value. 
        initial_state is a list of length 6 where: 
        index 0-2: represent skills of teams A,B,C (values lie in [0,3] inclusive)
        index 3-5: represent results of matches AvB, BvC, CvA (values lie in [0,2] inclusive)    
        Returns the new state sampled from the probability distribution as a tuple of length 6. 
    """
    A_cpd = bayes_net.get_cpds("A")      
    AvB_cpd = bayes_net.get_cpds("AvB")
    match_table = AvB_cpd.values
    team_table = A_cpd.values
    sample = tuple(initial_state)    
    # TODO: finish this function͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
    raise NotImplementedError    
    return sample


def compare_sampling(bayes_net, initial_state):
    """
        Compare Gibbs and Metropolis-Hastings sampling by calculating how long it takes for each method to converge.
    """    
    Gibbs_count = 0
    MH_count = 0
    MH_rejection_count = 0
    Gibbs_convergence = [0,0,0] # posterior distribution of the BvC match as produced by Gibbs 
    MH_convergence = [0,0,0] # posterior distribution of the BvC match as produced by MH
    # TODO: finish this function͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
    raise NotImplementedError        
    return Gibbs_convergence, MH_convergence, Gibbs_count, MH_count, MH_rejection_count


def sampling_question():
    """
        Question about sampling performance.
    """
    # TODO: assign value to choice and factor͏︅͏︀͏︋͏︋͏󠄌͏󠄎͏󠄋͏󠄊͏󠄏͏︌
    raise NotImplementedError
    choice = 2
    options = ['Gibbs','Metropolis-Hastings']
    factor = 0
    return options[choice], factor


def return_your_name():
    """
        Return your name from this function
    """
    return "Jinglin Xu"
    #raise NotImplementedError
  #想和大神交朋友或想软件开发兼职接项目,请通过手机端搜小#程#序: "黄页小艺"或公#众#号:"卧看星河"

这段 Python 代码实现了一系列与贝叶斯网络相关的功能,主要包括以下几个方面:

一、贝叶斯网络构建与设置

  1. 构建安全系统贝叶斯网络

    • make_security_system_net函数创建了一个表示安全系统的贝叶斯网络,定义了节点之间的依赖关系,包括"黑客攻击(H)""反情报机构(C)""军情六处被攻击(M)""邦德保护军情六处(B)""黑客获取文件(Q)""克格勃获取文件(K)""双重间谍被暴露(D)"等节点,并添加了相应的边表示依赖关系。

    • set_probability函数为安全系统贝叶斯网络中的每个节点设置条件概率分布(CPD)。例如,为"黑客攻击(H)""反情报机构(C)"等节点设置了二值分布,为"黑客获取文件(Q)""克格勃获取文件(K)""双重间谍被暴露(D)"等节点设置了基于其依赖节点的条件概率分布。

  2. 构建游戏贝叶斯网络(未完全实现)

    • get_game_network函数被定义用于创建一个表示游戏问题的贝叶斯网络,但目前仅抛出了NotImplementedError,说明该功能尚未实现。

二、概率计算

  1. 安全系统相关概率计算

    • get_marginal_double0函数使用变量消除法计算双重间谍被暴露的边际概率。
    • get_conditional_double0_given_no_contra函数计算在反情报机构关闭的条件下双重间谍被暴露的条件概率。
    • get_conditional_double0_given_no_contra_and_bond_guarding函数计算在反情报机构关闭且邦德被重新分配去保护军情六处的条件下双重间谍被暴露的条件概率。
  2. 游戏问题相关概率计算(未完全实现)

    • calculate_posterior函数被定义用于计算在给定特定比赛结果的情况下,某场比赛的后验分布,但目前仅抛出了NotImplementedError,说明该功能尚未实现。

三、采样算法

  1. Gibbs 采样

    • Gibbs_sampler函数实现了 Gibbs 采样算法的一次迭代。给定一个贝叶斯网络和初始状态,通过选择一个变量,根据当前状态下其他变量的值,从该变量的条件分布中采样一个新的值,然后返回更新后的状态作为一个元组。但目前函数中大部分内容抛出了NotImplementedError,说明该功能尚未完全实现。
  2. Metropolis-Hastings 采样(未完全实现)

    • MH_sampler函数被定义用于实现 Metropolis-Hastings 采样算法的一次迭代,但目前仅抛出了NotImplementedError,说明该功能尚未实现。
  3. 采样算法比较(未完全实现)

    • compare_sampling函数被定义用于比较 Gibbs 采样和 Metropolis-Hastings 采样算法的收敛速度,但目前仅抛出了NotImplementedError,说明该功能尚未实现。
  4. 采样问题回答(未完全实现)

    • sampling_question函数被定义用于回答关于采样性能的问题,但目前仅抛出了NotImplementedError,说明该功能尚未实现。

四、返回名字

  • return_your_name函数返回一个名字字符串。

总体来说,这段代码旨在构建和操作贝叶斯网络,实现概率计算和采样算法,以解决特定的概率推理问题,但目前许多功能尚未完全实现。

#想和大神交朋友或想软件开发兼职接项目,请通过手机端搜小#程#序: "黄页小艺" 。

相关推荐
leaf_leaves_leaf4 分钟前
win11用一条命令给anaconda环境安装GPU版本pytorch,并检查是否为GPU版本
人工智能·pytorch·python
夜雨飘零110 分钟前
基于Pytorch实现的说话人日志(说话人分离)
人工智能·pytorch·python·声纹识别·说话人分离·说话人日志
404NooFound17 分钟前
Python轻量级NoSQL数据库TinyDB
开发语言·python·nosql
天天要nx28 分钟前
D102【python 接口自动化学习】- pytest进阶之fixture用法
python·pytest
minstbe29 分钟前
AI开发:使用支持向量机(SVM)进行文本情感分析训练 - Python
人工智能·python·支持向量机
落魄实习生1 小时前
AI应用-本地模型实现AI生成PPT(简易版)
python·ai·vue·ppt
苏言の狗1 小时前
Pytorch中关于Tensor的操作
人工智能·pytorch·python·深度学习·机器学习
用余生去守护1 小时前
python报错系列(16)--pyinstaller ????????
开发语言·python
数据小爬虫@1 小时前
利用Python爬虫快速获取商品历史价格信息
开发语言·爬虫·python
是Dream呀2 小时前
Python从0到100(七十八):神经网络--从0开始搭建全连接网络和CNN网络
网络·python·神经网络