下面是一个简单的深度学习模型例程,使用Keras(基于TensorFlow)构建一个卷积神经网络(CNN)来分类MNIST手写数字数据集。例程包括详细的代码和说明。
1. 安装所需库
首先,确保你已经安装了tensorflow
,如果没有,请运行以下命令来安装:
bash
复制代码
pip install tensorflow
2. 深度学习模型例程
导入必要的库
python
复制代码
import tensorflow as tf from tensorflow.keras import layers, models from tensorflow.keras.datasets import mnist import matplotlib.pyplot as plt
加载和准备数据
MNIST数据集已经内置在Keras中,因此可以直接加载。
python
复制代码
# 加载MNIST数据集 (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # 规范化:将像素值从[0, 255]缩放到[0, 1] train_images, test_images = train_images / 255.0, test_images / 255.0 # 将图像维度扩展为 [batch_size, height, width, channels] train_images = train_images.reshape((train_images.