cnn模型代码TensorFlow
时间: 2024-10-22 20:02:30 浏览: 9
cnn_tensorflow.rar_CNN_tensorflow_tensorflow cnn
在TensorFlow框架中,卷积神经网络(Convolutional Neural Network,简称CNN)的代码通常包含以下几个步骤:
1. **导入库**:
```python
import tensorflow as tf
from tensorflow.keras import layers
```
2. **创建模型**:
```python
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(height, width, channels)), # 卷积层
layers.MaxPooling2D((2, 2)), # 池化层
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(), # 展平层
layers.Dense(128, activation='relu'), # 全连接层
layers.Dropout(0.5), # 防止过拟合
layers.Dense(num_classes, activation='softmax') # 输出层
])
```
3. **编译模型**:
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.categorical_crossentropy,
metrics=['accuracy'])
```
4. **训练模型**:
```python
model.fit(x_train, y_train, epochs=num_epochs, validation_data=(x_test, y_test))
```
5. **保存模型**:
```python
model.save('cnn_model.h5')
```
阅读全文