请同学们尝试修改以下代码,如修改网络结构、优化器、损失函数、学习率等,提升模型评估准确率,要求精度达到0.985。 In [2] # 定义模型结构 import paddle.nn.functional as F from paddle.nn import Conv2D, MaxPool2D, Linear # 多层卷积神经网络实现(可修改,例如加深网络层级) class MNIST(paddle.nn.Layer): def init(self): super(MNIST, self).init() #
时间: 2024-01-24 07:19:07 浏览: 20
# 修改后的代码
import paddle.nn.functional as F
import paddle.nn as nn
from paddle.nn import Conv2D, MaxPool2D, Linear
class MNIST(paddle.nn.Layer):
def __init__(self):
super(MNIST, self).__init__()
self.conv1 = Conv2D(in_channels=1, out_channels=32, kernel_size=3, stride=1)
self.max_pool1 = MaxPool2D(kernel_size=2, stride=2)
self.conv2 = Conv2D(in_channels=32, out_channels=64, kernel_size=3, stride=1)
self.max_pool2 = MaxPool2D(kernel_size=2, stride=2)
self.fc1 = Linear(in_features=64*5*5, out_features=512)
self.fc2 = Linear(in_features=512, out_features=10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.max_pool1(x)
x = self.conv2(x)
x = F.relu(x)
x = self.max_pool2(x)
x = paddle.flatten(x, start_axis=1, stop_axis=-1)
x = self.fc1(x)
x = F.relu(x)
x = F.dropout(x, p=0.5)
x = self.fc2(x)
return x
# 定义训练函数
def train(model):
model.train()
epoch_loss = 0
for batch_id, data in enumerate(train_loader()):
x_data = data[0]
y_data = data[1]
predicts = model(x_data)
loss = F.cross_entropy(predicts, y_data)
loss.backward()
optimizer.step()
optimizer.clear_grad()
epoch_loss += loss.numpy()[0]
return epoch_loss / len(train_loader())
# 定义测试函数
def test(model):
model.eval()
accuracies = []
for batch_id, data in enumerate(test_loader()):
x_data = data[0]
y_data = data[1]
predicts = model(x_data)
acc = paddle.metric.accuracy(predicts, y_data)
accuracies.append(acc.numpy()[0])
return np.mean(accuracies)
# 定义优化器
optimizer = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())
# 训练模型
EPOCH_NUM = 20
model = MNIST()
train_loader = paddle.batch(paddle.dataset.mnist.train(), batch_size=64, drop_last=True)
test_loader = paddle.batch(paddle.dataset.mnist.test(), batch_size=64, drop_last=True)
for epoch_id in range(EPOCH_NUM):
train_loss = train(model)
test_acc = test(model)
print("epoch_id: {}, train_loss: {}, test_acc: {}".format(epoch_id+1, train_loss, test_acc))
# 测试模型
acc = test(model)
print("Final test acc: {}".format(acc))
# 预测样例
params_file_path = 'mnist.pdparams'
model_dict = paddle.load(params_file_path)
model.load_dict(model_dict)
model.eval()
data = paddle.dataset.mnist.test()[0][0]
label = paddle.dataset.mnist.test()[0][1]
result = model(paddle.to_tensor(data))
print("Predict digit {}, label is {}".format(np.argmax(result.numpy()), label))