-
Notifications
You must be signed in to change notification settings - Fork 2
/
Transfer_Learning_VGG16.py
206 lines (155 loc) · 5.58 KB
/
Transfer_Learning_VGG16.py
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
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 22:10:18 2020
---------------------------------------------------------------------
-- Author: Vigneashwara Pandiyan
---------------------------------------------------------------------
Utils file for visualization/ Plots
"""
#%%
import torchvision.transforms as transforms
import torchvision
import torch
from torchsummary import summary
import matplotlib.pyplot as plt
import numpy as np
from torch.optim.lr_scheduler import StepLR
from mlxtend.plotting import plot_confusion_matrix
import seaborn as sns
from torchvision import datasets
from Heatmap import heatmap , annotate_heatmap
#torch.cuda.empty_cache()
from torch import optim, cuda
import os
from PIL import Image
import pandas as pd
import torchvision.models as models
from torch import nn
from collections import OrderedDict
# Whether to train on a gpu
train_on_gpu = cuda.is_available()
print(f'Train on gpu: {train_on_gpu}')
from Utils import *
#%%
classes = ('Balling', 'LoF', 'Nopores','Keyhole')
PATH = './VGG16-Pytorch.pth'
Trained_model = torch.load(PATH)
print(Trained_model)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
# setting the root directories and categories of the images
# Data--> https://polybox.ethz.ch/index.php/s/7tAitrlpVuUAxWJ
#%%
datadir = 'Bronze_dataset/'
traindir = datadir + 'Train/'
testdir = datadir + 'Test/'
#%%
for name, child in Trained_model.named_children():
if name == 'classifier':
for name2, params in child.named_parameters():
print(name,name2)
params.requires_grad = True
else:
for name2, params in child.named_parameters():
params.requires_grad = False
Trained_model.to(device)
summary(Trained_model, (3 ,32 ,32))
#%%
def get_lr(optimizer):
for param_group in optimizer.param_groups:
print('Learning rate =')
print(param_group['lr'])
return param_group['lr']
transform = transforms.Compose([transforms.Resize((512,512)),
transforms.ToTensor()])
#transform = transforms.Compose([transforms.ToTensor()])
trainload = datasets.ImageFolder(root=traindir, transform=transform)
trainset = torch.utils.data.DataLoader(trainload, batch_size=10,
shuffle=True, num_workers=0)
testload = datasets.ImageFolder(root=testdir, transform=transform)
testset = torch.utils.data.DataLoader(testload, batch_size=10,
shuffle=True, num_workers=0)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#device = torch.device("cpu")
print(device)
net= Trained_model
net.to(device)
costFunc = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(),lr=0.001,momentum=0.9)
scheduler = StepLR(optimizer, step_size = 25, gamma= 0.5 )
Loss_value =[]
Iteration_count=1
iteration=[]
Epoch_count=0
Total_Epoch =[]
Accuracy=[]
Learning_rate=[]
for epoch in range(2):
learingrate_value = get_lr(optimizer)
Learning_rate.append(learingrate_value)
closs = 0
scheduler.step()
for i,batch in enumerate(trainset,0):
data,output = batch
data,output = data.to(device),output.to(device)
prediction = net(data)
loss = costFunc(prediction,output)
# print("loss",loss)
closs += loss
# print("closs",closs)
optimizer.zero_grad()
loss.backward()
optimizer.step()
Iteration_count = Iteration_count + i
iteration.append(Iteration_count)
# closs = loss.item()
#print every 1000th time
if i%100 == 0:
print('[%d %d] loss: %.4f'% (epoch+1,i+1,loss))
loss_train = closs / i
print('Loss on epoch: [%d] is %.4f'% (epoch+1,loss_train))
Loss_value.append(loss_train)
correctHits=0
total=0
for batches in testset:
data,output = batches
data,output = data.to(device),output.to(device)
prediction = net(data)
# _,prediction = torch.max(prediction.data,1) #returns max as well as its index
prediction = torch.argmax(prediction, dim=1)
total += output.size(0)
correctHits += (prediction==output).sum().item()
Epoch_accuracy = (correctHits/total)*100
Accuracy.append(Epoch_accuracy)
print('Accuracy on epoch ',epoch+1,'= ',str((correctHits/total)*100))
Epoch_count = epoch+1
Total_Epoch.append (Epoch_count)
y_pred = []
y_true = []
correctHits=0
total=0
for batches in testset:
data,output = batches
data,output = data.to(device),output.to(device)
prediction = net(data)
# _,prediction = torch.max(prediction.data,1) #returns max as well as its index
prediction = torch.argmax(prediction, dim=1)
total += output.size(0)
correctHits += (prediction==output).sum().item()
prediction=prediction.data.cpu().numpy()
output=output.data.cpu().numpy()
y_true.extend(output) # Save Truth
y_pred.extend(prediction)
print('Accuracy = '+str((correctHits/total)*100))
print('Finished Training')
PATH = './VGG16Bronze-Pytorch.pth'
torch.save(net.state_dict(), PATH)
torch.save(net, PATH)
#Trained_model = torch.load(PATH)
#%%
Loss_value= torch.stack(Loss_value)
Loss_value=Loss_value.cpu().detach().numpy()
plots(iteration,Loss_value,Total_Epoch,Accuracy,Learning_rate,'VGG16_Transfer_Bronze')
count_parameters(net)
plotname= 'VGG16'+'_Transfer_Bronze'+'_confusion_matrix'+'.png'
plot_confusion_matrix(y_true, y_pred,classes,plotname)