"""Independent pure-NumPy neural network structure lab: neuron, activations, nonlinearity collapse, 2-3-1 forward & task heads."""
import json
import platform
import numpy as np
def sigmoid(z: np.ndarray | float):
z_arr = np.asarray(z, dtype=np.float64)
return 1.0 / (1.0 + np.exp(-z_arr))
def relu(z: np.ndarray | float):
return np.maximum(0.0, z)
def softmax(z: np.ndarray, axis: int = 0) -> np.ndarray:
shifted = z - np.max(z, axis=axis, keepdims=True)
exp_z = np.exp(shifted)
return exp_z / np.sum(exp_z, axis=axis, keepdims=True)
def initialize_network(input_size: int, hidden_size: int, output_size: int, seed: int = 42):
np.random.seed(seed)
return dict(
W1=np.random.randn(hidden_size, input_size) * 0.01,
b1=np.zeros((hidden_size, 1)),
W2=np.random.randn(output_size, hidden_size) * 0.01,
b2=np.zeros((output_size, 1)),
)
def forward_propagation(network: dict, X: np.ndarray):
W1, b1, W2, b2 = network["W1"], network["b1"], network["W2"], network["b2"]
Z1 = np.dot(W1, X) + b1
A1 = relu(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
cache = dict(Z1=Z1, A1=A1, Z2=Z2, A2=A2)
return A2, cache
def run_cases():
cases = []
# 1. Artificial neuron weighted sum + Sigmoid / ReLU / Softmax properties
inputs = [1.5, -0.5, 2.0]
weights = [0.4, -0.8, 0.5]
bias = -0.3
z_val = sum(x * w for x, w in zip(inputs, weights)) + bias # 0.6 + 0.4 + 1.0 - 0.3 = 1.7
sig_val = float(sigmoid(z_val))
sig_sat_deriv = float(sigmoid(10.0) * (1.0 - sigmoid(10.0)))
relu_vals = relu(np.array([-3.0, 0.0, 2.5])).tolist()
logits = np.array([[2.0], [1.0], [0.1]])
sm = softmax(logits, axis=0)
sm_shifted = softmax(logits + 1000.0, axis=0)
sm_shift_diff = float(np.max(np.abs(sm - sm_shifted)))
c1_ok = (
abs(z_val - 1.7) < 1e-12
and 0.0 < sig_val < 1.0
and sig_sat_deriv < 1e-4
and relu_vals == [0.0, 0.0, 2.5]
and abs(float(sm.sum()) - 1.0) < 1e-12
and sm_shift_diff < 1e-12
)
cases.append(dict(
name="single_neuron_and_activation_functions",
inputs=dict(x=inputs, w=weights, b=bias, softmax_logits=[2.0, 1.0, 0.1]),
prerequisites="人工神经元加权求和加偏置及 Sigmoid、ReLU、Softmax 数值特性校验",
action="验证神经元 z=1.7、Sigmoid 在 z=10 处梯度饱和 (<1e-4)、ReLU 负截断正恒等以及 Softmax 归一化与平移不变性。",
expected=dict(z_exact=True, sigmoid_saturates=True, relu_piecewise=True, softmax_valid=True),
actual=dict(
z_exact=(abs(z_val - 1.7) < 1e-12),
sigmoid_saturates=(sig_sat_deriv < 1e-4),
relu_piecewise=(relu_vals == [0.0, 0.0, 2.5]),
softmax_valid=(abs(float(sm.sum()) - 1.0) < 1e-12 and sm_shift_diff < 1e-12),
),
measurements=dict(
z=round(z_val, 4),
sigmoid_z=round(sig_val, 6),
sigmoid_deriv_at_10=round(sig_sat_deriv, 8),
softmax_probs=[round(float(v), 4) for v in sm[:, 0]],
),
passed=c1_ok,
))
# 2. Why nonlinearity is essential: linear multi-layer collapses vs ReLU MLP solves XOR
rng = np.random.default_rng(7)
W1 = rng.normal(size=(4, 2))
b1 = rng.normal(size=(4, 1))
W2 = rng.normal(size=(1, 4))
b2 = rng.normal(size=(1, 1))
X_xor = np.array([[0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0]])
y_xor = np.array([[0.0, 1.0, 1.0, 0.0]])
two_linear = W2 @ (W1 @ X_xor + b1) + b2
collapsed = (W2 @ W1) @ X_xor + (W2 @ b1 + b2)
collapse_err = float(np.max(np.abs(two_linear - collapsed)))
# Construct exact 2-2-1 ReLU MLP solving XOR: h1=ReLU(x1+x2-0.5), h2=ReLU(x1+x2-1.5), y=2*h1-6*h2
W1_xor = np.array([[1.0, 1.0], [1.0, 1.0]])
b1_xor = np.array([[-0.5], [-1.5]])
W2_xor = np.array([[2.0, -6.0]])
b2_xor = np.array([[0.0]])
xor_out = W2_xor @ relu(W1_xor @ X_xor + b1_xor) + b2_xor
xor_preds = (xor_out >= 0.5).astype(int)
xor_acc = float(np.mean(xor_preds == y_xor.astype(int)))
# Best possible linear threshold classifier on XOR cannot achieve 100% (max 3/4 = 0.75)
# Least-squares affine fit on XOR predicts constant 0.5
X_aug = np.vstack([X_xor, np.ones((1, 4))]).T
w_lin, *_ = np.linalg.lstsq(X_aug, y_xor.ravel(), rcond=None)
lin_mse = round(float(np.mean((X_aug @ w_lin - y_xor.ravel()) ** 2)), 4)
c2_ok = collapse_err < 1e-13 and xor_acc == 1.0 and lin_mse == 0.25
cases.append(dict(
name="nonlinearity_prevents_layer_collapse",
inputs=dict(task="XOR", linear_layers=2, relu_hidden=2),
prerequisites="验证无激活函数多层线性网络代数退化为单层,而加入 ReLU 隐藏层可精确求解非线性 XOR",
action="确认两层线性映射与单层等价矩阵最大误差 <1e-13(XOR 最小二乘 MSE 恒为 0.25),而 2-2-1 ReLU 网络 4 点全对。",
expected=dict(linear_collapses=True, linear_xor_mse=0.25, relu_xor_acc=1.0),
actual=dict(linear_collapses=(collapse_err < 1e-13), linear_xor_mse=lin_mse, relu_xor_acc=xor_acc),
measurements=dict(
collapse_max_err=round(collapse_err, 15),
relu_xor_outputs=[round(float(v), 4) for v in xor_out.ravel()],
),
passed=c2_ok,
))
# 3. Exact 2-3-1 NumPy forward propagation from source (seed=42, X=[[1.5], [-0.5]])
net = initialize_network(input_size=2, hidden_size=3, output_size=1, seed=42)
X_sample = np.array([[1.5], [-0.5]])
y_pred, cache = forward_propagation(net, X_sample)
pred_prob = round(float(y_pred[0, 0]), 6)
pred_cls = 1 if pred_prob > 0.5 else 0
# Batch forward check: 8 samples (2, 8) -> (1, 8)
X_batch = np.random.default_rng(42).normal(size=(2, 8))
y_batch, _ = forward_propagation(net, X_batch)
c3_ok = (
net["W1"].shape == (3, 2)
and net["b1"].shape == (3, 1)
and net["W2"].shape == (1, 3)
and net["b2"].shape == (1, 1)
and set(cache.keys()) == {"Z1", "A1", "Z2", "A2"}
and 0.49 < pred_prob < 0.51
and y_batch.shape == (1, 8)
)
cases.append(dict(
name="three_layer_2_3_1_forward_propagation",
inputs=dict(arch="2-3-1", seed=42, sample=[1.5, -0.5], batch_size=8),
prerequisites="核对来源 2-3-1 三层 NumPy 网络参数矩阵形状、中间缓存与前向传播输出",
action="验证 W1=(3,2)、W2=(1,3)、缓存 Z1/A1/Z2/A2 完整、未训练输出 A2 接近 0.5 且支持 (2,8)->(1,8) 批量前向。",
expected=dict(param_shapes_exact=True, prob_near_05=True, batch_shape=[1, 8]),
actual=dict(
param_shapes_exact=(net["W1"].shape == (3, 2) and net["b1"].shape == (3, 1) and net["W2"].shape == (1, 3)),
prob_near_05=(0.49 < pred_prob < 0.51),
batch_shape=list(y_batch.shape),
),
measurements=dict(
z1=[round(float(v), 6) for v in cache["Z1"].ravel()],
a1=[round(float(v), 6) for v in cache["A1"].ravel()],
z2=round(float(cache["Z2"][0, 0]), 6),
a2_prob=pred_prob,
predicted_class=pred_cls,
),
passed=c3_ok,
))
# 4. Input flattening (28x28 -> 784) & output-layer heads for binary, K-class, and regression
img_28 = np.zeros((28, 28), dtype=np.float64)
flat_dim = int(img_28.reshape(-1, 1).shape[0])
H = np.random.default_rng(123).normal(size=(16, 5)) # hidden features for 5 samples
rng_h = np.random.default_rng(124)
out_bin = sigmoid(rng_h.normal(size=(1, 16)) @ H)
out_multi = softmax(rng_h.normal(size=(4, 16)) @ H, axis=0)
out_reg = rng_h.normal(size=(1, 16)) @ H - 2.5
bin_ok = bool(out_bin.shape == (1, 5) and np.all((out_bin > 0.0) & (out_bin < 1.0)))
multi_ok = bool(out_multi.shape == (4, 5) and np.allclose(out_multi.sum(axis=0), 1.0))
reg_ok = bool(out_reg.shape == (1, 5) and (float(out_reg.min()) < 0.0 or float(out_reg.max()) > 1.0))
c4_ok = flat_dim == 784 and bin_ok and multi_ok and reg_ok
cases.append(dict(
name="layer_architectures_for_task_heads",
inputs=dict(image_shape=[28, 28], batch=5, multiclass_k=4),
prerequisites="核对输入层展平维度(28x28->784)及二分类/多分类/回归三种输出层激活约束",
action="验证二分类 Sigmoid 落在 (0,1)、4 分类 Softmax 列和恒为 1.0、回归线性输出不受区间限制。",
expected=dict(flat_dim=784, binary_head_ok=True, multiclass_head_ok=True, regression_head_ok=True),
actual=dict(flat_dim=flat_dim, binary_head_ok=bin_ok, multiclass_head_ok=multi_ok, regression_head_ok=reg_ok),
measurements=dict(
multiclass_col_sums=[round(float(v), 6) for v in out_multi.sum(axis=0)],
regression_range=[round(float(out_reg.min()), 4), round(float(out_reg.max()), 4)],
),
passed=c4_ok,
))
payload = dict(
version=platform.python_version(),
numpy=np.__version__,
system=platform.system(),
cases=cases,
)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/ml-structure-of-neural-networks-lab/explore-structure-of-neural-networks.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-structure-of-neural-networks.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a501.zip