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()

运行结果:

相关推荐
肖有米XTKF864614 分钟前
带货者精品优选模式系统的平台解析
人工智能·信息可视化·团队开发·csdn开发云
天天进步201515 分钟前
打破沙盒限制:OpenWork 如何通过权限模型实现安全的系统级调用?
人工智能·安全
qq_6543669816 分钟前
CSS如何处理@import样式表的嵌套加载_评估递归对加载的影响
jvm·数据库·python
weixin_3812881817 分钟前
苹果微软双修党福音:Navicat如何跨系统平滑迁移配置
jvm·数据库·python
xcbrand18 分钟前
政府事业机构品牌策划公司找哪家
大数据·人工智能·python
骥龙21 分钟前
第十篇:合规与未来展望——构建AI智能体安全标准
人工智能·安全
薛定e的猫咪21 分钟前
AI 辅助科研工具全景指南:计算机与金融领域(2025-2026)
人工智能·金融·ai编程·ai写作
码界筑梦坊22 分钟前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
阿荻在肝了25 分钟前
Agent学习六:LangGraph学习-持久化与记忆一
python·学习·agent
qingyulee26 分钟前
python多进程、线程、协程
python