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

运行结果:

相关推荐
一点晖光8 分钟前
Docker 作图咒语生成器搭建指南
python·docker
IT空门:门主24 分钟前
Spring AI的教程,持续更新......
java·人工智能·spring·spring ai
smj2302_7968265231 分钟前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
美狐美颜SDK开放平台33 分钟前
美颜sdk是什么?如何将美颜SDK接入安卓/iOS直播平台?
人工智能·美颜sdk·直播美颜sdk·美颜api·美狐美颜sdk
AI营销资讯站34 分钟前
AI营销内容生产:哪些平台支持全球多语言内容同步生产?
大数据·人工智能
木头左34 分钟前
位置编码增强法在量化交易策略中的应用基于短期记忆敏感度提升
python
Acc1oFl4g35 分钟前
详解Java反射
java·开发语言·python
飞哥数智坊35 分钟前
AutoGLM 开源实测:一句话让 AI 帮我点个鸡排
人工智能·chatglm (智谱)
F_D_Z43 分钟前
简明 | Yolo-v3结构理解摘要
深度学习·神经网络·yolo·计算机视觉·resnet
2022.11.7始学前端1 小时前
n8n第九节 使用LangChain与Gemini构建带对话记忆的AI助手
java·人工智能·n8n