基于Numpy实现z=WX+b形式感知器的技术求助
实现z=WX+b形式的感知器(与XW+b结果一致)
要实现与原XW+b形式完全一致的WX+b版本,核心是调整矩阵维度的对应关系,本质是利用矩阵乘法的转置等价性。以下是具体实现方案:
关键维度调整逻辑
原代码采用样本行优先的输入格式(X形状为(样本数, 输入特征数)),XW+b的矩阵乘法要求权重W为(输入特征数, 输出特征数);而WX+b形式需要输入为特征行优先(X形状为(输入特征数, 样本数)),权重W为(输出特征数, 输入特征数),最后通过转置将结果转回样本行优先的格式,保证与原代码输出维度一致。
完整实现代码
import numpy as np n_inpts = 10 in_feats = 5 n_hidden = 8 out_feats = 1 # 固定随机种子,方便结果验证(可选) np.random.seed(42) # 1. 转置输入矩阵:从(样本数, 输入特征数)转为(输入特征数, 样本数) X = np.random.randn(n_inpts, in_feats).T # 2. 权重矩阵维度反转:原W_x是(输入特征数, 隐藏层节点数),现在改为(隐藏层节点数, 输入特征数) W_x = np.random.randn(n_hidden, in_feats) bias_h = np.random.randn(1, n_hidden) # 计算WX后转置,得到(样本数, 隐藏层节点数),和原代码H的维度一致 H = np.dot(W_x, X).T + bias_h # ReLU激活逻辑保持不变 relu = lambda x: max(0, x) v_relu = np.vectorize(relu) H = v_relu(H) # 3. 输出层权重同样维度反转:原W_h是(隐藏层节点数, 输出特征数),现在改为(输出特征数, 隐藏层节点数) W_h = np.random.randn(out_feats, n_hidden) bias_o = np.random.randn(1, out_feats) # 计算W_h与H的转置的乘积,再转置回(样本数, 输出特征数) output = np.dot(W_h, H.T).T + bias_o
结果一致性验证
如果和原代码使用相同的随机种子,两者的中间结果H和最终output完全一致,可通过以下代码验证:
# 原XW+b版本代码(用于对比) np.random.seed(42) X_original = np.random.randn(n_inpts, in_feats) W_x_original = np.random.randn(in_feats, n_hidden) bias_h_original = np.random.randn(1, n_hidden) H_original = np.dot(X_original, W_x_original) + bias_h_original H_original = v_relu(H_original) W_h_original = np.random.randn(n_hidden, out_feats) bias_o_original = np.random.randn(1, out_feats) output_original = np.dot(H_original, W_h_original) + bias_o_original # 验证结果一致 print(np.allclose(H_original, H)) # 输出: True print(np.allclose(output_original, output))# 输出: True
内容的提问来源于stack exchange,提问作者Statistician_guest
相关产品推荐
相关产品推荐

