信息熵计算及代码

该博客介绍了如何使用Python进行离散信源数学模型的构建,计算信息熵,并通过matplotlib绘制字母出现概率的柱状图。内容涉及信息熵的物理含义、计算方法以及其在衡量信源不确定性中的作用。通过示例文本,展示了如何统计字母出现频率并计算信息熵,最后展示了一个可视化结果。
摘要由CSDN通过智能技术生成

实验目的:了解离散信源数学模型和信息熵
实验内容:以附件中英文文本文件中的内容为来源,构建26个英文字母(区分大小写)为信源符号的数学模型,要求输出字母的概率和该模型的信息熵。
要求:请使用自己熟悉的编程语言,完成信源建模,输出英文字母的概率和信源的信息熵。

使用python编写,最后输出相应柱状图,展示出字母的输出概率。

  • 等消息个数信源,消息概率分布差异大,信源熵小,不确定程度小;消息等概分布,信源熵大,不确定程度大。
  • 消息等概分布,消息个数多,信源熵大,不确定程度大。

信源熵有三种物理含义:

  • 信源熵H(X)表示信源输出后,离散消息所提供的平均信息量。
  • 信源熵H(X)表示信源输出前,信源的平均不确定度。
  • 信源熵H(X)反映了变量X的随机性。
     

信息熵计算过程为:

for i in dict3:
    if dict3[i] != 0:
        sum1 += dict3[i] * (math.log(1 / (dict3[i]), 2))

全部代码如下所示:

import string
import matplotlib.pyplot as plt
import math


def draw_from_dict(dicdata, RANGE, heng=0):
    # dicdata:字典的数据。
    # RANGE:截取显示的字典的长度。
    # heng=0,代表条状图的柱子是竖直向上的。heng=1,代表柱子是横向的。考虑到文字是从左到右的,让柱子横向排列更容易观察坐标轴。
    by_value = sorted(dicdata.items(), key=lambda item: item[0], reverse=False)
    x = []
    y = []
    plt.xlabel("Sequential letters")
    plt.ylabel("Probability of occurrence of each letter")
    plt.title("Character probability statistics")
    for xx, yy in zip(dicdata.keys(), dicdata.values()):
        # plt.text(xx, yy + 0.1, str(yy), ha='center')
        if yy != 0:
            plt.text(xx, yy, '%.3f' % yy, ha='center', va='bottom', fontsize=5)
    for d in by_value:
        x.append(d[0])
        y.append(d[1])
    if heng == 0:
        plt.bar(x[0:RANGE], y[0:RANGE])
        plt.show()
        return
    elif heng == 1:
        plt.barh(x[0:RANGE], y[0:RANGE])
        plt.show()
        return
    else:
        return "heng的值仅为0或1!"


def countLetters(string):
    s_count = 0
    for i in s:
        if i.isalpha():
            s_count += 1
    print('字母的个数有:', s_count, '个')
    return s_count


s = 'Love is a set of emotions and behaviors characterized by intimacy, passion, and commitment. It involves care, ' \
    'closeness, protectiveness, attraction, affection, and trust. Love can vary in intensity and can change over ' \
    'time. It is associated with a range of positive emotions, including happiness, excitement, life satisfaction, ' \
    'and euphoria, but it can also result in negative emotions such as jealousy and stress. '
letterSum = countLetters(s)
print(letterSum)
asciiAll = string.ascii_lowercase + string.ascii_uppercase
dict3 = {key: 0.0 for key in asciiAll}
for x in s:
    if x.isalpha():
        dict3[x] = round(s.count(x) / letterSum, 6)

for i in sorted(dict3):
    print((i, dict3[i]), end="\n")
sum1 = 0
for i in dict3:
    if dict3[i] != 0:
        sum1 += dict3[i] * (math.log(1 / (dict3[i]), 2))

print('计算出的熵是', round(sum1, 4))

draw_from_dict(dict3, 52, 0)

通过matplotlib包输出可视化图形,输出的柱状图如下

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个用MATLAB计算样本信息熵的示例代码: ```matlab % 假设有一个样本数据矩阵,每一行代表一个样本,每一列代表一个特征 sample_data = [1, 2, 1; 2, 1, 0; 1, 1, 0; 2, 1, 1; 1, 3, 1; 2, 2, 0]; % 获取样本总数 total_samples = size(sample_data, 1); % 获取样本标签,假设在最后一列 labels = sample_data(:, end); % 统计每个类别出现的次数 unique_labels = unique(labels); class_counts = zeros(length(unique_labels), 1); for i = 1:length(unique_labels) class_counts(i) = sum(labels == unique_labels(i)); end % 计算样本信息熵 sample_entropy = 0; for i = 1:length(class_counts) p = class_counts(i) / total_samples; sample_entropy = sample_entropy - p * log2(p); end disp(['样本信息熵为:', num2str(sample_entropy)]); ``` 以上代码假设样本数据矩阵`sample_data`有3列,每列分别表示一个特征,最后一列为样本标签。首先,通过`size`函数获取样本总数,然后通过取最后一列获取样本标签。接下来,使用`unique`函数获取不同的标签值,并使用`sum`函数统计每个标签出现的次数。最后,根据信息熵计算公式,求取各个类别的概率,并根据熵的定义进行计算,最后显示样本信息熵的值。 ### 回答2: 下面是样本信息熵计算的Matlab代码示例: ```matlab % 输入样本数据 samples = [0 1 0 1 1 0 0 0 1 1]; % 计算样本总数 total_samples = length(samples); % 计算样本分布概率 prob_samples = histcounts(samples, [0 1]) / total_samples; % 去除概率值的零元素 non_zero_prob_samples = prob_samples(prob_samples > 0); % 计算信息熵 info_entropy = -sum(non_zero_prob_samples .* log2(non_zero_prob_samples)); % 显示结果 disp(['样本信息熵:' num2str(info_entropy)]); ``` 代码首先输入样本数据,这里的样本数据是一个包含二分类标签的向量。然后计算总样本数和样本分布概率。下一步,代码将零概率值从概率值去除,并计算信息熵。最后,代码会显示计算得到的样本信息熵。 需要注意的是,这里使用的是二分类标签,因此样本只能取值0或1。如果数据还包含其他取值,你需要根据实际情况修改代码的样本取值范围和计算方法。 ### 回答3: 以下是使用MATLAB计算样本信息熵代码: ```matlab % 假设样本数据存储在变量data,每个样本的标签存储在变量labels % 计算样本数目 num_samples = length(labels); % 计算每个标签出现的频率 unique_labels = unique(labels); % 获取所有不同的标签值 label_frequency = zeros(size(unique_labels)); % 初始化标签频率为0向量 for i = 1:length(unique_labels) label_frequency(i) = sum(labels == unique_labels(i)); % 统计每个标签出现的次数 end % 计算每个标签的概率 label_probability = label_frequency / num_samples; % 计算样本信息熵 entropy = -sum(label_probability .* log2(label_probability)); ``` 这段代码首先通过计算标签的频率来得到每个标签的概率。然后,使用这些概率计算样本信息熵,即每个标签概率的负和。最后,将计算得到的样本信息熵保存在变量`entropy`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值