"""Contrast probability losses and verify selected PyTorch classification calls."""
import argparse
import json
from math import exp, inf, isclose, isinf, log
import platform
def cross_entropy(target, predicted):
if any(p > 0 and q == 0 for p,q in zip(target,predicted,strict=True)):
return inf
return -sum(p*log(q) for p,q in zip(target,predicted,strict=True) if p > 0)
def from_logits(scores,target):
shift = max(scores)
scores = [value-shift for value in scores]
total = log(sum(exp(value) for value in scores))
return -sum(p*(value-total) for p,value in zip(target,scores,strict=True))
def main():
cli=argparse.ArgumentParser()
cli.add_argument("--torch",action="store_true")
args=cli.parse_args()
cases=[]
versions={}
def record(name, operation, inputs, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
y=[1.,0.,0.]
guesses=[[.33,.33,.34],[.5,.3,.2],[.7,.2,.1],[.9,.07,.03],[.98,.01,.01],[.02,.9,.08]]
record("six_probability_losses","evaluate six three-class predictions at the same hard target",
guesses,[1.108663,.693147,.356675,.105361,.020203,3.912023],
[round(cross_entropy(y,p),6) for p in guesses])
squared=[(a-b)**2 for a,b in zip(y,guesses[-1],strict=True)]
record("mse_uses_all_classes","compare true-class square, class MSE and full loss ratio",
guesses[-1],[.9604,.592267,6.60517],[round(squared[0],4),round(sum(squared)/3,6),
round(cross_entropy(y,guesses[-1])/(sum(squared)/3),5)])
record("zero_probability_has_limits","check zero weight terms and zero predicted mass on positive target",
[[1,0,0],[0,1,0]], [0.,True], [cross_entropy(y,[1,0,0]),isinf(cross_entropy(y,[0,1,0]))])
record("logits_stable_under_shifts","evaluate equal logits and very large common offsets",
[10000.,10000.,10000.], [True,True],
[isclose(from_logits([10000.]*3,y),log(3)),isclose(from_logits([-1000.,1000.,0.],y),2000.)])
smooth=[.6,.3,.1]
record("soft_label_uses_all_probability","compare deterministic and soft labels on equal prediction",
smooth,True,cross_entropy(smooth,smooth)>0.)
if args.torch:
import torch
import torch.nn.functional as F
versions["torch"]=torch.__version__
raw=[[3.,1.,0.],[1.,2.,-1.],[-1000.,1000.,0.]]
logits=torch.tensor(raw,dtype=torch.float64)
labels=torch.tensor([0,1,0])
expected=[from_logits(row,[float(i==label) for i in range(3)]) for row,label in zip(raw,labels.tolist())]
observed=F.cross_entropy(logits,labels,reduction="none").tolist()
record("torch_hard_targets","run unreduced classification losses with integral labels",
labels.tolist(),True,all(isclose(p,q) for p,q in zip(expected,observed,strict=True)))
pad=torch.tensor([0,-100,0])
each=F.cross_entropy(logits,pad,ignore_index=-100,reduction="none")
total=F.cross_entropy(logits,pad,ignore_index=-100,reduction="sum").item()
average=F.cross_entropy(logits,pad,ignore_index=-100,reduction="mean").item()
record("ignore_padding_and_reduce","omit the padded token and compare both reductions",
pad.tolist(),[True,True,True],[each[1].item()==0,isclose(total,each.sum().item()),isclose(average,total/2)])
target=torch.tensor(smooth,dtype=torch.float64)
loss=F.cross_entropy(logits[0],target).item()
record("torch_soft_targets","use teacher class weights as a full target distribution",
smooth,True,isclose(loss,from_logits(raw[0],smooth)))
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__=="__main__":
main()
本例需在 Windows、Python 3.12.14。torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。torch 2.10.0+cpu。
入口文件:projects/ai-math-cross-entropy-lab/compare-label-losses.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
compare-label-losses.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a45.zip