TensorFlow2.0入门1-1 简单的手写字分类
内容总结自吴恩达TensorFlow2.0的课程
导入数据:
import tensorflow as tf
print(tf.__version__)
%matplotlib inline
读取数据集
没有数据集的可以点击下载。注意要下载在.keras\datasets\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='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
进行模型训练
使用adam优化,用交叉熵作为损失函数,用正确率作为指标。进行五次循环。
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
进行模型评估
model.evaluate(test_images, test_labels)
让训练及时停止
import tensorflow as tf
print(tf.__version__)
# 自定义停止函数
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('loss')<0.4): # 得到现在的准确率
print('达到60%z准确率')
self.model.stop_training = True
callbacks = myCallback()
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
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(512,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit(training_images,training_labels, epochs=5, callbacks=[callbacks])