1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
| import torch from torch import nn,optim from torch.utils.data import Dataset, DataLoader from matplotlib import ticker import matplotlib.pyplot as plt import torchvision.transforms as transforms import torchvision from torchvision.datasets import ImageFolder, DatasetFolder import os from torchsummary import summary
num_classes = 12
cat_model_name = "cat_model.pth"
batch_size = 32 loss_fn = nn.CrossEntropyLoss() epochs = 1
transform = transforms.Compose([ transforms.ColorJitter(brightness=0.05, contrast=0.05, saturation=0.05, hue=0.05), transforms.Resize((256, 256)), transforms.CenterCrop(196), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomVerticalFlip(p=0.5), transforms.ToTensor(), transforms.Normalize(mean=[0.4848, 0.4435, 0.4023], std=[0.2744, 0.2688, 0.2757]), ])
eval_transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.CenterCrop(196), transforms.ToTensor(), transforms.Normalize(mean =[0.4848, 0.4435, 0.4023], std=[0.2744, 0.2688, 0.2757]), ])
class myRes(nn.Module): def __init__(self): super(myRes, self).__init__() if os.path.isfile(cat_model_name): a = False else: a = True self.resnet = torchvision.models.resnet50(pretrained=a) self.add_module('add_Linear', nn.Linear(1000, num_classes))
def forward(self, x): x = self.resnet(x) return x
def train(train_dataloader, model, loss_fn, optimizer): """ 训练网络
输入: train_dataloader: 训练集的dataloader model: 网络模型 loss_fn: 损失函数 optimizer: 优化器 """ model.train(True) for images, labels in train_dataloader: images, labels = images.to(device), labels.to(device) optimizer.zero_grad() pred = model(images) loss = loss_fn(pred, labels) loss.backward() optimizer.step()
size = len(train_dataloader.dataset) num_batches = len(train_dataloader) model.eval() test_loss, correct = 0, 0 model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for images, labels in train_dataloader: images, labels = images.to(device), labels.to(device) pred = model(images) test_loss += loss_fn(pred, labels).item() correct += (pred.argmax(1) == labels).sum().item() test_loss /= num_batches correct /= size print(f"Test Error: \n Train_Accuracy: {(100 * correct):>0.1f}%, Train_Avg_loss: {test_loss:>8f} \n") return correct, test_loss
def val(val_dataloader, model, loss_fn): """ 测试网络
输入: test_dataloader: 测试集的dataloader model: 网络模型 loss_fn: 损失函数 """ size = len(val_dataloader.dataset) num_batches = len(val_dataloader) model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for images, labels in val_dataloader: images, labels = images.to(device), labels.to(device) pred = model(images) test_loss += loss_fn(pred, labels).item() correct += (pred.argmax(1) == labels).sum().item() test_loss /= num_batches correct /= size print(f"Test Error: \n Val_Accuracy: {(100 * correct):>0.1f}%, Val_Avgloss: {test_loss:>8f} \n") return correct, test_loss
def train_correct_plt(epochs, X, Y1, Y2, Y3, Y4): plt.figure(figsize=(epochs*2, 8), dpi=80) plt.plot(X, Y1, label="val_correct", color="#FC331D", marker='*', linestyle="-") plt.plot(X, Y3, label="train_correct", color="#1D3162", marker='*', linestyle="-") for x_, y_ in zip(X, Y1): plt.text(x_, y_, y_, ha='left', va='bottom') for x_, y_ in zip(X, Y3): plt.text(x_, y_, y_, ha='left', va='bottom') plt.xticks(X, X) plt.gca().yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1)) plt.ylim(0.0, 1.1) plt.title("result") plt.xlabel("epoch") plt.ylabel("correct") plt.legend() plt.show() plt.clf() plt.cla()
plt.plot(X, Y2, label="val_loss", color="#F3991F", marker='o', linestyle="-") plt.plot(X, Y4, label="train_loss", color="#22a9Fd", marker='o', linestyle="-") for x_, y_ in zip(X, Y2): plt.text(x_, y_, y_, ha='left', va='bottom') for x_, y_ in zip(X, Y4): plt.text(x_, y_, y_, ha='left', va='bottom') plt.title("train_result") plt.ylim(0,max(Y2)) plt.xlabel("epoch") plt.ylabel("loss") plt.legend() plt.show()
if __name__ == '__main__': trian_folder_path = 'data\cat_12_train_new' train_dataset = ImageFolder(trian_folder_path, transform=transform) print(train_dataset) train_dataloader = DataLoader(train_dataset, batch_size=batch_size,shuffle=True)
val_folder_path = 'data\cat_12_val_new' val_dataset = ImageFolder(val_folder_path, transform=eval_transform) print(val_dataset) val_dataloader = DataLoader(val_dataset, batch_size=batch_size)
for images, labels in val_dataloader: print("Shape of X [N, C, H, W]: ", images.shape) print("Shape of y: ", labels.shape) break
device = "cuda" if torch.cuda.is_available() else "cpu" print("Using {} device".format(device)) model = myRes().to(device) print(model)
optim = optim.Adam(model.parameters(), lr=0.001)
if os.path.exists(cat_model_name): model.load_state_dict(torch.load(cat_model_name))
X = [] Y1 = [] Y2 = [] Y3 = [] Y4 = []
for t in range(epochs): print(f"Epoch {t+1}\n-------------------------------") correct_y3, test_loss_y4 = train(train_dataloader, model, loss_fn, optim) correct_y1, test_loss_y2 = val(val_dataloader, model, loss_fn)
X.append(t+1) Y1.append(round(correct_y1,3)) Y2.append(round(test_loss_y2,2)) Y3.append(round(correct_y3,3)) Y4.append(round(test_loss_y4,2))
train_correct_plt(epochs, X, Y1, Y2, Y3, Y4)
input_size = (3, 196, 196) in_channels = 3
''' from thop import profile
flops_transform = transforms.Compose([ transforms.Resize((256, 256)), # 缩放到指定大小 transforms.CenterCrop(196), # 中心随机裁剪 transforms.Normalize(mean=[0.4848, 0.4435, 0.4023], std=[0.2744, 0.2688, 0.2757]), # 归一化 ])
input_size = (1, 3, 196, 196) input = torch.randn(input_size).to() transformed_input = flops_transform(input) model = myRes() flops, params = profile(model, inputs=(transformed_input,)) print('FLOPs: %.2fG' % (flops / 1e9)) '''
torch.save(model.state_dict(), cat_model_name) print("Done!")
|