import numpy as np
# 1. 模拟 3 个样本的 Batch 输入 X (Shape: 3x4) 与 Ground Truth 独热标签 Y (Shape: 3x3)
rng = np.random.default_rng(seed=2026)
X = rng.standard_normal((3, 4))
Y_true = np.array([
[1, 0, 0], # 样本 0 真实类别为 0
[0, 1, 0], # 样本 1 真实类别为 1
[0, 0, 1] # 样本 2 真实类别为 2
])
# 2. 模型参数 W: (4x3), b: (3,)
W = rng.standard_normal((4, 3))
b = np.array([0.1, -0.2, 0.5])
# 3. 线性前向计算 Z = X @ W + b
Z = X @ W + b
# 4. 数值稳定 Softmax 计算预测概率矩阵 P
Z_max = np.max(Z, axis=1, keepdims=True)
exp_Z = np.exp(Z - Z_max)
P = exp_Z / np.sum(exp_Z, axis=1, keepdims=True)
# 5. 计算交叉熵损失 Loss = -sum(Y_true * log(P + eps)) / N
eps = 1e-15 # 防止 log(0)
clipped_P = np.clip(P, eps, 1 - eps)
loss = -np.sum(Y_true * np.log(clipped_P)) / X.shape[0]
# 6. 预测类别 ID
pred_labels = np.argmax(P, axis=1)
true_labels = np.argmax(Y_true, axis=1)
print("=== 预测概率矩阵 P (3x3) ===
", np.round(P, 4))
print("
=== 预测类别 vs 真实类别 ===")
print("预测类别 IDs:", pred_labels)
print("真实类别 IDs:", true_labels)
print(f"
=== 平均交叉熵损失 Loss: {loss:.4f} ===")