"""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()
本例需在 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。
入口文件:projects/ai-math-entropy-lab/entropy-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
entropy-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a53.zip