人工智能课程中利用飞桨动态图搭建一个卷积神经网络,对包含斑马线的马路和不包含斑马线的马路图像进行分类的全部代码
时间: 2024-10-10 15:17:28 浏览: 46
在PaddlePaddle(飞桨)中,使用动态图构建一个卷积神经网络(CNN)进行图像分类是一个常见的实践。这里提供一个简单的示例,展示如何训练一个模型来区分包含斑马线和不包含斑马线的马路图像。请注意,由于篇幅限制,这个例子不会包括完整的数据加载和预处理部分,但在实际项目中这些都是必不可少的。
首先,你需要安装飞桨库:
```bash
pip install paddlepaddle
```
然后,你可以创建一个简单的动态图模型:
```python
import paddle
from paddle.nn import Conv2D, MaxPool2D, Flatten, Dense
# 定义卷积神经网络结构
class SimpleCNN(paddle.nn.Layer):
def __init__(self, in_channels=3, num_classes=2):
super(SimpleCNN, self).__init__()
self.conv1 = Conv2D(in_channels, 16, kernel_size=3, stride=1, padding=1)
self.pool1 = MaxPool2D(kernel_size=2)
self.conv2 = Conv2D(16, 32, kernel_size=3, stride=1, padding=1)
self.pool2 = MaxPool2D(kernel_size=2)
self.flatten = Flatten()
self.fc1 = Dense(32 * 4 * 4, 64) # 假设输入尺寸是28x28x16
self.output = Dense(64, num_classes)
def forward(self, x):
x = self.conv1(x)
x = paddle.nn.functional.relu(x)
x = self.pool1(x)
x = self.conv2(x)
x = paddle.nn.functional.relu(x)
x = self.pool2(x)
x = self.flatten(x)
x = self.fc1(x)
x = paddle.nn.functional.relu(x)
x = self.output(x)
return x
model = SimpleCNN() # 创建模型实例
loss_fn = paddle.nn.CrossEntropyLoss() # 定义损失函数
optimizer = paddle.optimizer.Adam(learning_rate=0.001) # 设置优化器
# 假设 `train_loader` 和 `test_loader` 分别是训练集和测试集的数据迭代器
for epoch in range(num_epochs): # 数量取决于您的需求
for batch_id, data in enumerate(train_loader):
images, labels = data
outputs = model(images) # 前向传播
loss = loss_fn(outputs, labels) # 计算损失
loss.backward() # 反向传播
optimizer.step() # 更新权重
optimizer.clear_grad() # 清空梯度
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.numpy():.4f}")
# 测试阶段
model.eval()
correct, total = 0, 0
with paddle.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = paddle.max(outputs, axis=1)
correct += (predicted == labels).sum().numpy()
total += labels.shape[0]
accuracy = correct / total * 100
print("Test Accuracy: %.2f%%" % accuracy)
```
阅读全文