tensorflow入门 自定义层

前面讲了自定义损失函数,自定义正则化,自定义评价函数。现在来讲自定义层,其实都差不多,继承重要的组件就可以了。自定义层就是基层keras.layers.Layer

python 复制代码
class MyLayer(keras.layers.Layer):
    def __init__(self, units, activation = None, **kwargs):
        super().__init__(**kwargs)
        self.units = units
        self.activation = keras.activations.get(activation)
        
    def build(self, batch_input_shape):
        self.kernel = self.add_weight(name = 'kernel', shape = [batch_input_shape[-1], self.units], initializer='glorot_normal')
        self.bais = self.add_weight(name = 'bias', shape = self.units, initializer='zeros')
        super().build(batch_input_shape)
        
    def call(self, x):
        return self.activation(X @ self.kernel + self.bias)
        
    def compute_output_shape(self, batch_input_shape):
        return tf.TensorShape(batch_input_shape.as_list()[:-1] + [self.units])
    
    def get_config(self):
        base_config = super().get_config()
        return {**base_config, 'units':self.units, 'activation': keras.activations.serialize(self.activation)}

还是老样子,继承keras已有的组件layers,然后实现几个必要的函数。

(1).构造函数将所有超参数用作参数,kwargs负责把所有的默认参数传递给父类,比如input_shape,trainable,name.

(2).build方法的作用是通过为每个权重调用add_weight()方法来创建层的变量,keras会自动推测输入的维度,也即是batch_input_shape

(3).call方法是每次计算矩阵相乘的时候,被自动调用的方法。

(4).compute_output_shape返回输出的维度,这个函数可有可无,keras会自动推断出输出的维度

(5).get_config是必须的,初始化父类的权重,以及自己的某些参数,当然不仅仅是unit和激活函数,值得注意的是,这里使用了keras.activation.serialize方法保存激活函数的完整配置。

上面创建的层可以直接拿来使用。比如dense = MyLayer(100,'relu')(input)

创建自定义的层也很灵活,可以多输入多输出,只不过需要再call返回的时候,分开返回,比如三个输入,两个输出的自定义层。

class MyLayer(keras.layers,Layer):

def call(self, X):

x1, x2, x3 = X

return x1+x2, x2+x3

这里只是举一个简单的例子

如果再自定义层中需要加入一些操作,比如正则化,也需要再call函数中实现。

相关推荐
朴马丁7 小时前
从制造到智造:PLM如何赋能企业研发创新
大数据·运维·人工智能·食品行业·流程行业plm·化工新材料行业·新能源材料行业
chenment8 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
武子康8 小时前
GAIA、Cosmos、Genie 等视频模型纷纷自称"世界模型",为什么说视觉逼真度不构成决策证据?
人工智能·llm·agent
上海锝秉工控8 小时前
普通编码器:基础信号处理与数据转换核心岗
人工智能·信号处理
chenyuhao20248 小时前
第一章_自动驾驶中的社会交互
人工智能·机器学习·自动驾驶
洛阳泰山8 小时前
别再为做 AI 去学 Python 了!MaxKB4j:纯 Java 造的企业级 RAG + 工作流引擎,开箱即用
人工智能·开源·agent
fthux8 小时前
GitZip Pro:给GitHub仓库“瘦身”的魔法剪刀手
人工智能·chrome·ai·语言模型·开源·github·open source
武子康8 小时前
Video VAE 不是末端编解码器:5 维-潜网格-主模型 Token 的“表示合同“
人工智能·llm·agent
互联网中的一颗神经元8 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql
Sunlly8 小时前
Transcript 不是 Context:用五组实验拆解 OpenClaw 的上下文生命周期
人工智能