函数式API简介
转自:https://www.cnblogs.com/miraclepbc/p/14312152.html
导入相关库以及数据加载
相关库导入:
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']
)
模型训练
标签:layers,函数,keras,简介,train,28,test,API,images From: https://www.cnblogs.com/gongzb/p/18224681history = model.fit( train_images, train_labels, epochs = 30, validation_data = (test_images, test_labels) )