作者简介:大家好,自我介绍: 人工智能硕博在读、精通python、某大厂nlp算法经历、机器学习、深度学习、自然语言处理、计算机视觉
个人主页:数学是算法的灵魂
觉得uu写的不错的话 麻烦动动小手 点赞 收藏⭐ 评论
今天给大家带来的刷题系列是:pytorch 复现 FCN模型详细代码教程
直奔主题模型图:
环境配置
pycharm python3.8 pytorch1.8
pip配库模板
pip install tensorflow==2.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn **加粗样式** pip install --user jupyterlab -i https://pypi.tuna.tsinghua.edu.cn/simple
导包:
import cv2 import numpy as np import matplotlib.pyplot as plt from PIL import Image import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, random_split from torchvision import transforms from torchvision import models from tqdm import tqdm import warnings
模型代码:
class FCN(nn.Module): def __init__(self,): super(FCN, self).__init__() self.stage1 = nn.Sequential( nn.Conv2d(in_channels=2, out_channels=128, kernel_size=(8,8), padding=1), nn.ReLU(), nn.BatchNorm2d(num_features=96),# # nn.MaxPool2d(kernel_size=2, padding=0) ) self.stage2 = nn.Sequential( nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(5,5), padding=1), nn.ReLU(), nn.BatchNorm2d(num_features=256), # nn.MaxPool2d(kernel_size=2, padding=0) ) self.stage3 = nn.Sequential( nn.Conv2d(in_channels=256, out_channels=128, kernel_size=(3,3), padding=1), nn.ReLU(), nn.BatchNorm2d(num_features=128), # # nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, padding=1), # nn.ReLU(), # nn.BatchNorm2d(num_features=384), # # nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, padding=1), # nn.ReLU(), # nn.BatchNorm2d(num_features=256), # # nn.MaxPool2d(kernel_size=2, padding=0) ) self.stage4 = nn.Sequential( nn.AvgPool2d(kernel_size=2, padding=0), nn.Softmax() ) def forward(self, x): x = x.float() # conv1->pool1->输出 x = self.stage1(x) # conv2->pool2->输出 x = self.stage2(x) # conv3->pool3->输出输出, 经过上采样后, 需要用pool3暂存 x = self.stage3(x) pool3 = x # conv4->pool4->输出输出, 经过上采样后, 需要用pool4暂存 output = self.stage4(x) return output model=FCN() print(model)
结果打印: