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

运行结果:

相关推荐
阿里云大数据AI技术1 小时前
SENSER识季 × 阿里云OpenSearch:从时尚灵感到自我表达
人工智能
the3clipse1 小时前
Windows 11 26H2 AI 功能使用指南:回顾、单击以执行与实时字幕
人工智能·windows·copilot+ pc·recall 回顾·单击以执行·实时字幕翻译·windows studio
geovindu1 小时前
python:Logistic Regression
开发语言·后端·python·算法
OpenPie丨拓数派2 小时前
拓数派以产品化FDE基座赋能某世界500强医疗科技企业,打造基于本体论的DRG检验医保合规AI原生服务
人工智能
摇滚侠2 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
阿里云大数据AI技术2 小时前
Hologres 数据沙箱:让 AI 在隔离环境中安全探索和验证
人工智能
geovindu3 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手3 小时前
2. 编程语言-Python-Anaconda
开发语言·python
aifannihao3 小时前
断言从 == 改成 > 0:用 Python 审出 git diff 里的测试降级
git·python·测试·标准库·代码审查
程序员cxuan3 小时前
Running Hub 上线 Motion
人工智能·aigc