Tensorflow2的Keras介面:compile、fit

dongcjava發表於2020-10-25

Tensorflow2的Keras介面:compile、fit

能將Train和test的過程封裝起來,使程式碼簡潔化,便於管理。

compile、fit、evaluate、predict函式中引數的具體說明請看:引數說明

完整程式碼例項:

import  tensorflow as tf
from    tensorflow.keras import datasets, layers, optimizers, Sequential, metrics


def preprocess(x, y):
    """
    x is a simple image, not a batch
    """
    x = tf.cast(x, dtype=tf.float32) / 255.
    x = tf.reshape(x, [28*28])
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x,y


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())



db = tf.data.Dataset.from_tensor_slices((x,y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz) 

sample = next(iter(db))
print(sample[0].shape, sample[1].shape)


network = Sequential([layers.Dense(256, activation='relu'),
                     layers.Dense(128, activation='relu'),
                     layers.Dense(64, activation='relu'),
                     layers.Dense(32, activation='relu'),
                     layers.Dense(10)])
network.build(input_shape=(None, 28*28))
network.summary()



# metrics:測試的指標
network.compile(optimizer=optimizers.Adam(lr=0.01),
		loss=tf.losses.CategoricalCrossentropy(from_logits=True),
		metrics=['accuracy']
	)

# db:訓練的資料集   epochs:訓練的次數    validation_data:測試的資料集   validation_freq:每訓練n次,測試一次,也可以設定一個指標,達到指標停止訓練
network.fit(db, epochs=5, validation_data=ds_val, validation_freq=2)
 
network.evaluate(ds_val) #整個訓練完成後,測試一次,也可以用一個新的資料集測試

sample = next(iter(ds_val))
x = sample[0]
y = sample[1] # one-hot
pred = network.predict(x) # [b, 10]獲得一個batch的值
# convert back to number 
y = tf.argmax(y, axis=1)
pred = tf.argmax(pred, axis=1)

print(pred)
print(y)

相關文章