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()
相关推荐
明明真系叻2 小时前
最优传输理论学习(1)+PINN文献阅读
深度学习·学习
weixin_456904275 小时前
Transformer架构发展历史
深度学习·架构·transformer
番茄寿司5 小时前
具身智能六大前沿创新思路深度解析
论文阅读·人工智能·深度学习·计算机网络·机器学习
rengang665 小时前
25-TensorFlow:概述Google开发的流行机器学习框架
人工智能·机器学习·tensorflow
碧海银沙音频科技研究院8 小时前
DiVE长尾识别的虚拟实例蒸馏方法
arm开发·人工智能·深度学习·算法·音视频
AI浩8 小时前
基于多焦点高斯邻域注意力机制与大规模基准的视频人群定位
人工智能·深度学习·音视频
8Qi88 小时前
A Survey of Camouflaged Object Detection and Beyond论文阅读笔记
人工智能·深度学习·目标检测·计算机视觉·伪装目标检测
AI规划师-南木8 小时前
低代码开发医疗AI工具:5分钟搭建用药推荐系统,零基础也能落地
人工智能·深度学习·低代码·计算机视觉·推荐系统·rxjava·医疗ai
晚霞apple8 小时前
Graph + Agents 融合架构:2025年七大创新路径
论文阅读·人工智能·深度学习·神经网络·机器学习
浣熊-论文指导9 小时前
人工智能与生物医药融合六大创新思路
论文阅读·人工智能·深度学习·计算机网络·机器学习