问题描述
我正在使用 Keras 运行一个简单的前馈网络.只有一个隐藏层,我想对每个输入与每个输出的相关性进行一些推断,我想提取权重.
I'm running a simple feed-forward network using Keras .Having just one hidden layer I would like to make some inference regarding the relevance of each input to each output and I would like to extract the weights.
这是模型:
def build_model(input_dim, output_dim):
n_output_layer_1 = 150
n_output = output_dim
model = Sequential()
model.add(Dense(n_output_layer_1, input_dim=input_dim, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(n_output))
提取我写的重量:
for layer in model.layers:
weights = layer.get_weights()
weights = np.array(weights[0]) #this is hidden to output
first = model.layers[0].get_weights() #input to hidden
first = np.array(first[0])
不幸的是,我没有得到矩阵中的偏差列,我知道 Keras 会自动将其放入其中.
Unfortunately I don't get the biases columns in the matrices, which I know Keras automatically puts in it.
您知道如何检索偏差权重吗?
预先感谢您的帮助!
推荐答案
get_weights()
对于 Dense
层返回两个元素的列表,第一个元素包含权重,第二个元素包含偏差.所以你可以简单地做:
get_weights()
for a Dense
layer returns a list of two elements, the first element contains the weights, and the second element contains the biases. So you can simply do:
weights = model.layers[0].get_weights()[0]
biases = model.layers[0].get_weights()[1]
请注意,权重和偏差已经是 numpy 数组.
Note that weights and biases are already numpy arrays.
这篇关于如何在 Keras 序列模型中提取偏置权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!