卷积神经网络图像识别python
时间: 2023-09-14 10:06:26 浏览: 111
卷积神经网络(CNN)是一种用于图像识别的深度学习算法。在Python中,可以使用TensorFlow或Keras等库来实现CNN图像识别。以下是一个简单的CNN图像识别代码示例:
1. 导入必要的库
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
```
2. 加载数据集
```python
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
```
3. 数据预处理
```python
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
```
4. 建立模型
```python
model = keras.Sequential(
[
keras.Input(shape=(32, 32, 3)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
]
)
```
5. 编译模型
```python
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
```
6. 训练模型
```python
model.fit(x_train, y_train, batch_size=64, epochs=10, validation_split=0.1)
```
7. 评估模型
```python
model.evaluate(x_test, y_test, batch_size=64)
```
以上是一个简单的CNN图像识别代码示例,你可以根据自己的需求进行修改和扩展。
阅读全文