使用传统全连接神经网络训练minist数据集(一)
发布日期:2021-05-12 19:17:52 浏览次数:11 分类:精选文章

本文共 1772 字,大约阅读时间需要 5 分钟。

使用全连接神经网络训练minist数据集

在机器学习和深度学习领域,使用全连接神经网络训练minist数据集是一个常见的入门项目。minist数据集包含28x28的黑白小图像,每张图像对应一个数字(0-9)。本文将详细介绍如何使用Keras框架搭建并训练一个全连接神经网络。

一、加载数据集

首先,我们需要加载并加载minist数据集。以下是代码实现:

from tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.datasets import mnistimport matplotlib.pyplot as pltimport cv2(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

数据预处理

由于输入数据的范围是0-255,我们需要将其归一化到[-1,1]范围内,以便神经网络更好地收敛。

# 归一化train_images = train_images.astype(float) / 255.0test_images = test_images.astype(float) / 255.0# 展开成矩阵形式train_images = train_images.reshape(60000, 28 * 28)test_images = test_images.reshape(10000, 28 * 28)# 转换为独热编码train_labels = to_categorical(train_labels)test_labels = to_categorical(test_labels)

二、搭建神经网络

我们将使用Keras的Sequential模型来构建一个简单的全连接网络。网络架构如下:

model = models.Sequential()model.add(layers.Dense(units=128, activation='relu', input_shape=(28*28),                      kernel_regularizer=regularizers.l1(0.0001)))model.add(layers.Dropout(0.01))model.add(layers.Dense(units=32, activation='relu',                      kernel_regularizer=regularizers.l1(0.0001)))model.add(layers.Dropout(0.01))model.add(layers.Dense(units=10, activation='softmax'))

三、训练网络

接下来,我们需要编译并训练模型。训练过程包括选择优化器和损失函数。

model.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])model.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)

四、模型评估

在训练完成后,我们可以使用evaluate方法测试模型在测试集上的性能。

test_loss, test_accuracy = model.evaluate(test_images, test_labels)print("test_loss:", test_loss, "test_accuracy:", test_accuracy)

通过以上步骤,我们成功使用全连接神经网络训练并评估了minist数据集。训练好的模型可以对测试集上的图像进行预测,具体实现如下:

y_pred = model.predict(test_images[:5])print(y_pred, "\n", test_labels[:5])

这个过程展示了基本的数据预处理、模型构建和训练流程,并通过测试集验证了模型的性能。

上一篇:使用卷积神经网络CNN训练minist数据集(二)
下一篇:CV面试题目总结(三) - 传统图像算法

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月29日 23时36分00秒