仅作为记录,大佬请跳过。
直接上代码
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '1/'
import copy
'''
缓冲区
'''
model_ft = models.resnet18(pretrained=True)
print('1*********************************************************')
print(model_ft)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 5)
print('2*********************************************************')
print(model_ft)
model_ft=models.resnet18(pretrained=True)
del model_ft.fc
model_ft.fc=lambda x:x
print('3*********************************************************')
print(model_ft)
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
from PIL import Image
from tqdm import tqdm
import torch
from torchvision import datasets, models, transforms
import skimage.io as io
import os
class_names = [0, 1, 2, 3]
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
data_transforms = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
inputs = Image.open('/Data4T/hufei/dataset_her2/dataset_her2_server_five-class/val/3/3_42_111184_63276.png').convert(
'RGB')
inputs0 = inputs
inputs = data_transforms(inputs)
model = model_ft
print(model)
inputs = torch.unsqueeze(inputs, dim=0)
print(inputs.shape)
with torch.no_grad():
outputs = model(inputs)
print(outputs.shape)
_model_ft=models.resnet18(pretrained=True)
num_ftrs = _model_ft.fc.in_features
fc = nn.Linear(num_ftrs, 5)
final_outputs=fc(outputs)
_, preds = torch.max(outputs, 1)
print('ok')
其中提取的特征outputs 的维度是(1,512), (特征融合后)(上述代码未进行特征融合) 再进行全连接分类层,得到的final_outputs的维度是(1,5)
参考
去除resnet全连接层,感谢大佬博主文章——传送门
|