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

运行结果:

相关推荐
桂花很香,旭很美几秒前
Anthropic Agent 工程实战笔记(二)工具设计
笔记·架构·language model
逐梦苍穹4 分钟前
谷歌新研究:训练大模型时“偷懒跳过“50%更新,性能反而提升20%?
人工智能·google·论文·梯度更新
向哆哆5 分钟前
单车/共享单车目标检测数据集(适用YOLO系列)(已标注+划分/可直接训练)
人工智能·yolo·目标检测
新缸中之脑6 分钟前
轻量AI助手的兴起
人工智能
悠闲蜗牛�14 分钟前
深入浅出Spring Boot 3.x:新特性全解析与实战指南
开发语言·python
xinhuanjieyi24 分钟前
python获取租房70页信息,为了安全隐去了真实网址
开发语言·python
陈天伟教授27 分钟前
人工智能应用- 预测化学反应:02. 化学反应简介
人工智能·神经网络·算法·机器学习·推荐算法
光的方向_39 分钟前
04-Tokenization实战-从BPE到Hugging-Face应用
人工智能·深度学习·chatgpt·transformer
后端小肥肠39 分钟前
喂饭级教程!免费部署云端 OpenClaw + 打通飞书,自动抓取 ClawHub 技能并写入飞书表格
人工智能·agent