TensorFlow2.0教程-使用keras訓練模型

dpoerpoiwetiop發表於2020-02-17

1.一般的模型構造、訓練、測試流程

模型構造

inputs = keras.Input(shape=(784,), name=‘mnist_input’)
h1 = layers.Dense(64, activation=‘relu’)(inputs)
h1 = layers.Dense(64, activation=‘relu’)(h1)
outputs = layers.Dense(10, activation=‘softmax’)(h1)
model = keras.Model(inputs, outputs)

keras.utils.plot_model(model, ‘net001.png’, show_shapes=True)

model.compile(optimizer=keras.optimizers.RMSprop(),
loss=keras.losses.SparseCategoricalCrossentropy(),
metrics=[keras.metrics.SparseCategoricalAccuracy()])

載入資料

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype(‘float32’) /255
x_test = x_test.reshape(10000, 784).astype(‘float32’) /255

x_val = x_train[-10000:]
y_val = y_train[-10000:]

x_train = x_train[:-10000]
y_train = y_train[:-10000]

訓練模型

history = model.fit(x_train, y_train, batch_size=64, epochs=3,
validation_data=(x_val, y_val))
print(‘history:’)
print(history.history)

result = model.evaluate(x_test, y_test, batch_size=128)
print(‘evaluate:’)
print(result)
pred = model.predict(x_test[:2])
print(‘predict:’)
print(pred)

完整程式碼

import tensorflow
import tensorflow as tf
from tensorflow import keras
import numpy as np
from tensorflow.keras import layers
inputs = keras.Input(shape=(784,), name='mnist_input')
h1 = layers.Dense(64, activation='relu')(inputs)
h1 = layers.Dense(64, activation='relu')(h1)
outputs = layers.Dense(10, activation='softmax')(h1)
model = keras.Model(inputs, outputs)
# keras.utils.plot_model(model, 'net001.png', show_shapes=True)

model.compile(optimizer=keras.optimizers.RMSprop(),
             loss=keras.losses.SparseCategoricalCrossentropy(),
             metrics=[keras.metrics.SparseCategoricalAccuracy()])


#model.compile的引數說明 看官方的說  https://keras.io/models/model/
# 載入資料
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') /255
x_test = x_test.reshape(10000, 784).astype('float32') /255

x_val = x_train[-10000:]
y_val = y_train[-10000:]

x_train = x_train[:-10000]
y_train = y_train[:-10000]

# 訓練模型
history = model.fit(x_train, y_train, batch_size=64, epochs=3,
         validation_data=(x_val, y_val))
print('history:')
print(history.history)

result = model.evaluate(x_test, y_test, batch_size=128)
print('evaluate:')
print(result)
pred = model.predict(x_test[:2])
print('predict:')
index=tf.math.argmax(pred[0]).numpy()
print(index)

相關文章