蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行常见网络核心数值原语与 MLP 分类实测

PYTHONWindows 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。explore-common-network-types.py
explore-common-network-types.py260 行
"""Independent NumPy + scikit-learn CPU lab for FCN/MLP, Conv1D/2D+Pool, RNN/Gated step, GAN step, and Self-Attention."""
import json
import platform

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


def sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -30.0, 30.0)))


def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
    shifted = x - np.max(x, axis=axis, keepdims=True)
    exp_x = np.exp(shifted)
    return exp_x / np.sum(exp_x, axis=axis, keepdims=True)


def conv2d_nchw_same_stride1(x: np.ndarray, weight: np.ndarray, bias: np.ndarray) -> np.ndarray:
    """Minimal pure-NumPy 2D cross-correlation matching PyTorch Conv2d(padding=1, stride=1) for 3x3 kernels."""
    N, C_in, H, W = x.shape
    C_out, _, kH, kW = weight.shape
    pad_h, pad_w = kH // 2, kW // 2
    x_pad = np.pad(x, ((0, 0), (0, 0), (pad_h, pad_h), (pad_w, pad_w)), mode="constant")
    out = np.zeros((N, C_out, H, W), dtype=np.float64)
    for n in range(N):
        for oc in range(C_out):
            acc = np.full((H, W), bias[oc], dtype=np.float64)
            for ic in range(C_in):
                for kh in range(kH):
                    for kw in range(kW):
                        acc += weight[oc, ic, kh, kw] * x_pad[n, ic, kh : kh + H, kw : kw + W]
            out[n, oc] = acc
    return out


def maxpool2d_2x2(x: np.ndarray) -> np.ndarray:
    N, C, H, W = x.shape
    return x.reshape(N, C, H // 2, 2, W // 2, 2).max(axis=(3, 5))


def run_cases():
    rng = np.random.default_rng(2026)
    cases = []

    # 1. FCN / MLP forward geometry, parameter explosion on images, and real scikit-learn MLPClassifier
    W1 = rng.normal(0.0, 0.1, size=(100, 128))
    b1 = np.zeros(128)
    W2 = rng.normal(0.0, 0.1, size=(128, 64))
    b2 = np.zeros(64)
    W3 = rng.normal(0.0, 0.1, size=(64, 10))
    b3 = np.zeros(10)
    x_fcn = rng.normal(0.0, 1.0, size=(4, 100))
    h1 = np.maximum(0.0, x_fcn @ W1 + b1)
    h2 = np.maximum(0.0, h1 @ W2 + b2)
    logits = h2 @ W3 + b3
    fcn_params = W1.size + b1.size + W2.size + b2.size + W3.size + b3.size  # 21834

    # Parameter explosion comparison for 3x32x32 image
    flat_img_fcn_params = (3 * 32 * 32) * 128 + 128  # 393344
    conv3x3_16_params = 16 * (3 * 3 * 3) + 16        # 448

    data = load_breast_cancer()
    X_tr, X_te, y_tr, y_te = train_test_split(
        data.data, data.target, test_size=0.25, random_state=42, stratify=data.target
    )
    mlp_pipe = Pipeline([
        ("scaler", StandardScaler()),
        ("mlp", MLPClassifier(hidden_layer_sizes=(32, 16), max_iter=400, random_state=42)),
    ])
    mlp_pipe.fit(X_tr, y_tr)
    mlp_test_acc = round(float(accuracy_score(y_te, mlp_pipe.predict(X_te))), 4)

    c1_ok = (
        list(logits.shape) == [4, 10]
        and fcn_params == 21834
        and flat_img_fcn_params == 393344
        and conv3x3_16_params == 448
        and mlp_test_acc >= 0.94
    )
    cases.append(dict(
        name="fcn_mlp_forward_and_sklearn_fit",
        inputs=dict(fcn_dims=[100, 128, 64, 10], img_shape=[3, 32, 32], dataset="breast_cancer"),
        prerequisites="NumPy 三层全连接前向计算 + 3×32×32 图像展平参数量对比 + scikit-learn MLPClassifier 实测",
        action="验证 SimpleFCN(100->128->64->10) 精确 21,834 参数与输出形状 [4,10],3×32×32 图像 FCN 首层参数为 3×3 卷积的 878 倍,及表格 MLP 测试准确率 >=94%。",
        expected=dict(logits_shape=[4, 10], fcn_params=21834, conv_param_ratio_gt_800=True, mlp_acc_ge_94=True),
        actual=dict(logits_shape=list(logits.shape), fcn_params=fcn_params, conv_param_ratio_gt_800=(flat_img_fcn_params / conv3x3_16_params > 800), mlp_acc_ge_94=(mlp_test_acc >= 0.94)),
        measurements=dict(flat_img_fcn_params=flat_img_fcn_params, conv3x3_16_params=conv3x3_16_params, ratio=round(flat_img_fcn_params / conv3x3_16_params, 2), mlp_test_acc=mlp_test_acc),
        passed=c1_ok,
    ))

    # 2. CNN 1D shift-equivariance + 2D Conv->ReLU->MaxPool shape & parameter sharing
    signal = np.array([0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
    signal_shifted = np.roll(signal, 2)
    edge_kernel = np.array([-1.0, 1.0])
    conv1d_a = np.correlate(signal, edge_kernel, mode="valid")
    conv1d_b = np.correlate(signal_shifted, edge_kernel, mode="valid")
    # Peak edge index shifts exactly by +2 due to parameter sharing
    peak_shift = int(np.argmax(conv1d_b) - np.argmax(conv1d_a))

    x_img = rng.normal(0.0, 1.0, size=(2, 3, 16, 16))
    k1 = rng.normal(0.0, 0.2, size=(8, 3, 3, 3))
    b_c1 = np.zeros(8)
    k2 = rng.normal(0.0, 0.2, size=(16, 8, 3, 3))
    b_c2 = np.zeros(16)
    f1 = maxpool2d_2x2(np.maximum(0.0, conv2d_nchw_same_stride1(x_img, k1, b_c1)))
    f2 = maxpool2d_2x2(np.maximum(0.0, conv2d_nchw_same_stride1(f1, k2, b_c2)))
    flat_f2 = f2.reshape(x_img.shape[0], -1)
    # Also check SimpleCNN(32x32) shape: after two 2x2 pools -> 8x8 -> 32*8*8=2048
    simple_cnn_flat_dim = 32 * (32 // 4) * (32 // 4)

    c2_ok = (
        peak_shift == 2
        and list(f1.shape) == [2, 8, 8, 8]
        and list(f2.shape) == [2, 16, 4, 4]
        and list(flat_f2.shape) == [2, 256]
        and simple_cnn_flat_dim == 2048
    )
    cases.append(dict(
        name="cnn_local_conv_and_maxpool_primitives",
        inputs=dict(img_batch_shape=[2, 3, 16, 16], kernel_size=3, pool=2),
        prerequisites="纯 NumPy 一维互相关平移等变性 + 二维 Conv(padding=1)->ReLU->MaxPool2d(2,2) 两层堆叠",
        action="验证共享卷积核对移位信号响应精确同步移位 (+2),及 16×16 输入经两次卷积池化依次输出 [2,8,8,8]、[2,16,4,4] 与展平 [2,256]。",
        expected=dict(peak_shift=2, pool1_shape=[2, 8, 8, 8], pool2_shape=[2, 16, 4, 4], flat_shape=[2, 256], cnn32_flat_dim=2048),
        actual=dict(peak_shift=peak_shift, pool1_shape=list(f1.shape), pool2_shape=list(f2.shape), flat_shape=list(flat_f2.shape), cnn32_flat_dim=simple_cnn_flat_dim),
        passed=c2_ok,
    ))

    # 3. RNN recurrence memory & gated cell retention (LSTM-like additive path vs vanilla decay)
    vocab_size, embed_dim, hidden_dim, num_classes = 20, 8, 12, 2
    emb_table = rng.normal(0.0, 0.5, size=(vocab_size, embed_dim))
    W_xh = rng.normal(0.0, 0.3, size=(embed_dim, hidden_dim))
    W_hh = rng.normal(0.0, 0.3, size=(hidden_dim, hidden_dim))
    b_h = np.zeros(hidden_dim)
    W_out = rng.normal(0.0, 0.3, size=(hidden_dim, num_classes))

    def rnn_forward(token_ids):
        embs = emb_table[token_ids]  # (B, T, E)
        h = np.zeros((token_ids.shape[0], hidden_dim))
        for t in range(token_ids.shape[1]):
            h = np.tanh(embs[:, t, :] @ W_xh + h @ W_hh + b_h)
        return h, h @ W_out

    seq_a = np.array([[1, 4, 7, 2, 9, 5], [3, 6, 8, 1, 2, 4]])
    seq_b = seq_a.copy()
    seq_b[0, 0] = 15  # perturb only step t=0
    h_a, out_a = rnn_forward(seq_a)
    h_b, _ = rnn_forward(seq_b)
    memory_delta = float(np.linalg.norm(h_a[0] - h_b[0]))

    # Compare long-range signal retention over T=20 steps: attenuated vanilla factor 0.5 vs forget gate f=0.95
    T_long = 20
    vanilla_retention = round(0.5 ** T_long, 8)
    gated_retention = round(0.95 ** T_long, 4)

    c3_ok = (
        list(out_a.shape) == [2, 2]
        and memory_delta > 1e-4
        and vanilla_retention < 1e-5
        and gated_retention > 0.35
    )
    cases.append(dict(
        name="rnn_sequence_memory_and_gated_step",
        inputs=dict(batch=2, seq_len=6, embed_dim=8, hidden_dim=12, long_steps=20),
        prerequisites="Embedding -> Vanilla RNN 递推隐状态 + 20 步遗忘门记忆保留率对比",
        action="验证修改 t=0 词元会改变末步隐状态 h_T (顺序依赖),且 20 步后衰减系数 0.5 残余 <1e-5 而遗忘门 0.95 保留 >0.35。",
        expected=dict(out_shape=[2, 2], history_dependent=True, gated_beats_vanilla_long_range=True),
        actual=dict(out_shape=list(out_a.shape), history_dependent=memory_delta > 1e-4, gated_beats_vanilla_long_range=(vanilla_retention < 1e-5 and gated_retention > 0.35)),
        measurements=dict(t0_perturb_ht_norm=round(memory_delta, 6), vanilla_20step=vanilla_retention, gated_20step=gated_retention),
        passed=c3_ok,
    ))

    # 4. Miniature 1D GAN adversarial game with explicit stop-gradient separation
    # Real data ~ N(3.0, 0.35^2), Generator G(z) = a*z + b initialized at a=0.5, b=0.0
    # Discriminator D(x) = sigmoid(w*x + c)
    g_a, g_b = 0.5, 0.0
    d_w, d_c = 0.1, 0.0
    lr_d, lr_g = 0.15, 0.15
    real_mean_target = 3.0
    init_fake_mean = g_b
    for _ in range(180):
        x_real = rng.normal(real_mean_target, 0.35, size=64)
        z = rng.normal(0.0, 1.0, size=64)
        # Step 1: update D on real (y=1) and detached fake (y=0)
        x_fake_detached = g_a * z + g_b
        p_real = sigmoid(d_w * x_real + d_c)
        p_fake = sigmoid(d_w * x_fake_detached + d_c)
        # grad of -[log(p_real) + log(1 - p_fake)] wrt d_w, d_c
        grad_dw = float(np.mean((p_real - 1.0) * x_real + p_fake * x_fake_detached))
        grad_dc = float(np.mean((p_real - 1.0) + p_fake))
        d_w -= lr_d * grad_dw
        d_c -= lr_d * grad_dc

        # Step 2: update G (D fixed) to minimize -log(D(G(z)))
        z2 = rng.normal(0.0, 1.0, size=64)
        x_fake = g_a * z2 + g_b
        p_fake_g = sigmoid(d_w * x_fake + d_c)
        # d[-log(sigmoid(d_w*x + d_c))]/dx = (p_fake_g - 1) * d_w
        dL_dx = (p_fake_g - 1.0) * d_w
        g_a -= lr_g * float(np.mean(dL_dx * z2))
        g_b -= lr_g * float(np.mean(dL_dx))

    final_fake_mean = round(float(g_b), 4)
    moved_toward_real = bool(abs(final_fake_mean - real_mean_target) < abs(init_fake_mean - real_mean_target) and final_fake_mean > 2.0)
    params_finite = bool(np.isfinite(d_w) and np.isfinite(g_b))
    c4_ok = bool(moved_toward_real and params_finite)
    cases.append(dict(
        name="gan_minimax_adversarial_step",
        inputs=dict(real_mean=3.0, init_gen_mean=0.0, steps=180),
        prerequisites="一维极简生成器/判别器交替更新循环(判别器更新截断生成器梯度,生成器固定判别器权重)",
        action="验证经过 180 步交替对抗更新后,生成器分布均值由 0.0 显著逼近真实分布均值 3.0 (>2.0) 且参数保持有限。",
        expected=dict(generator_moved_toward_real=True, params_finite=True),
        actual=dict(generator_moved_toward_real=moved_toward_real, params_finite=params_finite),
        measurements=dict(init_gen_mean=init_fake_mean, final_gen_mean=final_fake_mean, final_gen_scale=round(float(abs(g_a)), 4), final_d_w=round(float(d_w), 4)),
        passed=c4_ok,
    ))

    # 5. Scaled dot-product self-attention (Transformer core primitive)
    seq_len, d_k, d_v = 5, 64, 16
    Q = rng.normal(0.0, 1.0, size=(seq_len, d_k))
    K = rng.normal(0.0, 1.0, size=(seq_len, d_k))
    V = rng.normal(0.0, 1.0, size=(seq_len, d_v))
    raw_scores = Q @ K.T
    scaled_scores = raw_scores / np.sqrt(d_k)
    attn_unscaled = softmax(raw_scores, axis=-1)
    attn_scaled = softmax(scaled_scores, axis=-1)
    attn_out = attn_scaled @ V

    row_sum_err = float(np.max(np.abs(attn_scaled.sum(axis=-1) - 1.0)))
    # Scaled attention should have higher average entropy (less saturated) than unscaled at d_k=64
    ent_unscaled = float(-np.mean(np.sum(attn_unscaled * np.log(attn_unscaled + 1e-12), axis=-1)))
    ent_scaled = float(-np.mean(np.sum(attn_scaled * np.log(attn_scaled + 1e-12), axis=-1)))
    c5_ok = bool(list(attn_out.shape) == [seq_len, d_v] and row_sum_err < 1e-12 and ent_scaled > ent_unscaled)
    cases.append(dict(
        name="self_attention_scaled_dot_product",
        inputs=dict(seq_len=seq_len, d_k=d_k, d_v=d_v),
        prerequisites="Transformer 缩放点积自注意力 softmax(QK^T / sqrt(d_k))V",
        action="验证注意力权重每行严格归一 (误差 <1e-12)、输出形状 [5,16],且除以 sqrt(d_k) 后注意力分布熵高于未缩放版本。",
        expected=dict(out_shape=[5, 16], row_sums_exact=True, scaling_reduces_saturation=True),
        actual=dict(out_shape=list(attn_out.shape), row_sums_exact=bool(row_sum_err < 1e-12), scaling_reduces_saturation=bool(ent_scaled > ent_unscaled)),
        measurements=dict(max_row_sum_err=row_sum_err, entropy_unscaled=round(ent_unscaled, 4), entropy_scaled=round(ent_scaled, 4)),
        passed=c5_ok,
    ))

    payload = dict(
        version=platform.python_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-common-network-types-lab/explore-common-network-types.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-common-network-types.py,或下载右侧课程工程包。
  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。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a454.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习