CNN python
时间: 2023-10-12 10:06:01 浏览: 89
在Python中,使用卷积神经网络(CNN)进行图像分类的步骤如下:
1. 导入所需的库:
```
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
```
2. 加载MNIST手写数字图片数据集:
```
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
```
3. 数据预处理:
```
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images, test_images = train_images / 255.0, test_images / 255.0
```
4. 构建CNN模型:
```
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
```
5. 编译模型:
```
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
6. 训练模型:
```
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
```
7. 评估模型性能:
```
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('Test accuracy:', test_acc)
```
通过上述步骤,您可以在Python中使用CNN对MNIST手写数字图片数据集进行分类。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [CNN基本原理及Python实现](https://blog.csdn.net/vinojie/article/details/106199578)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文