大家好,本页面是2023年零基础实践深度学习周作业,本次作业内容为基于本章学习到的内容(数据处理、飞桨API查询、模型结构、损失函数、优化算法等)尝试修改模型结构、损失函数、优化器、学习率等,提高模型的准确率,要求模型评估精度达到0.985及以上 即通过作业考核。如有疑问可以联系qq群助教。 note:项目中需保留训练好的模型和训练log,此外是模型评估精度。 导入相关的库 In [4] # 导入相关的库 import paddle import numpy as np from data_proce
时间: 2024-01-24 21:19:15 浏览: 86
ss import load_data, data_augmentation
import paddle.nn.functional as F
import time
# 设置参数
batch_size = 64
epochs = 10
learning_rate = 0.001
# 加载数据
train_loader, val_loader, test_loader = load_data(batch_size=batch_size)
# 自定义模型结构
class CustomNet(paddle.nn.Layer):
def __init__(self):
super(CustomNet, self).__init__()
self.conv1 = paddle.nn.Conv2D(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1)
self.bn1 = paddle.nn.BatchNorm2D(32)
self.conv2 = paddle.nn.Conv2D(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
self.bn2 = paddle.nn.BatchNorm2D(64)
self.conv3 = paddle.nn.Conv2D(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)
self.bn3 = paddle.nn.BatchNorm2D(128)
self.pool = paddle.nn.MaxPool2D(kernel_size=2, stride=2)
self.fc1 = paddle.nn.Linear(in_features=128*7*7, out_features=256)
self.fc2 = paddle.nn.Linear(in_features=256, out_features=10)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = self.pool(F.relu(self.bn2(self.conv2(x))))
x = F.relu(self.bn3(self.conv3(x)))
x = self.pool(x)
x = paddle.flatten(x, start_axis=1, stop_axis=-1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# 实例化模型
model = paddle.Model(CustomNet())
# 自定义损失函数
class CustomLoss(paddle.nn.Layer):
def __init__(self):
super(CustomLoss, self).__init__()
def forward(self, logits, labels):
loss = F.cross_entropy(logits, labels)
loss = paddle.mean(loss)
return loss
# 实例化损失函数
criterion = CustomLoss()
# 自定义优化器
optimizer = paddle.optimizer.Adam(learning_rate=learning_rate, parameters=model.parameters())
# 训练模型
model.prepare(optimizer, criterion, paddle.metric.Accuracy())
start_time = time.time()
model.fit(train_loader, epochs=epochs, eval_freq=10, save_dir='./checkpoints', save_freq=2)
end_time = time.time()
print('训练时间:{}s'.format(end_time - start_time))
# 评估模型
result = model.evaluate(val_loader)
print('模型评估精度为:{}'.format(result['accuracy']))
阅读全文