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

运行结果:

相关推荐
闲人编程15 小时前
用Python识别图片中的文字(Tesseract OCR)
开发语言·python·ocr·识图·codecapsule
mwq3012315 小时前
MiniMind 模型架构创新技术详解
人工智能
骄傲的心别枯萎15 小时前
RV1126 NO.45:RV1126+OPENCV在视频中添加LOGO图像
人工智能·opencv·计算机视觉·音视频·rv1126
这儿有一堆花15 小时前
向工程神经网络对二进制加法的巧妙解决方案
人工智能·深度学习·神经网络
撬动未来的支点15 小时前
【AI】拆解神经网络“技术高墙”:一条基于“根本原理-补丁理论-AI部署”哲学的学习路径
人工智能·神经网络
盘古开天166615 小时前
从零开始:如何搭建你的第一个简单的Flask网站
后端·python·flask
li星野15 小时前
打工人日报#20251109
笔记
dxnb2215 小时前
【Datawhale25年11月组队学习:hello-agents+Task1学习笔记】
人工智能·学习
点云SLAM15 小时前
方差的迭代计算公式
大数据·深度学习·数据分析·概率论·数学原理·概论率
二进制星轨16 小时前
Transofrmer架构详解与PyTorch实现(附代码讲解)
人工智能·pytorch·python