把vgg16用在单通道灰度图上


1.把vgg16用在单通道灰度图上,具体做法就是直接将第一个卷积层的输入通道改为1

附完整代码:

import torch
from torch import nn
from torchvision.models.vgg import vgg16
from PIL import Image
import torchvision.transforms as transforms
img_to_tensor = transforms.ToTensor()
from torch.autograd import Variable
import numpy as np

vgg = vgg16(pretrained=True)
#更改vgg网络的input为单通道
vgg.features[0]=nn.Conv2d(1, 64, kernel_size=3, padding=1)

def inference(model, imgpath):
    model.eval()  # 必需,否则预测结果是错误的

    img = Image.open(imgpath)
    img = img.resize((224, 224))
    tensor = img_to_tensor(img)
    tensor = tensor.resize_(1, 1, 224, 224)

    result = model(Variable(tensor))
    result_npy = result.data.cpu().numpy()  # 将结果传到CPU,并转换为numpy格式
    max_index = np.argmax(result_npy[0])

    return max_index

imgpath = 'F:\pycharmProject\SRGAN-master\grey.png'
print(inference(vgg, imgpath))

2.vgg16模型减半,以pre_trained vgg16权重作为初始权重,重新训练vgg16(思路是这样,我还没运行过,因为还没下载ImageNet数据集,大家借鉴思路就行了)

附完整代码:

import torch
from torch import nn
from torchvision.models.vgg import vgg16
from PIL import Image
import torchvision.transforms as transforms
import torchvision.datasets as dsets
img_to_tensor = transforms.ToTensor()
from torch.autograd import Variable
import numpy as np
import torch.optim as optim

EPOCH=50
BATCH=4
LEARNING_RATE = 0.01

#process data
transform = transforms.Compose([
    transforms.RandomSizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize(mean = [ 0.485, 0.456, 0.406 ],
                         std  = [ 0.229, 0.224, 0.225 ]),
    ])

trainData = dsets.ImageFolder('../data/imagenet/train', transform, download=True)
testData = dsets.ImageFolder('../data/imagenet/test', transform)

trainLoader = torch.utils.data.DataLoader(dataset=trainData, batch_size=BATCH, shuffle=True)
testLoader = torch.utils.data.DataLoader(dataset=testData, batch_size=BATCH, shuffle=False)

#define network,网络大小减半
vgg = vgg16(pretrained=True)
vgg.features[0]=nn.Conv2d(3, 32, kernel_size=3, padding=1)
vgg.features[2]=nn.Conv2d(32, 32, kernel_size=3, padding=1)
vgg.features[5]=nn.Conv2d(32, 64, kernel_size=3, padding=1)
vgg.features[7]=nn.Conv2d(64, 64, kernel_size=3, padding=1)
vgg.features[10]=nn.Conv2d(64, 128, kernel_size=3, padding=1)
vgg.features[12]=nn.Conv2d(128, 128, kernel_size=3, padding=1)
vgg.features[14]=nn.Conv2d(128, 128, kernel_size=3, padding=1)
vgg.features[17]=nn.Conv2d(128, 256, kernel_size=3, padding=1)
vgg.features[19]=nn.Conv2d(256, 256, kernel_size=3, padding=1)
vgg.features[21]=nn.Conv2d(256, 256, kernel_size=3, padding=1)
vgg.features[24]=nn.Conv2d(256, 256, kernel_size=3, padding=1)
vgg.features[26]=nn.Conv2d(256, 256, kernel_size=3, padding=1)
vgg.features[28]=nn.Conv2d(256, 256, kernel_size=3, padding=1)
vgg.classifier[0]= nn.Linear(256 * 7 * 7, 4096)
vgg.cuda()

# #冻结层的代码如下
# for param in vgg.parameters():
#     param.requires_grad = False

# Loss and Optimizer
cost = nn.CrossEntropyLoss()
optimizer = optim.Adam(vgg16.parameters(), lr=LEARNING_RATE)

# Train the model
for epoch in range(EPOCH):
    for i, (images, labels) in enumerate(trainLoader):
    # for images, labels in trainLoader:
        images = Variable(images).cuda()
        labels = Variable(labels).cuda()

        # Forward + Backward + Optimize
        optimizer.zero_grad()
        outputs = vgg(images)
        loss = cost(outputs, labels)
        loss.backward()
        optimizer.step()

        if (i + 1) % 10 == 0:
            print('Epoch [%d/%d], Iter[%d/%d] Loss. %.4f' %(epoch + 1, EPOCH, i + 1, len(trainData) // BATCH, loss.item()))

# Test the model
vgg.eval()
correct = 0
total = 0

for images, labels in testLoader:
  images = Variable(images).cuda()
  outputs = vgg(images)
  _, predicted = torch.max(outputs.data, 1)
  total += labels.size(0)
  correct += (predicted.cpu() == labels).sum()

print('Test Accuracy of the model on the 10000 test images: %d %%' % (100 * correct / total))

# Save the Trained Model
torch.save(nn.state_dict(), 'cnn.pkl')

3.修改resnet网络中的层次结构,以pre_trained resnet权重作为初始权重

附完整代码:

import torchvision.models as models
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo


class CNN(nn.Module):

    def __init__(self, block, layers, num_classes=9):
        self.inplanes = 64
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        self.avgpool = nn.AvgPool2d(7, stride=1)
        # 新增一个反卷积层
        self.convtranspose1 = nn.ConvTranspose2d(2048, 2048, kernel_size=3, stride=1, padding=1, output_padding=0,
                                                 groups=1, bias=False, dilation=1)
        # 新增一个最大池化层
        self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
        # 去掉原来的fc层,新增一个fclass层
        self.fclass = nn.Linear(2048, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        # 新加层的forward
        x = x.view(x.size(0), -1)
        x = self.convtranspose1(x)
        x = self.maxpool2(x)
        x = x.view(x.size(0), -1)
        x = self.fclass(x)

        return x

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

# 加载model
resnet50 = models.resnet50(pretrained=True)
cnn = CNN(Bottleneck, [3, 4, 6, 3])
# 读取参数
pretrained_dict = resnet50.state_dict()
model_dict = cnn.state_dict()
# 将pretrained_dict里不属于model_dict的键剔除掉
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# 更新现有的model_dict
model_dict.update(pretrained_dict)
# 加载我们真正需要的state_dict
cnn.load_state_dict(model_dict)

 

 

小白,有错的话还请大神多指教。