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()
相关推荐
魔乐社区17 分钟前
DeepSeek在昇腾上的模型部署 - 常见问题及解决方案
人工智能·深度学习·deepseek
夜幕龙29 分钟前
深度生成模型(二)——基本概念与数学建模
人工智能·深度学习·transformer
山海青风35 分钟前
从零开始玩转TensorFlow:小明的机器学习故事 3
人工智能·机器学习·tensorflow
春末的南方城市1 小时前
VidSketch:具有扩散控制的手绘草图驱动视频生成
人工智能·深度学习·计算机视觉·aigc
紫雾凌寒1 小时前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
Francek Chen1 小时前
【大模型科普】AIGC技术发展与应用实践(一文读懂AIGC)
人工智能·深度学习·语言模型·大模型·aigc
孤寂大仙v2 小时前
深度学习实战:使用TensorFlow构建卷积神经网络(CNN)
深度学习·cnn·tensorflow
张焚雪10 小时前
关于卷积神经网络的一份介绍
人工智能·深度学习·神经网络·cnn
楼台的春风10 小时前
【图像的读写与基本操作】
图像处理·人工智能·深度学习·opencv·算法·计算机视觉·嵌入式
Y_3_712 小时前
30 分钟从零开始入门 CSS
开发语言·前端·css·人工智能·python·tensorflow