函式式API簡介

有何m不可發表於2024-05-31

函式式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']
)

模型訓練

history = model.fit(
    train_images,
    train_labels,
    epochs = 30,
    validation_data = (test_images, test_labels)
)

相關文章