这是一个图像分类的神经网络,但不是CNN,输入只是图像的每一个像素。用到的数据集是fashion mnist数据集。
这是跟着tensorflow官网上的第一个教程在vs code 中写的,只要安装了tensorflow、numpy、matplotlib就可以运行,
关于这些环境的安装我用的是anaconda,创建了一个新的python3环境,然后用conda install 安装的,再将anaconda里的环境导入到vs code中就可以了。
关于详细的教程点击这里查看
关于分类精度的总结:
教程中的隐藏层只有一层,128个神经元,训练了5轮,我得到的精度是0.8587
我对隐藏层进行了多次的调整
1.八层,每层16个神经元,训练5轮,精度:0.8458(保持128个神经元不变增加层数)
2.三层,72、64、20,训练5轮,精度:0.8595(保持128个神经元不变增加层数)
2.三层,72、64、20,训练10轮,精度0.8785(增加训练轮数,更加逼近最优)
4.十一层,128、128、100、80、60、40、40、40、20、20、15,训练10轮,精度0.8741
可以看出最终的精度在0.87至0.88之间随机,无法得到进一步的提高,
我认为主要的问题来自于输入层,教程所给的输入只考虑了每一个像素的数值,没有考虑图像的轮廓、纹理信息,从而导致分类精度无法得到进一步的提高。
一下是所有代码
from __future__ import absolute_import, division, print_function, unicode_literals
# 导入TensorFlow和tf.keras
import tensorflow as tf
from tensorflow import keras
# 导入辅助库
import numpy as np
import matplotlib.pyplot as plt
#导入Fashion MNIST数据集
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
#每个图像都映射到一个标签。由于类别名称不包含在数据集中,因此把他们存储在这里以便在绘制图像时使用:
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
#检查训练集中的第一个图像,您将看到像素值落在0到255的范围内:
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
#在馈送到神经网络模型之前,我们将这些值缩放到0到1的范围。为此,我们将像素值值除以255。
#重要的是,对训练集和测试集要以相同的方式进行预处理:
train_images = train_images / 255.0
test_images = test_images / 255.0
#显示训练集中的前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]])
plt.show()
#一个神经网络最基本的组成部分便是网络层。
#网络层从提供给他们的数据中提取表示,并期望这些表示对当前的问题更加有意义
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(100, activation=tf.nn.relu),
keras.layers.Dense(80, activation=tf.nn.relu),
keras.layers.Dense(60, activation=tf.nn.relu),
keras.layers.Dense(40, activation=tf.nn.relu),
keras.layers.Dense(40, activation=tf.nn.relu),
keras.layers.Dense(40, activation=tf.nn.relu),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(15, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
#在模型准备好进行训练之前,它还需要一些配置。这些是在模型的编译(compile)步骤中添加的:
#损失函数 —这可以衡量模型在培训过程中的准确程度。 我们希望将此函数最小化以"驱使"模型朝正确的方向拟合。
#优化器 —这就是模型根据它看到的数据及其损失函数进行更新的方式。
#评价方式 —用于监控训练和测试步骤。以下示例使用准确率(accuracy),即正确分类的图像的分数。
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#训练神经网络模型需要以下步骤:
#将训练数据提供给模型 - 在本案例中,他们是train_images和train_labels数组。
#模型学习如何将图像与其标签关联
#我们使用模型对测试集进行预测, 在本案例中为test_images数组。我们验证预测结果是否匹配test_labels数组中保存的标签。
#通过调用model.fit方法来训练模型 — 模型对训练数据进行"拟合"。
model.fit(train_images, train_labels, epochs=10)
#接下来,比较模型在测试数据集上的执行情况:
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
#通过训练模型,我们可以使用它来预测某些图像。
predictions = model.predict(test_images)
#我们可以用图表来查看全部10个类别
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()
# 绘制前X个测试图像,预测标签和真实标签
# 以蓝色显示正确的预测,红色显示不正确的预测
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()