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

运行结果:

相关推荐
Juchecar7 分钟前
解析视觉:视觉识别的七层模型
人工智能
2301_8217271744 分钟前
nfs服务
网络·笔记
报错小能手1 小时前
C++笔记 bind函数模板
开发语言·c++·笔记
FreeCode1 小时前
使用LangSmith追踪智能体运行
python·langchain·agent
Juchecar1 小时前
解析视觉:大脑如何“辨别”美丑?
人工智能
老蒋新思维1 小时前
紧跟郑滢轩,以 “学习力 +” 驱动 AI 与 IP 商业变革
网络·人工智能·学习·tcp/ip·企业管理·创始人ip·创客匠人
2501_941112141 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
Guheyunyi1 小时前
安防监控系统,如何为你的生活构筑智慧安全屏障?
大数据·人工智能·安全·信息可视化·生活
程序员晚枫1 小时前
Python文件类型大全:从.py到.pyd,你见过几种?
python