信息量与熵
用概率、对数和区间图解释自信息、离散熵及其在模型中的用法。
学完这一章,你能够
- 用概率、对数和区间图解释自信息、离散熵及其在模型中的用法。
一次事件的自信息
概率 p>0 的事件发生时,自信息是 −logᵦ p,底数 b>1。概率越小,自信息越大。底数 2 的单位为比特,自然对数的单位为纳特。比如概率 1/8 的事件提供 3 比特,概率为零时按极限自信息趋于无穷。
两个独立事件同时发生,联合概率是各自概率的乘积,因此自信息相加。概率为 1 的事件提供零自信息。新闻例子可比较概率差异,例如罕见事件的出现比几乎确定的事件更出人意料;自信息按概率计算。
把概率加权后的信息量相加
离散熵 H=−∑pᵢ logᵦ pᵢ,零质量项按极限记为零。固定 K 个可能类别时,确定分布熵最小为 0,均匀分布熵最大为 logᵦ K。自然对数下,二类均匀约为 0.693147,十类均匀约为 2.302585,[0.9,0.05,0.05] 约为 0.394398 纳特。
二分类 H(p) 对 p 与 1−p 对称。离线曲线包括 p=0 与 p=1,两端熵为零;p=1/2 时峰值为 1 比特或 ln 2 纳特。切换单位改变纵轴数值。
分裂、分类损失和探索
决策树计算信息增益时,从父节点熵减去子节点熵的加权和,权重是落入各子节点的样本比例。ID3 常以信息增益选择分裂,C4.5 引入增益率。实验用 scikit-learn 的熵分裂核对一棵深度为 1 的树。
在固定目标分布 p 下,交叉熵 H(p,q)=H(p)+KL(p‖q),因此两个目标的最小化一致。仅当 p 是独热分布时 H(p)=0,交叉熵等于从 p 到 q 的 KL。一般软标签保留 H(p)。
SAC 在最大熵强化学习中结合期望回报与策略熵,系数 α 调节熵项的权重。这个权重会改变探索偏好。本站比较两个已给定策略的一步目标,完整 SAC 还包括策略、价值估算和状态采样。
预测熵只描述模型给出的概率分散程度。校准需比较预测置信度和真实命中率。有两个都报 0.9 的组,其预测熵相同,观测命中率却可以是 0.9 和 0.2。分布外样本也可能收到高置信预测,需要额外评估。
从自信息到分裂增益与策略熵
展开查看收起
"""Measure self-information, Shannon entropy, and weighted split gain."""
import json
from math import isclose,isfinite,log
import platform
import numpy as np
import sklearn
from sklearn.tree import DecisionTreeClassifier
def entropy(probabilities,base):
if base<=1 or not isfinite(base) or any(p<0 or not isfinite(p) for p in probabilities):
raise ValueError("invalid log base or probability")
if not isclose(sum(probabilities),1.,rel_tol=0,abs_tol=1e-12):
raise ValueError("probabilities must sum to one")
return -sum(p*log(p,base) for p in probabilities if p)
def main():
cases=[]
def check(name,inputs,expected,actual,operation):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
steps=[1.,.5,.25,.125]
check("rarer_event_more_bits",steps,[0,1,2,3],[round(-log(p,2),8) for p in steps],"evaluate surprisal at four event masses")
check("independent_information_adds",[.5,.25],[3,3],
[round(-log(.5*.25,2)),round(-log(.5,2)-log(.25,2))],"compare joint and summed information")
distributions=[[1,0,0],[.5,.5],[.1]*10,[.9,.05,.05]]
check("four_example_entropies",distributions,[0,.693147,2.302585,.394398],
[round(entropy(p,np.e),6) for p in distributions],"compute Shannon entropy in nats")
check("entropy_bound_for_four_classes",[[1,0,0,0],[.25]*4,[.4,.3,.2,.1]],[0,2,True],
[entropy([1,0,0,0],2),entropy([.25]*4,2),0<entropy([.4,.3,.2,.1],2)<2],
"compare deterministic, uniform, and unequal four-class distributions")
rejected=0
for probabilities,base in (([.5,.7],2),([-.1,1.1],2),([.5,.5],1)):
try:
entropy(probabilities,base)
except ValueError:
rejected+=1
check("invalid_input_rejected",["unnormalized","negative","base=1"],3,rejected,"check probability and base constraints")
check("binary_curve_symmetry_and_peak",[.1,.5,.9],[True,1],
[isclose(entropy([.1,.9],2),entropy([.9,.1],2)),entropy([.5,.5],2)],
"compare complementary probabilities and the midpoint")
features=[[0,0],[0,1],[0,1],[1,0],[1,0],[1,1]]
labels=[0,0,0,1,0,1]
model=DecisionTreeClassifier(criterion="entropy",max_depth=1,random_state=4).fit(features,labels)
tree=model.tree_
counts=tree.weighted_n_node_samples
gain=tree.impurity[0]-(counts[1]*tree.impurity[1]+counts[2]*tree.impurity[2])/counts[0]
expected_gain=entropy([2/3,1/3],2)/2
check("decision_tree_weighted_information_gain",{"features":features,"labels":labels},[0,True],
[int(tree.feature[0]),isclose(gain,expected_gain,abs_tol=1e-12)],
"fit a depth-one entropy tree and compare weighted child impurity")
p=[.75,.25]
q=[.5,.5]
cross=lambda a,b: -sum(x*log(y) for x,y in zip(a,b,strict=True) if x>0)
kl=sum(x*log(x/y) for x,y in zip(p,q,strict=True))
check("entropy_plus_kl_is_cross_entropy",{"p":p,"q":q},[True,True],
[isclose(cross(p,q),entropy(p,np.e)+kl),isclose(cross([1,0],q),-log(.5))],
"check both soft targets and one-hot targets")
scores=[[(1-mass)+alpha*entropy([mass,1-mass],np.e) for mass in (0,.5)] for alpha in (.1,1.)]
check("entropy_bonus_changes_policy_preference",{"alphas":[.1,1.],"candidate_policies":[[0,1],[.5,.5]]},[0,1],
[int(np.argmax(row)) for row in scores],"compare two policies for a one-step reward plus entropy objective")
predicted_entropy=entropy([.9,.1],2)
check("fixed_entropy_can_hide_miscalibration",{"predicted_probabilities":[.9,.1],"group_correct_counts":[9,2]},
[True,.7],[isclose(predicted_entropy,entropy([.9,.1],2)),round(abs(.9-.2),8)],
"assign identical confidence to two groups whose observed accuracy differs")
print(json.dumps(dict(version=platform.python_version(),
library_versions={"numpy":np.__version__,"sklearn":sklearn.__version__},cases=cases)))
if __name__=="__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
复跑实验
解压后按 README 运行自编程序。
本章附件与实例包
常见错误与边界检查
- 先检查概率质量是否归一化。
- 比较多个熵值时统一对数底。
技术规范与官方资料
练习与参考解答
查看参考解答
−log₂(0.25)=2 比特。