MLP实现fashion_mnist数据集分类(2)-函数式API构建模型(tensorflow)

使用函数式API构建模型,使得模型可以处理多输入多输出。

1、查看tensorflow版本

python 复制代码
import tensorflow as tf

print('Tensorflow Version:{}'.format(tf.__version__))
print(tf.config.list_physical_devices())

2、fashion_mnist数据集分类模型

2.1 使用Sequential构建模型

python 复制代码
from keras import Sequential
from keras.layers import Flatten,Dense,Dropout
from keras import Input

model = Sequential()
model.add(Input(shape=(28,28)))
model.add(Flatten())
model.add(Dense(units=256,kernel_initializer='normal',activation='relu'))
model.add(Dropout(rate=0.1))
model.add(Dense(units=64,kernel_initializer='normal',activation='relu'))
model.add(Dropout(rate=0.1))
model.add(Dense(units=10,kernel_initializer='normal',activation='softmax'))
model.summary()

2.2 使用函数式API构建模型

python 复制代码
from keras.layers import Flatten,Dense,Dropout
from keras import Input,Model

input = Input(shape=(28,28))
x = Flatten()(input)
x = Dense(units=256,kernel_initializer='normal',activation='relu')(x)
x = Dropout(rate=0.1)(x)
x = Dense(units=64,kernel_initializer='normal',activation='relu')(x)
x = Dropout(rate=0.1)(x)
output = Dense(units=10,kernel_initializer='normal',activation='softmax')(x)
model = Model(inputs=input, outputs=output)
model.summary()

可以看到两个模型的结构是一样的,编译和训练也是一样的。

3、使用函数式API搭建多输入多输出模型

两个输入一个输出,对比两个图片是否一样。

python 复制代码
from keras.layers import Flatten,Dense,Dropout
from keras import Input,Model
import keras

input1 = Input(shape=(28,28))
input2 = Input(shape=(28,28))
x1 = Flatten()(input1)
x2 = Flatten()(input2)
x = keras.layers.concatenate([x1,x2])
x = Dense(units=256,kernel_initializer='normal',activation='relu')(x)
x = Dropout(rate=0.1)(x)
x = Dense(units=64,kernel_initializer='normal',activation='relu')(x)
x = Dropout(rate=0.1)(x)
output = Dense(units=1,kernel_initializer='normal',activation='sigmoid')(x)
model = Model(inputs=[input1,input2], outputs=output) # 两个输入,一个输出
model.summary()
相关推荐
MRDONG124 分钟前
从 Prompt 到智能体系统:Function Calling、Memory 与 Synthetic RAG 的全栈解析
人工智能·深度学习·神经网络·语言模型·自然语言处理·prompt
jinanwuhuaguo1 小时前
Ollama 全方位深度剖析:大模型时代的“Docker化”革命、算力普惠基础设施与安全边界重构
运维·开发语言·人工智能·深度学习·安全·docker·重构
盼小辉丶1 小时前
视觉Transformer实战 | Swin Transformer详解与实现
深度学习·计算机视觉·transformer
橙露12 小时前
特征选择实战:方差、卡方、互信息法筛选有效特征
人工智能·深度学习·机器学习
高洁0115 小时前
大模型微调进阶:多任务微调实战
人工智能·python·深度学习·机器学习·transformer
强盛小灵通专卖员15 小时前
基于深度学习 的急性阑尾炎CT 影像诊断
人工智能·深度学习·医学影像·ei会议
小超同学你好17 小时前
OpenClaw 深度解析与源代码导读 · 第3篇:Gateway——常驻控制面、单端口多协议与进程骨架
人工智能·深度学习·语言模型·gateway
yunhuibin18 小时前
videopipe学习之demo运行
人工智能·深度学习·学习
AGV算法笔记18 小时前
GaussianWorld:多帧融合到世界建模的跃迁
人工智能·深度学习·计算机视觉·自动驾驶·感知算法·三维感知
mailangduoduo18 小时前
实战对比PyTorch VS PyTorch Lighting以MNIST为例
人工智能·pytorch·python·深度学习·图像分类·全连接网络