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

运行结果:

相关推荐
用户8356290780513 分钟前
Python 调整 Excel 工作表显示设置
后端·python
阿里云大数据AI技术4 分钟前
阿里云DLF年度发布:Agentic Lake全模态 AI 数据湖底座
人工智能
小李不想当小白5 分钟前
SPI通信外设与W25Q64 (硬件SPI)(STM32标准库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
小咕聊编程35 分钟前
教育大数据可视化系统
python·django·flask
lusklusklusk36 分钟前
Python 巡检脚本:进程运行状态、数据库写入时效检查及邮件通知与告警
数据库·python·oracle
玩AI的奶茶41 分钟前
MiniMax H3 出 30 秒长片:显存账、拼接法和一次的成本
大数据·人工智能·ai·gpu算力·算力租赁
杭州默安科技1 小时前
从“被动响应”到“主动遏制”:AI Agent时代,网络防御体系如何重构?
人工智能·网络安全·ai智能体
Angeldream1231 小时前
第 10 章 医学影像伦理与安全
图像处理·人工智能·python·安全·机器学习·医学影像
勤奋的大熊猫1 小时前
Python 双层 enumerate 循环选取最后一层循环的优雅写法
python
JYCJ_1 小时前
星愿池·子项清单
python