"""仅依赖 NumPy 的两层二分类网络。"""
import numpy as np


def main():
    rng = np.random.default_rng(7)
    x = rng.normal(size=(256, 2))
    y = ((x[:, 0] * x[:, 1]) > 0).astype(np.float64)[:, None]
    w1 = rng.normal(scale=0.2, size=(2, 16)); b1 = np.zeros((1, 16))
    w2 = rng.normal(scale=0.2, size=(16, 1)); b2 = np.zeros((1, 1))

    for step in range(1000):
        h = np.tanh(x @ w1 + b1)
        logits = h @ w2 + b2
        p = 1 / (1 + np.exp(-np.clip(logits, -30, 30)))
        loss = -(y * np.log(p + 1e-8) + (1-y) * np.log(1-p + 1e-8)).mean()
        dz = (p - y) / len(x)
        dw2, db2 = h.T @ dz, dz.sum(0, keepdims=True)
        dh = dz @ w2.T
        da = dh * (1 - h*h)
        dw1, db1 = x.T @ da, da.sum(0, keepdims=True)
        w1 -= 0.1 * dw1; b1 -= 0.1 * db1
        w2 -= 0.1 * dw2; b2 -= 0.1 * db2
    accuracy = ((p >= 0.5) == y).mean()
    print(f"loss={loss:.4f} accuracy={accuracy:.3f}")


if __name__ == "__main__":
    main()

