使用paddle框架写一段卷积神经网络代码
时间: 2023-06-17 19:08:21 浏览: 155
好的,以下是一个使用PaddlePaddle框架构建的卷积神经网络的代码:
```
import paddle
# 定义卷积神经网络
class CNN(paddle.nn.Layer):
def __init__(self):
super(CNN, self).__init__()
# 定义卷积层和池化层
self.conv1 = paddle.nn.Conv2D(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2)
self.pool1 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)
self.conv2 = paddle.nn.Conv2D(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2)
self.pool2 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)
# 定义全连接层
self.fc1 = paddle.nn.Linear(in_features=32*7*7, out_features=128)
self.fc2 = paddle.nn.Linear(in_features=128, out_features=10)
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 = paddle.flatten(x, start_axis=1, stop_axis=-1)
x = self.fc1(x)
x = paddle.nn.functional.relu(x)
x = self.fc2(x)
return x
# 定义训练过程
def train(model):
# 定义数据集和数据加载器
train_dataset = paddle.vision.datasets.MNIST(mode='train')
val_dataset = paddle.vision.datasets.MNIST(mode='test')
train_loader = paddle.io.DataLoader(train_dataset, batch_size=64, shuffle=True)
val_loader = paddle.io.DataLoader(val_dataset, batch_size=64, shuffle=False)
# 定义优化器和损失函数
optimizer = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())
criterion = paddle.nn.CrossEntropyLoss()
# 训练模型
epochs = 10
for epoch in range(epochs):
for i, (inputs, labels) in enumerate(train_loader):
# 前向传播
outputs = model(inputs)
loss = criterion(outputs, labels)
# 反向传播和更新参数
optimizer.clear_grad()
loss.backward()
optimizer.step()
# 打印训练信息
if (i+1) % 100 == 0:
print("Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}"
.format(epoch+1, epochs, i+1, len(train_loader), loss.numpy()[0]))
# 在验证集上测试模型
correct = 0
total = 0
for inputs, labels in val_loader:
outputs = model(inputs)
_, predicted = paddle.max(outputs, axis=1)
total += labels.shape[0]
correct += (predicted == labels).sum().numpy()[0]
accuracy = 100 * correct / total
print("Epoch [{}/{}], Val Accuracy: {:.2f}%".format(epoch+1, epochs, accuracy))
# 创建模型并进行训练
model = CNN()
train(model)
```
以上代码实现了一个简单的卷积神经网络,用于手写数字识别任务。您可以根据自己的需求进行修改和调整。
阅读全文