参考文章:
https://www.tensorflow.org/tutorials/keras/classification
https://www.datacamp.com/tutorial/tensorflow-tutorial
一、引入模块
- import tensorflow as tf
- import tensorflow.keras as keras
- import numpy as np
- import matplotlib.pyplot as plt
- import skimage
- from skimage import transform
- from skimage.color import rgb2gray
二、加载数据集
1、使用minist数据集
- fashion_mnist = keras.datasets.fashion_mnist
-
- (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
2、自定义数据集
- def load_data(data_directory):
- directories = [d for d in os.listdir(data_directory)
- if os.path.isdir(os.path.join(data_directory, d))]
- labels = []
- images = []
- all_image_paths = []
- for d in directories:
- label_directory = os.path.join(data_directory, d)
- file_names = [os.path.join(label_directory, f)
- for f in os.listdir(label_directory)
- # if f.endswith(".ppm")
- ]
- for f in file_names:
- images.append(skimage.io.imread(f))
- labels.append(int(d))
- all_image_paths.append(f)
- return images, labels
-
- ROOT_PATH = "E:/dataset/"
- train_data_directory = os.path.join(ROOT_PATH, "test/training")
- test_data_directory = os.path.join(ROOT_PATH, "test/testing")
-
- train_images, train_labels = load_data(train_data_directory)
- test_images, test_labels = load_data(test_data_directory)
-
- # 训练数据
- train_images = [transform.resize(image, (28, 28)) for image in train_images]
- train_images = np.array(train_images)
- train_images = rgb2gray(train_images)
- train_labels = np.array(train_labels)
- # 测试数据
- test_images = [transform.resize(image, (28, 28)) for image in test_images]
- test_images = np.array(test_images)
- test_images = rgb2gray(test_images)
- test_labels = np.array(test_labels)
三、构建模型
- # 创建模型
- model = keras.Sequential([
- keras.layers.Flatten(input_shape=(28, 28)),
- keras.layers.Dense(128, activation='relu'), # 激活函数 relu
- keras.layers.Dense(128)
- ])
- # 优化器
- model.compile(optimizer='adam',
- loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
- metrics=['accuracy'])
- # 训练模型
- model.fit(train_images, train_labels, epochs=100) # epochs迭代次数
- # 评估准确率
- test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
-
- print('\nTest test_loss:{0} accuracy:{1}'.format(test_loss, test_acc))
四、进行预测
- probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
- predictions = probability_model.predict(test_images)
- pre_value = np.argmax(predictions[2]) # 预测标签
- truth_value = test_labels[2] # 实际标签
-
- print('\nTest pre_value:{0} truth_value:{1}'.format(pre_value, truth_value))
-
- # 可视化 流程图
- tf.keras.utils.plot_model(model, 'model1.png', show_shapes=True, show_dtype=True,show_layer_names=True)
-
- # 查看图片
- fig = plt.figure(figsize=(10, 10))
- for i in range(10):
- truth = test_labels[i]
- prediction = np.argmax(predictions[i])
- plt.subplot(3, 4, 1 + i) # 五行 两列
- plt.axis('off') # 坐标轴 off关闭坐标轴
- color = 'green' if truth == prediction else 'red'
- plt.text(40, 10, "Truth: {0}\nPrediction: {1}".format(truth, prediction),
- fontsize=12, color=color)
- plt.imshow(test_images[i], cmap="gray") # gray显示灰度图 默认显示热图
- # 显示图片
- plt.show()