Tensorflow2.0笔记 - 自定义Layer和Model

本笔记主要记录如何在tensorflow中实现自定的Layer和Model。详细内容请参考代码中的链接。

复制代码
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics

tf.__version__
#关于自定义layer和自定义Model的相关介绍,参考下面的链接:
#https://tf.wiki/zh_hans/basic/models.html
#https://blog.csdn.net/lzs781/article/details/104741958


#自定义Dense层,继承自Layer
class MyDense(layers.Layer):
    #需要实现__init__和call方法
    def __init__(self, input_dim, output_dim):
        super(MyDense, self).__init__()
        self.kernel = self.add_weight(name='w', shape=[input_dim, output_dim], initializer=tf.random_uniform_initializer(0, 1.0))
        self.bias = self.add_weight(name='b', shape=[output_dim], initializer=tf.random_uniform_initializer(0, 1.0))

    def call(self, inputs, training=None):
        out = inputs@self.kernel + self.bias
        return out

#自定义Model,继承自Model
class MyModel(keras.Model):
    #需要实现__init__和call方法
    def __init__(self):
        super(MyModel, self).__init__()
        #自定义5层MyDense自定义Layer
        self.fc1 = MyDense(28*28, 256)
        self.fc2 = MyDense(256, 128)
        self.fc3 = MyDense(128, 64)
        self.fc4 = MyDense(64, 32)
        self.fc5 = MyDense(32, 10)

    def call(self, inputs, trainning=None):
        x = self.fc1(inputs) #会调用MyDense的call方法
        x = tf.nn.relu(x)
        x = self.fc2(x)
        x = tf.nn.relu(x)
        x = self.fc3(x)
        x = tf.nn.relu(x)
        x = self.fc4(x)
        x = tf.nn.relu(x)
        x = self.fc5(x)
        return x

customModel = MyModel()
customModel.build(input_shape=[None, 28*28])
customModel.summary()

运行结果:

相关推荐
用户8356290780511 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
小徐_23331 小时前
向日葵 x AI:把远程控制封装成 MCP,让 AI 替我远程控制设备
前端·人工智能
桦说编程2 小时前
Harness Engineering — AI 时代的工程最佳实践
人工智能·架构·代码规范
老纪的技术唠嗑局2 小时前
Agent / Skills / Teams 架构演进流程及技术选型之道
人工智能·agent
该用户已不存在2 小时前
除了OpenClaw还有谁?五款安全且高效的开源AI智能体
人工智能·aigc·ai编程
机器之心2 小时前
AI发布首个全球科学家社区爆火,硅谷投资圈:科技研究领域的「谷歌地图」来了!
人工智能·openai
ECH00O002 小时前
06-Attention/注意力机制:AI的"聚光灯"
人工智能
机器之心2 小时前
1美元Token撬动4800美元收益!AI挑战百万美元级基准,最赚钱的Agent出现了
人工智能·openai
ECH00O002 小时前
05-Transformer:AI界的"变形金刚"
人工智能
非优秀程序员2 小时前
推荐五个OPENclaw 可以应用的场景,让你明白他能干怎么
人工智能·架构·浏览器