"神经网络"听起来像是只有博士才能理解的复杂概念,但实际上,借助现代Python工具库,任何人都可以在几分钟内搭建并训练自己的第一个神经网络!本文将手把手带你用Python实现一个识别手写数字的神经网络,即使你是编程新手也能跟上。
确保已安装:
# 安装必要库
pip install numpy matplotlib tensorflow
我们将使用经典的MNIST数据集——包含70,000张28x28像素的手写数字灰度图,目标是让神经网络学会识别数字0-9。
[外链图片转存中…(img-serjGOIT-1746494010964)]
我们的第一个神经网络将包含:
[输入图像] → [隐藏层(ReLU)] → [输出层(Softmax)] → 预测数字
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
# 数据预处理
X_train = X_train.reshape(60000, 784).astype("float32") / 255 # 归一化到0-1
X_test = X_test.reshape(10000, 784).astype("float32") / 255
# 将标签转换为one-hot编码
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train, y_train,
batch_size=64,
epochs=10,
validation_split=0.2 # 用20%数据作为验证集
)
# 在测试集上评估
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"测试准确率: {test_acc:.4f}")
# 绘制训练曲线
plt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
数据预处理:
reshape(60000, 784)
:将28x28图像展平为784维向量/255
:将像素值从0-255归一化到0-1范围to_categorical
:将标签"3"转换为[0,0,0,1,0,0,0,0,0,0]模型构建:
Dense
:全连接层relu
:修正线性单元,解决梯度消失问题softmax
:将输出转换为概率分布模型编译:
adam
:自适应学习率优化器categorical_crossentropy
:多分类问题的损失函数模型训练:
batch_size=64
:每次用64个样本更新权重epochs=10
:完整遍历数据集10次model = keras.Sequential([
layers.Dense(256, activation='relu', input_shape=(784,)),
layers.Dense(128, activation='relu'), # 新增隐藏层
layers.Dense(10, activation='softmax')
])
model.add(layers.Dropout(0.2)) # 在层之间添加
from tensorflow.keras.optimizers import Adam
opt = Adam(learning_rate=0.001, decay=1e-6)
model.compile(optimizer=opt, ...)
# 随机选择一张测试图片
index = np.random.randint(0, X_test.shape[0])
img = X_test[index].reshape(28, 28)
# 显示图片
plt.imshow(img, cmap='gray')
plt.show()
# 模型预测
pred = model.predict(X_test[index:index+1])
print(f"模型预测: {np.argmax(pred)}")
print(f"实际标签: {np.argmax(y_test[index])}")
Q:我的准确率只有92%,正常吗?
A:对于这个简单网络,92-96%都是正常范围。要获得>98%的准确率需要更复杂的架构(如CNN)。
Q:训练时loss不下降怎么办?
Q:如何保存训练好的模型?
model.save('my_first_model.h5')
# 加载模型
loaded_model = keras.models.load_model('my_first_model.h5')
恭喜!你刚刚完成了:
这只是一个开始,接下来你可以探索:
记住,每个AI专家都曾训练过他们的"第一个神经网络"。你今天迈出的这一小步,可能是未来AI创新的一大步!