keras tensorflow 获取某层输出和层内参数的值

1.查看模型的输出和形状

# 构建模型
Transformer_encoder = build_transformer_model(config_path, checkpoint_path)
gp_layer = GlobalPointer(len(categories), 64)
final_output = gp_layer(Transformer_encoder.output) # 将bert的编码送入后面接的分类层
model = Model(Transformer_encoder.input, final_output) # 由输入和输出定义

# 准备数据,可以自己写,不过这里复用了训练用的数据生成器
train_generator = data_generator(train_data, batch_size)
data_ge = train_generator.__iter__()
embeding_and_segments, labels = next(data_ge)

# K为keras的后端,也就是tensorflow
# K.function和上面那个Model很像,也由输入和输出定义,通过该函数就可以获取模型内部的输出
f = K.function(model.input, model.output)
out = f(embeding_and_segments) # 给模型输入数据,out就是模型的输出
print(out)
print(out.shape)

2.想要查看模型某一层的输出

model = Model(Transformer_encoder.input, final_output) # 由输入和输出定义
print(model.layers) # 模型有很多层
# 如果想看最后一层的输出,就直接这样写,其他层改一下索引即可
f = K.function(model.input, model.layers[-1].output)
out = f(embeding_and_segments)
print(out)
print(out.shape)

3.如果想看某一层里面的更细致的参数,比如最后一层GlobalPointer里面的某些数据处理

比如GlobalPointer的call前面几行input的处理,就自己新加代码获取输出

        inputs = self.dense(inputs)
        self.my = inputs # 新加代码
        inputs = tf.split(inputs, self.heads, axis=-1)
        inputs = K.stack(inputs, axis=-2)
        qw, kw = inputs[..., :self.head_size], inputs[..., self.head_size:]

就可以通过最后一层model.layer[-1].my查看在dense处理后的input和其形状,上面代码的self不是model本身,是GlobalPointer,这是模型的最后一层,用model.my肯定报错的

f = K.function(model.input, model.layer[-1].my)
out = f(embeding_and_segments)
print(out)
print(out.shape)

4.如果想看dense的参数,dense是在GlobalPointer的build函数里定义的

    def build(self, input_shape):
        super(GlobalPointer, self).build(input_shape)
        self.dense = Dense(
            units=self.head_size * self.heads * 2,
            use_bias=self.use_bias,
            kernel_initializer=self.kernel_initializer
        )

dense由Dense定义,则进入Dense源码,截取部分如下,可以注意到有一个self.kernel

    def build(self, input_shape):
        assert len(input_shape) >= 2
        input_dim = input_shape[-1]

        self.kernel = self.add_weight(shape=(input_dim, self.units),
                                      initializer=self.kernel_initializer,
                                      name='kernel',
                                      regularizer=self.kernel_regularizer,
                                      constraint=self.kernel_constraint)

那么就可以这样获取

f = K.function(model.input, model.layers[-1].dense.kernel)
out = f(embeding_and_segments)
print(out)
print(out.shape)

最后赠送两个函数,一个将模型summary输出到文件,有时候控制台显示不了那么宽的文字;另一个将模型打印成图,看了一下,细节不够,好像用处不大

def model_to_picture(model):
    # 画一个模型结构图
    from tensorflow.keras.utils import plot_model
    plot_model(model, to_file='model_structure.png', show_shapes=True)


def model_summary_tofile(model, file_name="model_summary.txt"):
    from contextlib import redirect_stdout
    with open(file_name, 'w') as f:
        with redirect_stdout(f):
            model.summary(line_length=250)

原文链接: https://www.cnblogs.com/lxzbky/p/15977828.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    keras tensorflow 获取某层输出和层内参数的值

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/399915

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月14日 上午9:38
下一篇 2023年4月14日 上午9:38

相关推荐