【tensorflow2.0】函数式API

(1)准备工作

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
#归一化
train_images = train_images /255.0
test_images = test_images /255.0

看一下train_images的形状,这个就是我们的输入形状:

train_images.shape

结果显示为(60000, 28, 28),第一维为个数,图像的维数为28×28.

(2)首先建立输入
Sequential模型需要直接先建立一个模型,而对于函数API,需要哪一层,直接调用它就可以。

input = keras.Input(shape=(28, 28))

Input里面的参数输入的是图像的维数!并不是个数!!!

(3)然后调用函数
先调用一个扁平层:

x = keras.layers.Flatten()(input)

将 keras.layers.Flatten()整体看作一个函数。

再调用一个Dense层:

x = keras.layers.Dense(32, activation='relu')(x)

再调用一个Dropout层:

x = keras.layers.Dropout(0.5)(x)

再调用一个输出64的Dense层:

x = keras.layers.Dense(64, activation='relu')(x)

最后输出:

output = keras.layers.Dense(10, activation='softmax')(x)

(4)建立模型
建立好input和output之后,需要用Model(inputs=, outputs=)函数建立model。

model = keras.Model(inputs=input, outputs=output)

函数keras.Model(inputs=x1, outputs=x2)会自动建立从x1到x2的模型。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值