TensorFlow2 Python深度学习 - 函数式API(Functional API)

锋哥原创的TensorFlow2 Python深度学习视频教程:

https://www.bilibili.com/video/BV1X5xVz6E4w/

课程介绍

本课程主要讲解基于TensorFlow2的Python深度学习知识,包括深度学习概述,TensorFlow2框架入门知识,以及卷积神经网络(CNN),循环神经网络(RNN),生成对抗网络(GAN),模型保存与加载等。

TensorFlow2 Python深度学习 - 函数式API(Functional API)

TensorFlow 2.x 的函数式 API 允许用户以更灵活和可扩展的方式构建模型,相比于顺序模型,它能处理更复杂的结构,尤其是当你需要多个输入或输出,或者需要共享层时。

1. 函数式 API 简介

在 TensorFlow 2.x 中,函数式 API 是通过 tf.keras.Modeltf.keras.layers.Layer 类来实现的。它允许你定义非线性模型的多个输入和输出,不同于 Sequential API,它是层的线性堆叠。

2. 主要特点:

  • 多个输入输出:适用于多个输入、多个输出的模型。

  • 共享层:不同的模型部分可以共享相同的层。

  • 动态结构:能够创建复杂的模型结构,如跳跃连接、残差网络(ResNet)等。

3. 函数式 API 基本用法

3.1 示例代码:单一输入单一输出
复制代码
import tensorflow as tf
from keras import Input, layers, models
​
# 输入层
inputs = Input(shape=(32,))
​
# 一个全连接层
x = layers.Dense(64, activation='relu')(inputs)
​
# 输出层
outputs = layers.Dense(10, activation='softmax')(x)
​
# 创建模型
model = models.Model(inputs=inputs, outputs=outputs)
​
# 查看模型结构
model.summary()
3.2 示例代码:多个输入输出

假设你有一个模型,它接收两个输入,并输出两个结果。

复制代码
import tensorflow as tf
from keras import Input, layers, models
​
# 输入层1
input1 = tf.keras.Input(shape=(32,))
# 输入层2
input2 = tf.keras.Input(shape=(64,))
​
# 分别通过不同的全连接层
x1 = layers.Dense(64, activation='relu')(input1)
x2 = layers.Dense(64, activation='relu')(input2)
​
# 将两个中间层拼接
x = layers.concatenate([x1, x2])
​
# 输出层1
output1 = layers.Dense(10, activation='softmax')(x)
# 输出层2
output2 = layers.Dense(1, activation='sigmoid')(x)
​
# 创建模型
model = models.Model(inputs=[input1, input2], outputs=[output1, output2])
​
# 查看模型结构
model.summary()

4. 总结

  • TensorFlow 2.x 的函数式 API 提供了灵活的模型定义方式,可以处理更复杂的网络结构。

  • Sequential API 相比,函数式 API 允许处理多个输入和输出,适用于更加复杂的应用场景(如共享层、跳跃连接等)。

  • 通过 tf.keras.Input 定义输入,通过层的函数调用将数据传递给后续层,最后通过 models.Model 构建整个模型。

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
LaughingZhu2 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼2 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
高洁012 天前
未来三年,AI 落地的五个确定性判断一
人工智能·深度学习·机器学习·transformer·知识图谱
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型