本案例使用经典的MNIST手写数字数据集,通过Keras构建全连接神经网络,实现0-9数字的分类识别。文章将包含:
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.metrics import confusion_matrix
import seaborn as sns
3.1 加载数据集
# 加载内置MNIST数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print("训练集形状:", x_train.shape)
print("测试集形状:", x_test.shape)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 5s 0us/step 训练集形状: (60000, 28, 28) 测试集形状: (10000, 28, 28)
可以看到图像是28*28,每张图像一共有784个像素点。
3.2 数据可视化
plt.figure(figsize=(10,5))
for i in range(15):
plt.subplot(3,5,i+1)
plt.imshow(x_train[i], cmap='gray')
plt.title(f"Label: {
y_train[i]}")
plt.axis('off')
plt.tight_layout()
plt.savefig('mnist_samples.png', dpi=300)
plt.show()
4.1 数据归一化
# 将像素值缩放到0-1范围
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# 将图像展平为784维向量
x_train = x_train.reshape(-1,
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有