二维随机变量的联合熵和条件熵的Python实现

 

import math
import numpy as np
###########################################
'''统计数组中的不同数据及其出现次数'''
'''返回值:diffData,存储data中出现的不同数据'''
'''       diffDataNum, 存储不同数据的出现次数'''
###########################################
def StatDataInf( data ):

    dataArrayLen = len( data )
    diffData = [];
    diffDataNum = [];
    dataCpy = []
    for n in data:
        dataCpy.append( n )
    for i in range( dataArrayLen ):
        count = 0;
        j = i
        if( dataCpy[j] != '/' ):
            temp = dataCpy[i]
            diffData.append( temp )
            while( j < dataArrayLen ):
                if( dataCpy[j] == temp ):
                    count = count + 1
                    dataCpy[j] = '/'
       
  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我可以帮你解答这个问题。 首先,需要导入 math 和 collections 模块: ```python import math import collections ``` 然后,我们需要定义一个函数来计算互信息: ```python def mutual_information(word1, word2, corpus): word_freq = collections.Counter(corpus) bigram_freq = collections.Counter(zip(corpus[:-1], corpus[1:])) total_words = sum(word_freq.values()) p_word1 = word_freq[word1] / total_words p_word2 = word_freq[word2] / total_words p_word1_word2 = bigram_freq[(word1, word2)] / (total_words - 1) return math.log2(p_word1_word2 / (p_word1 * p_word2)) ``` 其中,参数 word1 和 word2 分别表示要计算互信息的两个词,参数 corpus 是语料库,是一个由词组成的列表。 接下来,我们需要定义一个函数来计算联合: ```python def joint_entropy(word1, word2, corpus): word_freq = collections.Counter(corpus) bigram_freq = collections.Counter(zip(corpus[:-1], corpus[1:])) total_words = sum(word_freq.values()) p_word1_word2 = bigram_freq[(word1, word2)] / (total_words - 1) return -math.log2(p_word1_word2) ``` 同样,参数 word1 和 word2 分别表示要计算联合的两个词,参数 corpus 是语料库。 最后,我们可以使用以下代码来测试我们的函数: ```python corpus = ['this', 'is', 'a', 'test', 'sentence', 'for', 'calculating', 'mutual', 'information', 'and', 'joint', 'entropy'] word1 = 'a' word2 = 'test' print(mutual_information(word1, word2, corpus)) print(joint_entropy(word1, word2, corpus)) ``` 这里的语料库是一个简单的例子,你可以根据你的需求替换为你的语料库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值