如何在Keras顺序模型中提取偏差权重? [英] How to extract bias weights in Keras sequential model?

查看:437
本文介绍了如何在Keras顺序模型中提取偏差权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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])

不幸的是,我没有在矩阵中找到biass列,我知道Keras会自动将其放入.

Unfortunately I don't get the biases columns in the matrices, which I know Keras automatically puts in it.

您知道如何获取偏差权重吗?

在此先感谢您的帮助!

推荐答案

get_weights()返回两个元素的列表,第一个元素包含权重,第二个元素包含偏差.因此,您只需执行以下操作即可:

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顺序模型中提取偏差权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆