以下是一个使用 Python 和 TensorFlow 来基于 MNIST 数据集进行手写数字识别的简单示例代码: ```python import tensorflow as tf from tensorflow.keras.datasets import mnist # 加载 MNIST 数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 数据预处理 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype('float32') / 255 x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype('float32') / 255 # 将标签转换为独热编码 y_train = tf.keras.utils.to_categorical(y_train, num_classes=10) y_test = tf.keras.utils.to_categorical(y_test, num_classes=10) # 构建模型 model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=10, batch_size=128, validation_split=0.1) # 评估模型 test_loss, test_acc = model.evaluate(x_test, y_test) print('Test Loss:', test_loss) print('Test Accuracy:', test_acc) ``` 额外注意的逻辑点: 1. 调整超参数,如学习率、卷积核大小等,可能会提高模型性能。 2. 可以尝试不同的优化器,如 RMSprop 等。 3. 增加数据增强操作,如翻转、旋转等,能增加数据多样性。 [2025-04-24 14:33:30 | AI写代码神器 | 523点数解答]