tensorflow2面向对象实现数字识别
【摘要】 前面我们用过顺序结构实现过tensorflow2实现手写数字识别,顺序结构的好处是易于初学者理解,但是在实际开发当中,我们一般都用面向对象的方式来进行项目开发,以便达到代码的复用。
1.导入依赖包
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Flatten, Dense
import numpy as np
import time
2.加载数据集
(train_x, train_y), (test_x, test_y) = keras.datasets.mnist.load_data()
3.图片归一化
train_x, test_x = train_x / 255.0, test_x / 255.0
4.创建模型
class Mnist(tf.keras.Model):
def __init__(self):
super(Mnist, self).__init__()
self.dense1 = Flatten(input_shape=(28, 28))
self.dense2 = Dense(100, activation='relu')
self.dense3 = Dense(10, activation='softmax')
def call(self, inputs):
x = self.dense1(inputs)
x = self.dense2(x)
x = self.dense3(x)
return x
model = Mnist()
5.指定优化函数、损失函数、评价指标
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
6.记录模型开始训练时间
start_time = time.time()
7.训练模型
model.fit(train_x, train_y, batch_size=64, epochs=10, verbose=1, validation_freq=1)
Epoch 1/10
938/938 [==============================] - 2s 2ms/step - loss: 0.3147 - accuracy: 0.9126
Epoch 2/10
938/938 [==============================] - 2s 2ms/step - loss: 0.1486 - accuracy: 0.9571
Epoch 3/10
938/938 [==============================] - 2s 2ms/step - loss: 0.1059 - accuracy: 0.9692
Epoch 4/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0796 - accuracy: 0.9772
Epoch 5/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0632 - accuracy: 0.9812
Epoch 6/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0521 - accuracy: 0.9849
Epoch 7/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0422 - accuracy: 0.9872
Epoch 8/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0357 - accuracy: 0.9895
Epoch 9/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0292 - accuracy: 0.9918
Epoch 10/10
938/938 [==============================] - 2s 2ms/step - loss: 0.0254 - accuracy: 0.9929
<tensorflow.python.keras.callbacks.History at 0x1f69dd58400>
8.记录模型训练完成时间
end_time = time.time()
9.用测试集验证模型效果
test_loss, test_acc = model.evaluate(test_x, test_y, verbose=1)
predict = model.predict(test_x)
print('time:', end_time - start_time)
print(test_acc)
print('预测值:', np.argmax(predict[0]))
print('真实值:', test_y[0])
313/313 [==============================] - 1s 2ms/step - loss: 0.0771 - accuracy: 0.9776
time: 20.537350177764893
0.9775999784469604
预测值: 7
真实值: 7
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)