使用fashion mnsit数据集
研究tensorflow 深度学习框架
fashion mnist 使用28x28的灰度图片
# -*- coding: utf-8 -*-
# TensorFlow and tf.keras
from com.tfmnist.demo.utils import mnist_reader
from tensorflow import keras
import tensorflow as tf
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
'''
matplotlib 是一个 Python 的 2D绘图库
image 和标签数据集
'''
train_images, train_labels = mnist_reader.load_mnist('data', kind='train')
test_images, test_labels = mnist_reader.load_mnist('data', kind='t10k')
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
print("train_images ", train_images.shape, " test_images", test_images.shape)
'''
预处理数据
使用2D绘图库来显示 image图片
'''
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
'''
显示训练集中的前 25 张图像,并在每张图像下显示类别名称
'''
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
遇到的异常
- 在使用 matplotlib 库显示 numpy数组image图片时,出现了 TypeError: Invalid dimensions for image data异常
pyplot.imshow()方法显示二维数组的图片导致dimensions 非法数据维度,因为fashion mnist 使用28x28的灰度图片,查看train_images.shape
是一维数组的格式,需要转换为二维数组,然后使用imshow显示
image_temp=train_images[0].reshape(28, 28)
plt.imshow(image_temp)
使用numpy reshape()方法把数组维度设置为28x28的二维数组
转换完成之后,查看下image_temp的shape
然后运行出来的效果图如下
或者在mnist_reader.load_mnist 里面修改
with gzip.open(images_path, 'rb') as imgpath:
images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 28, 28)
把np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16) , reshape 为三维数组reshape(len(labels), 28, 28)
- 在macbook os系统上运行相同的代码,图片无显示
需要在结尾再调用plt.show() 来显示图片,效果如下图
显示数据没有问题,继续下一步
预处理数据
我们将28,28的数组的像素值缩小到 0 到 1 之间,然后将其馈送到神经网络模型。为此,将图像组件的数据类型从整数转换为浮点数,然后除以 255。以下是预处理图像的函数
train_images = train_images / 255.0
test_images = test_images / 255.0
构建模型
构建神经网络需要先配置模型的层,然后再编译模型。
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
该网络中的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28x28 像素)转换成一维数组(28 * 28 = 784 像素)。可以将该层视为图像中像素未堆叠的行,并排列这些行。该层没有要学习的参数;它只改动数据的格式。
在扁平化像素之后,该网络包含两个 tf.keras.layers.Dense 层的序列。这些层是密集连接或全连接神经层。第一个 Dense 层具有 128 个节点(或神经元)。第二个(也是最后一个)层是具有 10 个节点的 softmax 层,该层会返回一个具有 10 个概率得分的数组,这些得分的总和为 1。每个节点包含一个得分,表示当前图像属于 10 个类别中某一个的概率。
编译模型
指定目标函数或者损失函数为 sparse_categorical_crossentropy,
损失函数对应的优化器(数学不好不懂这个算法),
和数据训练的指标为accuracy 精准度
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
下一步训练模型
model.fit(train_images, train_labels, epochs=5)
调用fit进行训练,训练次数epochs设置为5次,下面是训练,5次训练的所有日志
Epoch 1/5
32/60000 [..............................] - ETA: 2:58 - loss: 2.5790 - acc: 0.0938
1184/60000 [..............................] - ETA: 7s - loss: 1.3121 - acc: 0.5591
2624/60000 [>.............................] - ETA: 4s - loss: 1.0030 - acc: 0.6562
4032/60000 [=>............................] - ETA: 3s - loss: 0.8903 - acc: 0.6949
5664/60000 [=>............................] - ETA: 2s - loss: 0.8147 - acc: 0.7228
7456/60000 [==>...........................] - ETA: 2s - loss: 0.7597 - acc: 0.7403
9344/60000 [===>..........................] - ETA: 2s - loss: 0.7349 - acc: 0.7480
11136/60000 [====>.........................] - ETA: 1s - loss: 0.7056 - acc: 0.7584
12864/60000 [=====>........................] - ETA: 1s - loss: 0.6844 - acc: 0.7654
14432/60000 [======>.......................] - ETA: 1s - loss: 0.6660 - acc: 0.7712
16128/60000 [=======>......................] - ETA: 1s - loss: 0.6460 - acc: 0.7777
17856/60000 [=======>......................] - ETA: 1s - loss: 0.6351 - acc: 0.7810
19680/60000 [========>.....................] - ETA: 1s - loss: 0.6213 - acc: 0.7863
21536/60000 [=========>....................] - ETA: 1s - loss: 0.6091 - acc: 0.7899
23392/60000 [==========>...................] - ETA: 1s - loss: 0.5992 - acc: 0.7932
24992/60000 [===========>..................] - ETA: 1s - loss: 0.5910 - acc: 0.7960
26816/60000 [============>.................] - ETA: 1s - loss: 0.5842 - acc: 0.7982
28672/60000 [=============>................] - ETA: 1s - loss: 0.5765 - acc: 0.8006
30464/60000 [==============>...............] - ETA: 0s - loss: 0.5687 - acc: 0.8028
32320/60000 [===============>..............] - ETA: 0s - loss: 0.5612 - acc: 0.8053
34112/60000 [================>.............] - ETA: 0s - loss: 0.5560 - acc: 0.8068
35904/60000 [================>.............] - ETA: 0s - loss: 0.5508 - acc: 0.8084
37728/60000 [=================>............] - ETA: 0s - loss: 0.5471 - acc: 0.8092
39552/60000 [==================>...........] - ETA: 0s - loss: 0.5414 - acc: 0.8112
41408/60000 [===================>..........] - ETA: 0s - loss: 0.5363 - acc: 0.8129
43168