-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
90 lines (60 loc) · 2.49 KB
/
utils.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
import numpy as np
def SetMyData(datatype, w=1):
if "CIFAR" == datatype:
data = PrepareCIFAR10Data()
Xtrain, Ytrain, Xval, Yval, Xtest, Ytest, nclasses = SplitDataTrnValTst(data)
return Xtrain * w, Ytrain, Xval * w, Yval, Xtest * w, Ytest, nclasses
if "MNIST" == datatype:
data = PrepareMNISTData()
imx = data[0].shape[1]
imy = data[0].shape[2]
nchannels = data[0].shape[3]
Xtrain, Ytrain, Xval, Yval, Xtest, Ytest, nclasses = SplitDataTrnValTst(data)
Xtrain = Xtrain.reshape(-1, imx * imy * nchannels)
Xval = Xval.reshape(-1, imx * imy * nchannels)
Xtest = Xtest.reshape(-1, imx * imy * nchannels)
return Xtrain * w, Ytrain, Xval * w, Yval, Xtest * w, Ytest, nclasses
def PrepareCIFAR10Data():
print("\n\n\n")
from tensorflow.keras.datasets import cifar10
(xtrain, ytrain), (xtest, ytest) = cifar10.load_data()
TrainInput = xtrain / 255.
TestInput = xtest / 255.
TrainInput -= np.mean(TrainInput, axis=0)
TestInput -= np.mean(TestInput, axis=0)
TrainInput /= (np.std(TrainInput))
TestInput /= (np.std(TestInput))
TrainLabels = np.zeros((len(ytrain), 10))
for i in range(0, len(ytrain)):
TrainLabels[i, ytrain[i]] = 1
TestLabels = np.zeros((len(ytest), 10))
for i in range(0, len(ytest)):
TestLabels[i, ytest[i]] = 1
return np.ascontiguousarray(TrainInput), np.ascontiguousarray(TrainLabels), np.ascontiguousarray(TestInput), np.ascontiguousarray(TestLabels), 10
def PrepareMNISTData():
from tensorflow.keras.datasets import mnist
(xtrain, ytrain), (xtest, ytest) = mnist.load_data()
TrainInput = xtrain.reshape(-1, 28, 28, 1) / 255.
TestInput = xtest.reshape(-1, 28, 28, 1) / 255.
TrainInput -= np.mean(TrainInput, axis=0)
TestInput -= np.mean(TestInput, axis=0)
TrainInput /= (np.std(TrainInput))
TestInput /= (np.std(TestInput))
TrainLabels = np.zeros((len(ytrain), 10))
for i in range(0, len(ytrain)):
TrainLabels[i, ytrain[i]] = 1
TestLabels = np.zeros((len(ytest), 10))
for i in range(0, len(ytest)):
TestLabels[i, ytest[i]] = 1
return TrainInput, TrainLabels, TestInput, TestLabels, 10
def SplitDataTrnValTst(data):
Xtrain = data[0]
Ytrain = data[1]
Xtst = data[2]
Ytst = data[3]
nval = 5000
XVal = Xtrain[:nval]
YVal = Ytrain[:nval]
Xtrn = Xtrain[nval:]
Ytrn = Ytrain[nval:]
return Xtrn, Ytrn, XVal, YVal, Xtst, Ytst, Ytst.shape[1]