神经网络的基本结构
核对人工神经元部件与加权求和、Sigmoid/ReLU/Softmax 激活特性、无非线性多层退化证明、三层层级拓扑与 2-3-1 NumPy 前向传播实测。
学完这一章,你能够
- 核对人工神经元部件与加权求和、Sigmoid/ReLU/Softmax 激活特性、无非线性多层退化证明、三层层级拓扑与 2-3-1 NumPy 前向传播实测。
神经网络直觉与人工神经元计算单元
人工神经网络受生物神经连接启发,是深度学习的基础数学模型:如同教儿童反复观察猫狗图片并按特征纠偏,网络接收输入样本与反馈信号,通过层层互联的计算单元自动调整连接权重、提炼判别模式,最终对未见过的新数据做出预测。
神经元是网络最小计算单元,完整执行“加权求和 → 加偏置 → 激活函数”三步流水线:先将每个输入 x_i 与对应权重 w_i 相乘并累加偏置 b 得 z = Σ x_i w_i + b,再输入非线性激活函数 f 输出 a = f(z)。各组成部件的数学表达与职责见下方第一张结构对照表。
三大常用激活函数与非线性不可或缺性
激活函数为神经网络注入非线性表达力,最常用的三种为:(1)Sigmoid f(z)=1/(1+e^{-z}) 将实数压缩至 (0, 1),适合二分类输出层,但在绝对值较大的两端梯度趋近于零(本站实测 z=10 处导数仅 4.54e-5),深层隐藏层易出现梯度消失;(2)ReLU f(z)=max(0, z) 在负半轴截断为 0、正半轴原样输出,计算高效且有效缓解正区梯度消失,是现代隐藏层默认首选;(3)Softmax f(z_i)=e^{z_i}/Σ e^{z_j} 将 K 维打分归一化为和为 1 的概率分布,专用于多分类输出层(实测对 logits=[2.0, 1.0, 0.1] 输出 [0.6590, 0.2424, 0.0986],整体加常数 1000 做数值稳定平移后结果误差 <1e-12)。若去掉激活函数,多层线性层在代数上必然退化为单层仿射变换——本站实测两层线性网络 W2(W1 X+b1)+b2 与合并单层 (W2 W1)X+(W2 b1+b2) 最大误差为 0.0,在非线性 XOR 问题上线性拟合 MSE 恒停在 0.25,而引入 2 个 ReLU 隐藏神经元后即可精确输出 [0.0, 1.0, 1.0, 0.0](准确率 100%)。
输入层、隐藏层与输出层的层级拓扑
将大量神经元按层组织并全连接即形成多层感知机:(1)输入层仅接收与传递原始特征,不做权重变换,神经元数等于输入特征维数(本站核对 28×28 灰度图展平后对应 784 维输入);(2)隐藏层位于中间,可堆叠一层或多层(“深度”学习正源于多层特征逐级抽象),每层接收前层全部输出并施加 ReLU 等非线性激活;(3)输出层规模与激活方式由任务决定——二分类常用 1 个 Sigmoid 神经元(实测 5 样本输出全部落在 (0,1))或 2 个 Softmax 神经元,K 分类用 K 个 Softmax 神经元(实测 4 分类 5 样本每列概率和严格为 1.0),连续回归用 1 个无激活线性神经元(实测输出区间 [-5.5211, 0.6416] 不受界限束缚)。
2-3-1 NumPy 前向传播实测与进阶路径
本站严格按来源结构以纯 NumPy 实现 2-3-1 三层网络(固定 seed=42、小随机高斯权重 ×0.01、零偏置),核对参数矩阵形状为 W1=(3, 2)、b1=(3, 1)、W2=(1, 3)、b2=(1, 1)。送入单样本 X=[[1.5], [-0.5]] 执行前向传播并缓存中间量:隐层线性输出 Z1=[0.008142, 0.002100, -0.002342],经 ReLU 将负分量截断得 A1=[0.008142, 0.002100, 0.0],输出层 Z2=0.000145,经 Sigmoid 得预测概率 A2=0.500036(大于 0.5 判为类 1),并验证 8 样本批量输入 (2, 8) 正确输出 (1, 8)。因尚未训练,小权重网络输出天然贴近 0.5,唯有结合后续损失函数与反向传播不断更新参数才能习得有效判别规律。
下方第二张表归纳了本章五项核心概念要点。掌握神经元与前向拓扑后,下一步应衔接损失函数(均方误差、交叉熵)与反向传播梯度下降,随后借助 TensorFlow 或 PyTorch 等框架扩展至 CNN、RNN 与 Transformer 等复杂架构。
人工神经元各组成部件功能详解
| 部件 | 类比 | 数学表达 | 作用 |
|---|---|---|---|
| 输入 x | 来自上游神经元的传入信号 | x_1, x_2, ..., x_n | 接收原始特征或上一层输出。 |
| 权重 w | 各条输入通道的重要性 | w_1, w_2, ..., w_n | 调节各输入对输出的贡献,是训练核心可学习参数。 |
| 偏置 b | 神经元激活门槛偏移量 | b | 平移加权和,灵活控制神经元激活难易程度。 |
| 加权和 z | 神经元汇集的总信号强度 | z = (x_1 w_1 + ... + x_n w_n) + b | 线性综合全部输入与偏置(单神经元示例实测 z=1.7)。 |
| 激活函数 f | 非线性开关与信号加工器 | a = f(z) | 引入非线性防止多层退化为单层线性变换(实测 XOR 关键)。 |
神经网络基础结构核心概念速查
| 核心概念 | 要点归纳 |
|---|---|
| 神经元 | 最小计算单元,依次完成加权求和、加偏置与非线性激活。 |
| 权重与偏置 | 网络待优化的核心参数矩阵与偏置向量(如 2-3-1 的 W1/b1/W2/b2)。 |
| 激活函数 | Sigmoid、ReLU、Softmax 等非线性映射,决定隐藏表征与输出语义。 |
| 网络层级 | 输入层传递特征、隐藏层逐层抽象、输出层按任务给出最终预测。 |
| 前向传播 | 数据从输入层单向流经隐藏层至输出层并缓存中间量以供反传。 |
运行神经元激活、多层线性退化证明、2-3-1 NumPy 前向与输出层头实测
"""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()
- 核对单神经元 z=1.7、Sigmoid 在 z=10 导数 4.54e-5、两层线性退化零误差而 2-2-1 ReLU 100% 解决 XOR、2-3-1 实测 A2=0.500036 及三类输出头约束。
所需环境: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。
当前源码 SHA256:6893312d65e6643188e9870c74fc96be5adf0cffa045acbf0f47695327fabfce
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境: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。
ZIP SHA256:ff3ccc3c7d8070be742cc6364a39799fa07ef239f16a85b5536ba89126427993
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么去掉隐藏层激活函数后,把 10 层全连接网络堆叠在一起依然无法解决 XOR 分类问题?
展开参考解答
因为任意多层线性变换的复合仍是单一线性仿射变换 W_eq x + b_eq(本站已实测两层合并误差为 0.0),决策边界永远是单条超平面,无法把线性不可分的 XOR 四个顶点正确隔开。