-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cifar10-stage1.py
184 lines (154 loc) · 7.48 KB
/
Cifar10-stage1.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
import os
import argparse
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from tqdm import tqdm
import pandas as pd
import torch
from torchvision import transforms
from torchvision.datasets import CIFAR10, STL10
from torch.utils.data import DataLoader
from data.stl10 import STL10PAIR
from model.resnet import ResNet18
from model.resnet_cifar import ResNet18withSobel
from tools.normalize import Normalize
from model.npc_model import NonParametricClassifier
from tools.averagetracker import AverageTracker
from tools.tools import check_clustering_metrics
from losses.Loss_IMI import crossview_contrastive_Loss_cifar
from losses.Loss_ID import Loss_ID
from losses.Loss_FMI import Loss_FMI_cifar
from PIL import Image
class CIFAR10Pair(CIFAR10):
"""CIFAR10 Dataset.
"""
def __getitem__(self, index):
img, target = self.data[index], self.targets[index]
img = Image.fromarray(img)
to_tensor = transforms.ToTensor()
if self.transform is not None:
pos_1 = self.transform(img)
pos_2 = to_tensor(img)
if self.target_transform is not None:
target = self.target_transform(target)
return pos_1, pos_2, target, index
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("-g", "--gpus", type=str, default="4")
parser.add_argument("-n", "--num_workers", type=int, default=8)
parser.add_argument('--batch_size', default=256, type=int, help='Number of images in each mini-batch')
parser.add_argument('--epochs', default=2000, type=int, help='Number of sweeps over the dataset to train')
parser.add_argument("--pretrained", default="", type=str, help="path to pretrained models")
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
return args
def main():
args = parse()
batch_size, epochs = args.batch_size, args.epochs
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_transform1 = transforms.Compose([
transforms.RandomResizedCrop(32),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8),
transforms.RandomGrayscale(p=0.2),
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])
train_data = CIFAR10Pair(root='data', train=True, transform=train_transform1, download=True)
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True,
drop_last=True)
low_dim = 128
net = ResNet18(low_dim=low_dim)
norm = Normalize(2)
npc = NonParametricClassifier(input_dim=low_dim,
output_dim=len(train_data),
tau=1.0,
momentum=0.5)
loss_id_func = Loss_ID(tau2=2.0)
loss_fmi_func = Loss_FMI_cifar()
net, norm = net.to(device), norm.to(device)
npc, loss_id, loss_fmi = npc.to(device), loss_id_func.to(device), loss_fmi_func.to(device)
# lr = 0.03
optimizer = torch.optim.SGD(net.parameters(),
lr=0.03,
momentum=0.9,
weight_decay=5e-4,
nesterov=False,
dampening=0)
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,
[500, 950, 1350, 2050, 2350, 2750, 3350, 3750, 4250, 4550],
gamma=0.5)
if torch.cuda.is_available():
net = torch.nn.DataParallel(net,
device_ids=range(len(
args.gpus.split(","))))
torch.backends.cudnn.benchmark = True
trackers = {n: AverageTracker() for n in ["loss", "loss_id", "loss_fmi", "loss_imi"]}
if os.path.exists(args.pretrained):
print('Restart from checkpoint {}'.format(args.pretrained))
checkpoint = torch.load(args.pretrained, map_location='cpu')
optimizer.load_state_dict(checkpoint['optimizer'])
net.load_state_dict(checkpoint['model'])
net.cuda()
start_epoch = checkpoint['epoch']
else:
print('No checkpoint file at {}'.format(args.pretrained))
start_epoch = 0
net = net.cuda()
file_name = "Cifar10-stage1_test1.py"
results = {'Epochs': [], 'loss_id': [],'loss_fmi':[],'loss_imi':[], 'k_means_acc': [], 'k_means_nmi': [],
'k_means_ari': []}
save_name_pre = '{}_{}_{}'.format(file_name, batch_size, epochs)
if not os.path.exists('results'):
os.mkdir('results')
tmp = 1
for epoch in range(start_epoch+1, epochs + 1):
net.train()
total_loss, total_num, train_bar = 0.0, 0, tqdm(train_loader)
for pos_1, pos_2, target, index in train_bar:
optimizer.zero_grad()
inputs_1 = pos_1.to(device, dtype=torch.float32, non_blocking=True)
inputs_2 = pos_2.to(device, dtype=torch.float32, non_blocking=True)
indexes = index.to(device, non_blocking=True)
features_1 = norm(net(inputs_1))
features_2 = norm(net(inputs_2))
outputs = npc(features_1, indexes)
loss_imi = crossview_contrastive_Loss_cifar(features_1, features_2)
loss_id = loss_id_func(outputs, indexes)
loss_fmi = loss_fmi_func(features_1)
#loss_fmi = loss_fmi(features_2)
tot_loss = loss_id + 0.01 * loss_fmi + 0.0001 * loss_imi
tot_loss.backward()
optimizer.step()
# track loss
trackers["loss"].add(tot_loss.item())
trackers["loss_id"].add(loss_id.item())
trackers["loss_imi"].add(loss_imi.item())
trackers["loss_fmi"].add(loss_fmi.item())
lr_scheduler.step()
# logging
# postfix = {name: t.avg() for name, t in trackers.items()}
# epoch_bar.set_postfix(**postfix)
# for t in trackers.values():
# t.reset()
# check clustering acc
# torch.cuda.empty_cache()
if (epoch == 0) or (((epoch + 1) % 10) == 0):
acc, nmi, ari = check_clustering_metrics(npc, train_loader)
print("Epoch:{} Loss_id:{} loss_fmi:{} loss_imi:{} Kmeans ACC, NMI, ARI = {}, {}, {}".format(epoch+1, loss_id, loss_fmi, loss_imi, acc, nmi, ari))
results['Epochs'].append(tmp * 10)
results['loss_id'].append(loss_id.item())
results['loss_fmi'].append(loss_fmi.item())
results['loss_imi'].append(loss_imi.item())
results['k_means_acc'].append(acc)
results['k_means_nmi'].append(nmi)
results['k_means_ari'].append(ari)
# Checkpoint
print('Checkpoint ...')
torch.save({'optimizer': optimizer.state_dict(), 'model': net.state_dict(),
'epoch': epoch + 1, 'npc': npc.state_dict()}, args.pretrained)
tmp = tmp + 1
# save statistics df = pd.DataFrame.from_dict(d, orient='index')
data_frame = pd.DataFrame.from_dict(data=results, orient='index')
data_frame.to_csv('results/{}_statistics.csv'.format(save_name_pre))
if __name__ == "__main__":
main()