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

运行结果:

相关推荐
__lai6 分钟前
iflow cli一键安装脚本运行了,也正常安装了,但是无法通过iflow命令进入软件。在termux安装iflow-cli AI工具
linux·人工智能·termux
Aspect of twilight8 分钟前
深度学习不同GPU性能比较
人工智能·深度学习
爱笑的眼睛1117 分钟前
超越`cross_val_score`:深入剖析Scikit-learn交叉验证API的设计哲学与高阶实践
java·人工智能·python·ai
火山引擎开发者社区22 分钟前
两大模型发布!豆包大模型日均使用量突破 50 万亿 Tokens
大数据·人工智能
小尘要自信24 分钟前
Bright Data AI Scraper Studio:企业级AI爬虫解决方案,让数据采集更智能
人工智能·爬虫·通过ai自动化爬虫·prompt生产爬虫·云端爬虫平台
丝瓜蛋汤24 分钟前
chunking-free RAG简介
人工智能·深度学习·机器学习
虹科汽车电子31 分钟前
重新定义精密协作:低成本CAN FD如何赋予机器人「指尖智慧」?
人工智能·can总线·机器人灵巧手
王中阳Go1 小时前
09 Go Eino AI应用开发实战 | Hertz Web 框架搭建
人工智能·后端·go
map_vis_3d1 小时前
JSAPIThree 加载单体三维模型学习笔记:SimpleModel 简易加载方式
笔记·学习·3d
智驱力人工智能1 小时前
从人海战术到智能巡逻 城市街道违规占道AI识别系统的实践与思考 占道经营检测系统价格 占道经营AI预警系统
人工智能·安全·yolo·目标检测·无人机·边缘计算