如何在Matlab中正确实现Garson算法计算神经网络参数重要性?
Garson算法MATLAB实现疑问解答
1. 代码实现是否正确?
你的代码并未正确实现Garson算法,核心问题如下:
算法逻辑偏差
原始Garson算法针对单隐藏层前馈神经网络设计,核心是计算输入层-隐藏层权重与隐藏层-输出层权重的联合贡献,逻辑为:
对每个输入特征,计算其通过每个隐藏层神经元向输出层传递的权重贡献占比,再将所有隐藏层神经元的贡献求和,最后归一化得到相对重要性。
而你的代码存在以下错误:
- 仅提取了输入层到第一层隐藏层的权重(
net.IW),完全忽略了后续隐藏层之间、最后一层隐藏层到输出层的权重(net.LW),丢失了权重传递的关键环节,无法反映特征对输出的实际贡献。 - 错误将偏置权重(
net.b)纳入计算:偏置是网络的固有参数,不属于输入特征,不应计入特征重要性。 - 计算方式错误:直接对输入层权重的绝对值按列求和再归一化,这只是简单的权重占比,并非Garson算法定义的“特征通过隐藏层对输出的相对贡献”。
多隐藏层适配问题
你的网络包含3个隐藏层,而标准Garson算法不支持多隐藏层场景,需要对算法进行扩展(比如逐层计算权重的传递贡献),但你的代码完全未处理多隐藏层的权重传递逻辑。
2. 改变输入参数数量时,相对重要性结果是否会变化?
会发生变化,原因如下:
- 输入特征数量改变后,神经网络会重新训练,权重会根据新的特征空间重新分配,每个特征的权重绝对值和相对占比都会调整。
- Garson算法的相对重要性基于所有特征的贡献总和进行归一化,增减特征会直接改变总和的基数,进而影响每个特征的相对占比。
- 特征之间存在交互性,新增或移除特征会改变模型对剩余特征的学习侧重,导致其对输出的贡献占比发生变化。
附:原始代码
主程序代码
%%% Data Inputs inputs = data(:, 1:4)'; targets = data(:, 5)'; %%% Create a feedforward neural network net = feedforwardnet([10, 15, 20]); %%%% Set the number of neurons in each hidden layer net.layers{1}.size = 10; net.layers{2}.size = 15; net.layers{3}.size = 20; %%%% Change activation functions (e.g., 'tansig' to 'purelin' for output layer) net.layers{1}.transferFcn = 'tansig'; % Activation function for first hidden layer net.layers{2}.transferFcn = 'tansig'; % Activation function for second hidden layer net.layers{3}.transferFcn = 'tansig'; % Activation function for third hidden layer net.layers{4}.transferFcn = 'purelin'; % Activation function for output layer %%%% Divide data for training, validation, and testing net.divideParam.trainRatio = 0.7; net.divideParam.valRatio = 0.15; net.divideParam.testRatio = 0.15; %%%% Train the neural network [net, tr] = train(net, inputs, targets); %%%% Calculate Garson's importance importance = garsonsAlgorithm(net); %%%% Display feature importances disp('Feature Importances (Garson''s Algorithm):'); for i = 1:length(importance) disp(['Importance for x' num2str(i) ': ' num2str(importance(i))]); end
自定义函数代码
function importance = garsonsAlgorithm(net) %%% Extract connection weights from the neural network weights = cell2mat(net.IW); % Check if there are bias weights if isfield(net, 'b') bias_weights = cell2mat(net.b); weights = [weights; bias_weights]; end %%% Calculate the absolute values of the weights absolute_weights = abs(weights); %%% Calculate the importance for each input feature importance = sum(absolute_weights, 1); %%% Normalize importance values importance = importance / sum(importance); end
内容的提问来源于stack exchange,提问作者Haris Saeed
相关产品推荐
相关产品推荐

