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()
相关推荐
一直在努力的小宁几秒前
【阅读笔记】具身智能的真机数采,到了分水岭
人工智能·深度学习·机器学习·agent·具身智能·vlm·vln
AI人工智能+17 分钟前
营业执照识别技术通过图像预处理、版面定位、深度学习OCR、NLP语义解析与智能校验五步流程,实现对倾斜、反光、遮挡等复杂照片的毫秒级精准识别
人工智能·深度学习·自然语言处理·营业执照识别
码农幻想梦1 小时前
深度学习与神经网络(二)
人工智能·深度学习·神经网络
问天_观心2 小时前
大模型训练与推理优化(二)
人工智能·深度学习·学习·大模型·transformer
空奈qwq4 小时前
ANN 全连接神经网络入门指南:从神经元到深度学习的第一步
人工智能·python·深度学习·神经网络·算法·机器学习
维克兜率天5 小时前
【维克】弹性策略:用“乖离率“捕捉超跌反弹
android·开发语言·python·深度学习·kotlin·量化
ai小陈6 小时前
深度学习CUDA OOM排查:显存占用与碎片问题实战
服务器·人工智能·python·深度学习·ai·gpu算力
richard_yuu7 小时前
Hopfield 网络:联想记忆的「鼻祖」,为什么它能「回忆」?
深度学习·神经网络·yolo·机器学习
云和数据.ChenGuang7 小时前
langchain4j的RAG入门
人工智能·深度学习·机器学习·语言模型·fastapi
cg50178 小时前
大模型 SFT(监督微调)该怎么做?(实践版)
人工智能·深度学习·机器学习