-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetdata.py
More file actions
419 lines (367 loc) · 17.3 KB
/
getdata.py
File metadata and controls
419 lines (367 loc) · 17.3 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import torch
from torchvision import datasets
from torch.utils.data import DataLoader
from torchvision.transforms import ToTensor
import numpy as np
import os
import gzip
import matplotlib.pyplot as plt
from six.moves import cPickle as pickle
import platform
from torchvision import transforms
from PIL import Image
import scipy.io as sio # 在文件开头加上
class GetDataSet():
def __init__(self, dataSetName):
self.dataSetName = dataSetName
self.trainData = None
self.trainLabel = None
self.trainDataSize = None
self.testData = None
self.testLabel = None
self.testDataSize = None
if self.dataSetName == 'MNIST' or self.dataSetName == 'mnist':
self.mnistDataDistribution()
print("mnist!!")
elif self.dataSetName == 'EMNIST' or self.dataSetName == 'emnist':
self.emnistDataDistribution()
print("Emnist!!")
elif self.dataSetName == 'CIFAR10' or self.dataSetName == 'cifar10':
self.cifar10DataDistribution()
print("cifar10!!")
elif self.dataSetName == 'CIFAR100' or self.dataSetName == 'cifar100':
self.cifar100DataDistribution()
print("cifar100!!")
elif self.dataSetName == 'FASHIONMNIST' or self.dataSetName == 'fashionmnist':
self.fashionmnistDataDistribution()
print("fashion!!")
elif self.dataSetName == 'imagenette2' or self.dataSetName == 'IMAGENETTE2':
self.imagenette2DataDistribution()
elif self.dataSetName == 'SVHN' or self.dataSetName == 'svhn':
self.svhnDataDistribution()
print("SVHN!!")
def svhnDataDistribution(self):
data_dir = './data/SVHN'
train_data_path = os.path.join(data_dir, 'train_32x32.mat')
test_data_path = os.path.join(data_dir, 'test_32x32.mat')
# 加载数据
train_data = sio.loadmat(train_data_path)
test_data = sio.loadmat(test_data_path)
# 提取图像和标签
X_train = train_data['X'] # shape: (32, 32, 3, N)
y_train = train_data['y'].flatten() # shape: (N,)
X_test = test_data['X']
y_test = test_data['y'].flatten()
# SVHN 的标签是 1-10,其中 10 表示数字 0,需要调整
y_train[y_train == 10] = 0
y_test[y_test == 10] = 0
# {X:1 }
# 转换形状为 (N, 3, 32, 32)
X_train = X_train.transpose(3, 2, 0, 1).astype(np.float32) / 255.0
X_test = X_test.transpose(3, 2, 0, 1).astype(np.float32) / 255.0
self.trainData = X_train
self.trainLabel = y_train.astype(np.int64)
self.testData = X_test
self.testLabel = y_test.astype(np.int64)
# 创建均衡的测试集
balance_testData = []
balance_testLabel = []
class_index = [np.argwhere(self.testLabel == y).flatten() for y in range(10)]
min_number = min([len(class_) for class_ in class_index])
for number in range(10):
balance_testData.append(self.testData[class_index[number][:min_number]])
balance_testLabel += [number] * min_number
self.testData = np.concatenate(balance_testData, axis=0)
self.testLabel = np.array(balance_testLabel)
self.testLabel = torch.tensor(self.testLabel).to(torch.int64)
print(self.trainData.shape)
print(self.testLabel)
print(self.testLabel.shape)
def cifar100DataDistribution(self):
cifar100_dir = 'data/cifar-100-python'
print(self.trainLabel)
self.trainData, self.trainLabel, self.testData, self.testLabel = self.load_CIFAR100(cifar100_dir)
def load_CIFAR100(self, ROOT):
# f = os.path.join(ROOT, )
train_data = self.unpickle_cifar100(os.path.join(ROOT, 'train'))
test_data = self.unpickle_cifar100(os.path.join(ROOT, 'test'))
meta_data = self.unpickle_cifar100(os.path.join(ROOT, 'meta'))
# 提取特征和标签
X_train = train_data['data']
y_train_fine = train_data['fine_labels'] # 细粒度类别
y_train_coarse = train_data['coarse_labels'] # 粗糙类别
X_test = test_data['data']
y_test_fine = test_data['fine_labels']
y_test_coarse = test_data['coarse_labels']
print(X_train.shape)
# 将数据转换为合适的形状
X_train = X_train.reshape((len(X_train), 3, 32, 32)).transpose(0, 1, 2, 3)
X_train = X_train.astype(np.float32)
X_test = X_test.reshape((len(X_test), 3, 32, 32)).transpose(0, 1, 2, 3)
X_test = X_test.astype(np.float32)
print(X_train.shape)
# 类别名称
fine_label_names = meta_data['fine_label_names']
coarse_label_names = meta_data['coarse_label_names'] # 粗糙类别名称
y_train_fine = np.array(y_train_fine, dtype=np.int64)
y_train_coarse = np.array(y_train_coarse, dtype=np.int64)
y_test_fine = np.array(y_test_fine, dtype=np.int64)
y_test_coarse = np.array(y_test_coarse, dtype=np.int64)
print(y_train_coarse)
X_train = np.multiply(X_train, 1.0 / 255.0)
X_test = np.multiply(X_test, 1.0 / 255.0)
return X_train, y_train_coarse, X_test, y_test_coarse
def unpickle_cifar100(self, file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='latin1')
return dict
# def mnistDataDistribution(self, isIID):
#
# trainingData = datasets.CIFAR10(
# root="data",
# train=True,
# download=True,
# transform=ToTensor(),
# )
# trainData = []
# trainLabel = []
# for X, y in trainingData:
# trainData.append(X.tolist())
# trainLabel.append(y)
# self.trainDataSize = len(trainData)
# # ----------------------------------------------------------- #
# testingData = datasets.CIFAR10(
# root="data",
# train=False,
# download=True,
# transform=ToTensor(),
# )
# testData = []
# testLabel = []
# for X, y in testingData:
# testData.append(X.tolist())
# testLabel.append(y)
# self.testDataSize = len(testData)
# self.testData = torch.tensor(testData)
# self.testLabel = torch.tensor(testLabel)
# # ----------------------------------------------------------- #
#
# if isIID == True:
# self.trainData = torch.tensor(trainData)
# self.trainLabel = torch.tensor(trainLabel)
# print(1)
#
# else:
# trainDataT = np.array(trainData, dtype='float32')
# trainLabelT = np.array(trainLabel, dtype='int64')
# self.trainData = trainDataT
# self.trainLabel = trainLabelT
# print(self.trainData.shape)
def emnistDataDistribution(self, ):
data_dir = r'./data/EMNIST'
train_images_path = os.path.join(data_dir, 'emnist-balanced-train.csv')
test_images_path = os.path.join(data_dir, 'emnist-balanced-test.csv.gz')
import pandas as pd
import numpy as np
# 读取 CSV 文件
train_images = pd.read_csv(train_images_path)
test_images = pd.read_csv(train_images_path)
# 提取标签
train_labels = train_images.iloc[:, 0].values
test_labels = test_images.iloc[:, 0].values
# 提取图像数据并转换为 numpy 数组
train_images = train_images.iloc[:, 1:].values
train_images = train_images.astype(np.float32) # 将图像数据转换为 float32 类型
train_images = np.reshape(train_images, (-1, 1, 28, 28)) # 将图像数据重新整形为 28x28 的数组
test_images = test_images.iloc[:, 1:].values
test_images = test_images.astype(np.float32) # 将图像数据转换为 float32 类型
test_images = np.reshape(test_images , (-1, 1, 28, 28)) # 将图像数据重新整形为 28x28 的数组
# 打印标签和图像的形状
train_images = np.multiply(train_images, 1.0 / 255.0)
test_images = np.multiply(test_images, 1.0 / 255.0)
self.trainData = train_images
self.trainLabel = train_labels
self.testData = test_images
self.testLabel = test_labels
print(self.trainData.shape)
print(self.trainLabel.shape)
balance_testData = []
balance_testlabel = []
class_index = [np.argwhere(self.testLabel == y).flatten() for y in range(self.testLabel.max() + 1)]
min_number = min([len(class_) for class_ in class_index])
for number in range(self.testLabel.max() + 1):
balance_testData.append(self.testData[class_index[number][:min_number]])
balance_testlabel += [number] * min_number
print(min_number)
self.testData = np.concatenate(balance_testData, axis=0)
self.testLabel = np.array(balance_testlabel)
self.testLabel = torch.tensor(self.testLabel).to(torch.int64)
def mnistDataDistribution(self, ):
data_dir = r'./data/MNIST/raw'
train_images_path = os.path.join(data_dir, 'train-images-idx3-ubyte.gz')
train_labels_path = os.path.join(data_dir, 'train-labels-idx1-ubyte.gz')
test_images_path = os.path.join(data_dir, 't10k-images-idx3-ubyte.gz')
test_labels_path = os.path.join(data_dir, 't10k-labels-idx1-ubyte.gz')
train_images = self.extract_images(train_images_path)
# print(train_images.shape) # 图片的形状 (60000, 28, 28, 1) 60000张 28 * 28 * 1 灰色一个通道
# print('-' * 22 + "\n")
train_labels = self.extract_labels(train_labels_path)
# print("-" * 5 + "train_labels" + "-" * 5)
# print(train_labels.shape) # label shape (60000, 10)
# print('-' * 22 + "\n")
test_images = self.extract_images(test_images_path)
test_labels = self.extract_labels(test_labels_path)
# assert train_images.shape[0] == train_labels.shape[0]
# assert test_images.shape[0] == test_labels.shape[0]
#
#
self.train_data_size = train_images.shape[0]
self.test_data_size = test_images.shape[0]
#
# assert train_images.shape[3] == 1
# assert test_images.shape[3] == 1
train_images = train_images.reshape(train_images.shape[0], 1, train_images.shape[1], train_images.shape[2])
test_images = test_images.reshape(test_images.shape[0], 1, test_images.shape[1], test_images.shape[2])
train_images = train_images.astype(np.float32)
# 数组对应元素位置相乘
train_images = np.multiply(train_images, 1.0 / 255.0)
# print(train_images[0:10,5:10])
test_images = test_images.astype(np.float32)
test_images = np.multiply(test_images, 1.0 / 255.0)
self.trainData = train_images
self.trainLabel = np.argmax(train_labels == 1, axis = 1)
self.testData = test_images
self.testLabel = np.argmax(test_labels == 1, axis = 1)
print(self.trainData.shape)
balance_testData = []
balance_testlabel = []
class_index = [np.argwhere(self.testLabel == y).flatten() for y in range(self.testLabel.max() + 1)]
min_number = min([len(class_) for class_ in class_index])
for number in range(self.testLabel.max() + 1):
balance_testData.append(self.testData[class_index[number][:min_number]])
balance_testlabel += [number] * min_number
self.testData = np.concatenate(balance_testData, axis=0)
self.testLabel = np.array(balance_testlabel)
self.testLabel = torch.tensor(self.testLabel).to(torch.int64)
def fashionmnistDataDistribution(self, ):
print("执行了吗?")
data_dir = r'./data/FashionMNIST/raw'
train_images_path = os.path.join(data_dir, 'train-images-idx3-ubyte.gz')
train_labels_path = os.path.join(data_dir, 'train-labels-idx1-ubyte.gz')
test_images_path = os.path.join(data_dir, 't10k-images-idx3-ubyte.gz')
test_labels_path = os.path.join(data_dir, 't10k-labels-idx1-ubyte.gz')
train_images = self.extract_images(train_images_path)
# print(train_images.shape) # 图片的形状 (60000, 28, 28, 1) 60000张 28 * 28 * 1 灰色一个通道
# print('-' * 22 + "\n")
train_labels = self.extract_labels(train_labels_path)
# print("-" * 5 + "train_labels" + "-" * 5)
# print(train_labels.shape) # label shape (60000, 10)
# print('-' * 22 + "\n")
test_images = self.extract_images(test_images_path)
test_labels = self.extract_labels(test_labels_path)
# assert train_images.shape[0] == train_labels.shape[0]
# assert test_images.shape[0] == test_labels.shape[0]
#
#
self.train_data_size = train_images.shape[0]
self.test_data_size = test_images.shape[0]
#
# assert train_images.shape[3] == 1
# assert test_images.shape[3] == 1
train_images = train_images.reshape(train_images.shape[0], 1, train_images.shape[1], train_images.shape[2])
test_images = test_images.reshape(test_images.shape[0], 1, test_images.shape[1], test_images.shape[2])
train_images = train_images.astype(np.float32)
# 数组对应元素位置相乘
train_images = np.multiply(train_images, 1.0 / 255.0)
# print(train_images[0:10,5:10])
test_images = test_images.astype(np.float32)
test_images = np.multiply(test_images, 1.0 / 255.0)
self.trainData = train_images
self.trainLabel = np.argmax(train_labels == 1, axis = 1)
self.testData = test_images
self.testLabel = np.argmax(test_labels == 1, axis = 1)
print(self.trainData.shape)
print(self.trainLabel.shape)
def extract_images(self, filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = self._read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
(magic, filename))
num_images = self._read32(bytestream)
rows = self._read32(bytestream)
cols = self._read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = np.frombuffer(buf, dtype=np.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
def _read32(self, bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_labels(self, filename):
"""Extract the labels into a 1D uint8 numpy array [index]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = self._read32(bytestream)
if magic != 2049:
raise ValueError(
'Invalid magic number %d in MNIST label file: %s' %
(magic, filename))
num_items = self._read32(bytestream)
buf = bytestream.read(num_items)
labels = np.frombuffer(buf, dtype=np.uint8)
return self.dense_to_one_hot(labels)
def dense_to_one_hot(self, labels_dense, num_classes=10):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
def cifar10DataDistribution(self):
cifar10_dir = 'data/cifar-10-batches-py'
print(self.trainLabel)
self.trainData, self.trainLabel, self.testData, self.testLabel = self.load_CIFAR10(cifar10_dir)
def load_CIFAR10(self, ROOT):
""" load all of cifar """
xs = []
ys = []
for b in range(1, 6):
f = os.path.join(ROOT, 'data_batch_%d' % (b,))
X, Y = self.load_CIFAR_batch(f)
xs.append(X)
ys.append(Y)
Xtr = np.concatenate(xs)
Ytr = np.concatenate(ys)
del xs, ys
Xte, Yte = self.load_CIFAR_batch(os.path.join(ROOT, 'test_batch'))
X_train = np.multiply(Xtr, 1.0 / 255.0)
X_test = np.multiply(Xte, 1.0 / 255.0)
# Resize images to 224x224
# X_train = Xtr
# X_test = Xte
# X_train = torch.Tensor(Xtr).permute(0, 1, 2, 3) / 255.0
# X_test = torch.Tensor(Xte).permute(0, 1, 2, 3) / 255.0
return X_train, Ytr, X_test, Yte
def load_CIFAR_batch(self, filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = self.load_pickle(f)
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).transpose(0, 1, 2, 3, ).astype("float32")
Y = np.array(Y).astype("int64")
return X, Y
def load_pickle(self, f):
version = platform.python_version_tuple()
if version[0] == '2':
return pickle.load(f)
elif version[0] == '3':
return pickle.load(f, encoding='latin1')
raise ValueError("invalid python version: {}".format(version))
# g = GetDataSet("EMNIST")
# print(g.trainData)
# print(g.trainLabel)