-
Notifications
You must be signed in to change notification settings - Fork 0
/
bbb
225 lines (193 loc) · 7.16 KB
/
bbb
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
import os
import csv
# 定义数据集的根目录路径和输出 CSV 文件路径
root_dir = '/path/to/dataset'
csv_file = '/path/to/output/csv/file.csv'
# 遍历数据集的子文件夹,获取每个子文件夹的名称和路径
subdirs = [os.path.join(root_dir, d) for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))]
# 初始化 CSV 文件的表头和数据列表
header = ['filename', 'label']
data = []
# 遍历每个子文件夹,获取子文件夹中所有的 JPG 文件,并将其添加到数据列表中
for subdir in subdirs:
label = os.path.basename(subdir)
filenames = [f for f in os.listdir(subdir) if f.endswith('.jpg')]
for filename in filenames:
data.append([os.path.join(subdir, filename), label])
# 将数据列表写入 CSV 文件
with open(csv_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(data)
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader,Dataset
from torchvision.datasets import ImageFolder
import pandas as pd
import os
from PIL import Image
Define hyperparameters
batch_size = 64
num_epochs = 10
lr = 0.0001
device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')
train_transforms=transforms.Compose([
transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
Custom dataset class
class CustomDataset(Dataset):
def init(self, csv_file, root_dir, transform=None):
self.annotations = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
self.annotations.iloc[:,1] = self.annotations.iloc[:,1].apply(lambda x:0 if x == -1 else x)
stylus
Copy
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
img_path = os.path.join(self.root_dir, self.annotations.iloc[index, 0])
image = Image.open(img_path).convert('RGB')
label = self.annotations.iloc[index, 1]
if self.transform:
image = self.transform(image)
return image, label
Load custom dataset
train_dataset = CustomDataset(csv_file='/home/DataBase1/jyp/mini-imagenet/trainall.csv', root_dir='/home/DataBase1/jyp/mini-imagenet/images/', transform=train_transforms)
定义数据集
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
定义 teacher 网络
class TeacherNet(nn.Module):
def init(self):
super(TeacherNet, self).init()
self.conv1 = nn.Conv2d(3, 128, kernel_size=4, stride=1, padding=3)
self.pool1 = nn.AvgPool2d(kernel_size=2, stride=2, padding=1)
self.conv2 = nn.Conv2d(128, 256, kernel_size=4, stride=1, padding=3)
self.pool2 = nn.AvgPool2d(kernel_size=2, stride=2, padding=1)
self.conv3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.conv4 = nn.Conv2d(256, 384, kernel_size=4, stride=1)
self.pool3 = nn.AdaptiveAvgPool2d((1,1))
self.fc = nn.Linear(384,19)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = self.pool1(x)
x = nn.functional.relu(self.conv2(x))
x = self.pool2(x)
x = nn.functional.relu(self.conv3(x))
x = self.conv4(x)
x = self.pool3(x)
x = x.view(x.size(0),-1)
x = self.fc(x)
#print(x.size())
return x
定义优化器和损失函数
teacher_net = TeacherNet()
teacher_net = teacher_net.to(device)
optimizer = optim.Adam(teacher_net.parameters(), lr=lr,weight_decay=0.00001)
criterion = nn.CrossEntropyLoss()
#criterion = nn.functional.mse_loss()
数据集上训练 teacher 网络
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = teacher_net(images)
#print(outputs.size(), labels.size())
loss = criterion(outputs.view(-1,19),labels.view(-1))
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.8f}'.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
保存预训练的 teacher 网络权重为 pth 文件
torch.save(teacher_net.state_dict(), 'teacher_net.pth')
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader,Dataset
from torchvision.datasets import ImageFolder
import pandas as pd
import os
from PIL import Image
Define hyperparameters
batch_size = 64
num_epochs = 10
lr = 0.0001
device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')
train_transforms=transforms.Compose([
transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
Custom dataset class
class CustomDataset(Dataset):
def init(self, csv_file, root_dir, transform=None):
self.annotations = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
self.annotations.iloc[:,1] = self.annotations.iloc[:,1].apply(lambda x:0 if x == -1 else x)
stylus
Copy
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
img_path = os.path.join(self.root_dir, self.annotations.iloc[index, 0])
image = Image.open(img_path).convert('RGB')
label = self.annotations.iloc[index, 1]
if self.transform:
image = self.transform(image)
return image, label
Load custom dataset
train_dataset = CustomDataset(csv_file='/home/DataBase1/jyp/mini-imagenet/trainall.csv', root_dir='/home/DataBase1/jyp/mini-imagenet/images/', transform=train_transforms)
定义数据集
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
定义 teacher 网络
class TeacherNet(nn.Module):
def init(self):
super(TeacherNet, self).init()
self.conv1 = nn.Conv2d(3, 128, kernel_size=4, stride=1, padding=3)
self.pool1 = nn.AvgPool2d(kernel_size=2, stride=2, padding=1)
self.conv2 = nn.Conv2d(128, 256, kernel_size=4, stride=1, padding=3)
self.pool2 = nn.AvgPool2d(kernel_size=2, stride=2, padding=1)
self.conv3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.conv4 = nn.Conv2d(256, 384, kernel_size=4, stride=1)
self.pool3 = nn.AdaptiveAvgPool2d((1,1))
self.fc = nn.Linear(384,19)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = self.pool1(x)
x = nn.functional.relu(self.conv2(x))
x = self.pool2(x)
x = nn.functional.relu(self.conv3(x))
x = self.conv4(x)
x = self.pool3(x)
x = x.view(x.size(0),-1)
x = self.fc(x)
#print(x.size())
return x
定义优化器和损失函数
teacher_net = TeacherNet()
teacher_net = teacher_net.to(device)
optimizer = optim.Adam(teacher_net.parameters(), lr=lr,weight_decay=0.00001)
criterion = nn.CrossEntropyLoss()
#criterion = nn.functional.mse_loss()
数据集上训练 teacher 网络
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = teacher_net(images)
#print(outputs.size(), labels.size())
loss = criterion(outputs.view(-1,19),labels.view(-1))
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.8f}'.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
保存预训练的 teacher 网络权重为 pth 文件
torch.save(teacher_net.state_dict(), 'teacher_net.pth')