cnn分类python
时间: 2023-07-01 19:23:29 浏览: 100
python实现CNN中文文本分类
下面是使用CNN进行图像分类的Python示例代码:
首先,导入必要的库:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
```
接下来,加载和预处理数据集:
```python
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
```
定义CNN模型:
```python
model = keras.Sequential(
[
keras.Input(shape=(32, 32, 3)),
layers.Conv2D(32, 3, padding="same", activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, 3, padding="same", activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(128, 3, padding="same", activation="relu"),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(10),
]
)
```
编译模型:
```python
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.Adam(lr=3e-4),
metrics=["accuracy"],
)
```
训练模型:
```python
model.fit(x_train, y_train, batch_size=64, epochs=10, verbose=2)
```
评估模型:
```python
model.evaluate(x_test, y_test, batch_size=64, verbose=2)
```
完整的代码示例:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
model = keras.Sequential(
[
keras.Input(shape=(32, 32, 3)),
layers.Conv2D(32, 3, padding="same", activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, 3, padding="same", activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(128, 3, padding="same", activation="relu"),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(10),
]
)
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.Adam(lr=3e-4),
metrics=["accuracy"],
)
model.fit(x_train, y_train, batch_size=64, epochs=10, verbose=2)
model.evaluate(x_test, y_test, batch_size=64, verbose=2)
```
阅读全文