Pytorch实现DenseNet,腾讯T3大牛手把手教你

本文详细介绍了DenseNet神经网络模型的各个组件,如Conv1、TransitionLayer和DenseLayer等,并展示了如何在Torchvision版本中使用。同时提到了作者提供的Python3.6环境下的资源包,包括代码示例和学习资料链接。
摘要由CSDN通过智能技术生成

print("Torchvision Version: ",torchvision.version)

all = [‘DenseNet121’, ‘DenseNet169’,‘DenseNet201’,‘DenseNet264’]

def Conv1(in_planes, places, stride=2):

return nn.Sequential(

nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),

nn.BatchNorm2d(places),

nn.ReLU(inplace=True),

nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

)

class _TransitionLayer(nn.Module):

def init(self, inplace, plance):

super(_TransitionLayer, self).init()

self.transition_layer = nn.Sequential(

nn.BatchNorm2d(inplace),

nn.ReLU(inplace=True),

nn.Conv2d(in_channels=inplace,out_channels=plance,kernel_size=1,stride=1,padding=0,bias=False),

nn.AvgPool2d(kernel_size=2,stride=2),

)

def forward(self, x):

return self.transition_layer(x)

class _DenseLayer(nn.Module):

def init(self, inplace, growth_rate, bn_size, drop_rate=0):

super(_DenseLayer, self).init()

self.drop_rate = drop_rate

self.dense_layer = nn.Sequential(

nn.BatchNorm2d(inplace),

nn.ReLU(inplace=True),

nn.Conv2d(in_channels=inplace, out_channels=bn_size * growth_rate, kernel_size=1, stride=1, padding=0, bias=False),

nn.BatchNorm2d(bn_size * growth_rate),

nn.ReLU(inplace=True),

nn.Conv2d(in_channels=bn_size * growth_rate, out_channels=growth_rate, kernel_size=3, stride=1, padding=1, bias=False),

)

self.dropout = nn.Dropout(p=self.drop_rate)

def forward(self, x):

y = self.dense_layer(x)

if self.drop_rate > 0:

y = self.dropout(y)

return torch.cat([x, y], 1)

class DenseBlock(nn.Module):

def init(self, num_layers, inplances, growth_rate, bn_size , drop_rate=0):

super(DenseBlock, self).init()

layers = []

for i in range(num_layers):

layers.append(_DenseLayer(inplances + i * growth_rate, growth_rate, bn_size, drop_rate))

self.layers = nn.Sequential(*layers)

def forward(self, x):

return self.layers(x)

class DenseNet(nn.Module):

def init(self, init_channels=64, growth_rate=32, blocks=[6, 12, 24, 16],num_classes=1000):

super(DenseNet, self).init()

bn_size = 4

drop_rate = 0

最后

不知道你们用的什么环境,我一般都是用的Python3.6环境和pycharm解释器,没有软件,或者没有资料,没人解答问题,都可以免费领取(包括今天的代码),过几天我还会做个视频教程出来,有需要也可以领取~

给大家准备的学习资料包括但不限于:

Python 环境、pycharm编辑器/永久激活/翻译插件

python 零基础视频教程

Python 界面开发实战教程

Python 爬虫实战教程

Python 数据分析实战教程

python 游戏开发实战教程

Python 电子书100本

Python 学习路线规划

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python爬虫全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
img

大家的负担。**

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
[外链图片转存中…(img-VLE8VX1R-1711201555986)]

以下是使用 PyTorch 实现 DenseNet 和学习策略的组合代码示例: 首先,我们需要导入必要的库: ```python import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms ``` 然后,我们定义我们的 DenseNet 模型。在这个例子中,我们使用了 DenseNet-121。模型的定义如下: ```python class DenseNet(nn.Module): def __init__(self): super(DenseNet, self).__init__() self.densenet = torchvision.models.densenet121(pretrained=True) self.densenet.classifier = nn.Linear(1024, 10) def forward(self, x): x = self.densenet(x) return x ``` 接下来,我们定义我们的学习策略。在这个例子中,我们使用了 SGD 优化器和学习率衰减。学习率衰减可以帮助我们在训练过程中逐渐减小学习率,以帮助我们更好地收敛。 ```python def get_optimizer(model): optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1) return optimizer, scheduler ``` 然后,我们定义我们的数据集和数据加载器。在这个例子中,我们使用 CIFAR-10 数据集。 ```python train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) test_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=4) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform) testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=4) ``` 接下来,我们定义我们的训练和测试函数。在训练函数中,我们使用交叉熵损失和 L2 正则化。在测试函数中,我们计算模型的准确率。 ```python def train(model, optimizer, criterion, trainloader, device): model.train() train_loss = 0.0 correct = 0 total = 0 for inputs, targets in trainloader: inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() return train_loss / len(trainloader), 100.0 * correct / total def test(model, criterion, testloader, device): model.eval() test_loss = 0.0 correct = 0 total = 0 with torch.no_grad(): for inputs, targets in testloader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) loss = criterion(outputs, targets) test_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() return test_loss / len(testloader), 100.0 * correct / total ``` 最后,我们可以开始训练和测试我们的模型。在这个例子中,我们使用 GPU 来加速训练。 ```python device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("Using device:", device) model = DenseNet().to(device) optimizer, scheduler = get_optimizer(model) criterion = nn.CrossEntropyLoss() best_acc = 0.0 for epoch in range(0, 10): scheduler.step() train_loss, train_acc = train(model, optimizer, criterion, trainloader, device) test_loss, test_acc = test(model, criterion, testloader, device) print("Epoch: {:2d} Train Loss: {:.2f} Train Acc: {:.2f}% Test Loss: {:.2f} Test Acc: {:.2f}%".format( epoch + 1, train_loss, train_acc, test_loss, test_acc)) if test_acc > best_acc: best_acc = test_acc torch.save(model.state_dict(), "best_model.pt") print("Best Test Acc: {:.2f}%".format(best_acc)) ``` 这就是一个使用 DenseNet 和学习策略的组合的 PyTorch 代码示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值