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

运行结果:

相关推荐
Industio_触觉智能4 小时前
瑞芯微AI算力NPU路线图与协处理器|触觉智能瑞芯微RK方案商出品
人工智能·嵌入式硬件·硬件架构·智能硬件·npu·瑞芯微·端侧ai
EchoMind-Henry4 小时前
EviScene:识别出AI图,不等于查明真假
人工智能
打工仔折腾 AI4 小时前
在线PDF工具隐私焦虑?把BentoPDF部署到极空间NAS本地处理
人工智能·后端·python·pdf·ai agent 实战
AI视频工具指南4 小时前
AI短剧怎么做?一个矛盾怎样接着讲三集
人工智能·aigc·音视频
keyipatience4 小时前
JS学习笔记(2)数组,函数,作用域,对象
前端·javascript·笔记·学习·html
2603_965148115 小时前
商品价格监控 API 接口:从原理到实战的完整指南
java·前端·数据库·python·生活
单向箔5 小时前
10|Skill:把重复 prompt 固化成自己的 AI 工作流
人工智能·prompt·ai编程
没有梦想的咸鱼185-1037-16635 小时前
基金本子被批“科学问题不凝练”?试试这个“三问法”
人工智能·chatgpt·ai写作
你想知道什么?5 小时前
词向量总结-学习笔记
人工智能·笔记·学习
He BianGu5 小时前
【笔记】WPF中RenderOptions类的详细功能
笔记·wpf