函数式API简介
函数式API简介
导入相关库以及数据加载
相关库导入:
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
函数式定义模型
输入:
input = keras.Input(shape = (28, 28))
这里的意思就是可以传任意28*28的数据
模型定义:
x = keras.layers.Flatten()(input)
x = keras.layers.Dense(32, activation = 'relu')(x)
x = keras.layers.Dropout(0.5)(x)
x = keras.layers.Dense(64, activation = 'relu')(x)
输出:
output = keras.layers.Dense(10, activation = 'softmax')(x)
构建模型:
model = keras.Model(inputs = input, outputs = output)
model.summary()
模型编译
model.compile(
optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['acc']
)
模型训练
history = model.fit(
train_images,
train_labels,
epochs = 30,
validation_data = (test_images, test_labels)
)