TensorFlow课程02 计算机视觉初探

图像分类示例

设置epoch的回调,监听损失值达到指定数值后停止训练

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import tensorflow as tf
print(tf.__version__)

# 设置回调类,在每个epoch的生命周期过程中执行该回调,可以在该回调中检查各项指标
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('loss')<0.4):
print("\nReached 60% accuracy so cancelling training!")
# 停止训练
self.model.stop_training = True

callbacks = myCallback()

# 加载fashion_mnist数据集
mnist = tf.keras.datasets.fashion_mnist

(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

# 预览数据
import matplotlib.pyplot as plt
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0])

# 归一化处理
training_images = training_images / 255.0
test_images = test_images / 255.0

# 构建模型
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])

# 指定优化器、损失函数
model.compile(optimizer = tf.train.AdamOptimizer(),
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])

# 开始训练
model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks])

# 测试集上预测结果 查看准确率和损失值
model.evaluate(test_images, test_labels)

设置epoch的回调,监听准确率达到指定数值后停止训练

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
# YOUR CODE SHOULD START HERE
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
# 准确率高于指定阈值时,停止训练
if(logs.get('acc')>0.99):
print("\nReached 99% accuracy so cancelling training!")
self.model.stop_training = True

callbacks = myCallback()

x_train = x_train / 255.0
x_test = x_test / 255.0

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

history = model.fit(
x_train, y_train, epochs=5, callbacks=[callbacks]
)