Appearance
demo_xor.py
复制以下内容并保存为 demo_xor.py,使用方法见配套代码说明。
python
"""示例:XOR —— 隐藏层如何表示非线性分类边界。
比较无隐藏层的逻辑回归与含一个隐藏层的 MLP。
"""
from nn import MLP
X = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]
Y = [[0.0], [1.0], [1.0], [0.0]]
def show(net, title):
print(f"\n{title}")
print(f" 参数量 = {net.n_params()}")
ok = True
for x, y in zip(X, Y):
p = net.predict(x)[0]
pred = 1.0 if p > 0.5 else 0.0
flag = "OK " if abs(pred - y[0]) < 1e-9 else "错 "
ok = ok and flag == "OK "
print(f" {x} 真值={y[0]:.0f} 预测={p:.4f} {flag}")
return ok
print("=" * 62)
print("XOR 问题:y = 1 当且仅当两个输入不同")
print("=" * 62)
# ---- 基线:没有隐藏层,[2, 1] 就是一个线性分类器 ----
linear = MLP([2, 1], hidden_activation="linear", output_activation="sigmoid",
loss="bce", seed=0)
hist_lin = linear.train(X, Y, epochs=8000, lr=1.0, batch_size=4, seed=0)
ok_lin = show(linear, "[基线] 无隐藏层 [2, 1]")
# ---- 多层:一个 4 神经元的隐藏层 ----
hidden = MLP([2, 4, 1], hidden_activation="tanh", output_activation="sigmoid",
loss="bce", seed=0)
hist_mlp = hidden.train(X, Y, epochs=8000, lr=0.5, batch_size=4, seed=1)
ok_mlp = show(hidden, "[多层] 一个隐藏层 [2, 4, 1]")
print("\n" + "-" * 62)
print(f"无隐藏层最终损失 : {hist_lin[-1]:.6f} (学不会)")
print(f"有隐藏层最终损失 : {hist_mlp[-1]:.6f} (学会了)")
print(f"无隐藏层是否全部正确 : {ok_lin}")
print(f"有隐藏层是否全部正确 : {ok_mlp}")
print("-" * 62)