-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_emnist.py
251 lines (212 loc) · 8.5 KB
/
convert_emnist.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
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
"""
File for conversions of the EMNIST dataset to different feature representations
arguments:
-v: version of feature representation
"""
import argparse
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
from mlxtend.data import loadlocal_mnist
from skimage.filters import threshold_otsu
from skimage.morphology import binary_erosion
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', required=True, type=int, default=6, help="Version of feature representation")
args = parser.parse_args()
# helper function to get a moment
def moment(it, jt, p, q):
return np.sum(it**p * jt**q)
###########################
"""
Feature representation 1:
Columns are...
0 - area
1 - perimeter
2 - radius mean
3 - radius std
4 - theta mean
5 - theta std
6 - range in x direction
7 - range in y direction
8-17 - coefficients of 9-degree polynomial fit on r and theta
"""
def feature_transform_1(X_train, X_test):
for i in range(2):
if i == 0:
str = 'train'
X = X_train
else:
str = 'test'
X = X_test
FR = np.zeros((X.shape[0], 18))
write_path = os.getcwd()+f'/feature_representations/feature_representation_{args.version}_{str}.npy'
with open(write_path, 'w') as csvfile:
incr = X.shape[0] // 10
for j in range(X.shape[0]):
# print statement to view progress
if j % incr == 0 and i == 0: print(f"{round(100*(j/X.shape[0]), 2)}% of the way through the training set")
if j % incr == 0 and i == 1: print(f"{round(100*(j/X.shape[0]), 2)}% of the way through the testing set")
# get binary image and binary image outline
x = X[j,:].reshape(28,28)
x = np.divide(x, 255.)
t = threshold_otsu(x)
x = np.where(x < t, 0, 1)
er = binary_erosion(x)
x_er = x - er
# find area and permiter of binary image
area = np.sum(x)
perimeter = np.sum(x_er)
# tranform coordinates of binary image to relative polar coordinates
ii, jj = np.where(x_er == 1)
it = ii / 28
jt = jj / 28
cen = np.mean(it), np.mean(jt)
it = it - cen[0]
jt = jt - cen[1]
r = [np.sqrt(k**2 + l**2) for k,l in list(zip(it, jt))]
theta = [np.arctan(l/k) if k!= 0 else 0 for k,l in list(zip(it, jt))]
# find mean and standard deviation of polar coordinates
r_mean = np.mean(r)
r_std = np.std(r, ddof=1)
theta_mean = np.mean(theta)
theta_std = np.std(theta, ddof=1)
# find the ranges in x and y direction
x_range = np.max(jt) - np.min(jt)
y_range = np.max(it) - np.min(it)
# find 10-degree polynomial coefficients on polar coordinates
coeffs = np.polyfit(r, theta, 9)
# represent features as numpy array
FR[j, 0] = area
FR[j, 1] = perimeter
FR[j, 2] = r_mean
FR[j, 3] = r_std
FR[j, 4] = theta_mean
FR[j, 5] = theta_std
FR[j, 6] = x_range
FR[j, 7] = y_range
FR[j, 8:] = coeffs
# normalize features and write to np array
print("Writing to disk")
norm_FR = np.zeros(FR.shape)
for k in range(FR.shape[1]):
col = FR[:, k]
new_col = (col - np.mean(col)) / np.std(col, ddof=1)
norm_FR[:, k] = new_col
np.save(write_path, norm_FR)
"""
Feature representation 2:
Columns are...
0 - area
1 - perimeter
2 - radius mean
3 - radius std
4 - theta mean
5 - theta std
6 - range in x direction
7 - range in y direction
8-16 - all combinations of 1-3 degree moments
"""
def feature_transform_2(X_train, X_test):
for i in range(2):
if i == 0:
str = 'train'
X = X_train
else:
str = 'test'
X = X_test
FR = np.zeros((X.shape[0], 17))
write_path = os.getcwd()+f'/feature_representations/feature_representation_{args.version}_{str}.npy'
with open(write_path, 'w') as csvfile:
incr = X.shape[0] // 10
for j in range(X.shape[0]):
# print statement to view progress
if j % incr == 0 and i == 0: print(f"{round(100*(j/X.shape[0]), 2)}% of the way through the training set")
if j % incr == 0 and i == 1: print(f"{round(100*(j/X.shape[0]), 2)}% of the way through the testing set")
# get binary image and binary image outline
x = X[j,:].reshape(28,28)
x = np.divide(x, 255.)
t = threshold_otsu(x)
x = np.where(x < t, 0, 1)
er = binary_erosion(x)
x_er = x - er
# find area and permiter of binary image
area = np.sum(x)
perimeter = np.sum(x_er)
# tranform coordinates of binary image to relative polar coordinates
ii, jj = np.where(x_er == 1)
it = ii / 28
jt = jj / 28
cen = np.mean(it), np.mean(jt)
it = it - cen[0]
jt = jt - cen[1]
r = [np.sqrt(k**2 + l**2) for k,l in list(zip(it, jt))]
theta = [np.arctan(l/k) if k!= 0 else 0 for k,l in list(zip(it, jt))]
# find mean and standard deviation of polar coordinates
r_mean = np.mean(r)
r_std = np.std(r, ddof=1)
theta_mean = np.mean(theta)
theta_std = np.std(theta, ddof=1)
# find the ranges in x and y direction
x_range = np.max(jt) - np.min(jt)
y_range = np.max(it) - np.min(it)
# find the 2 kinds of first degree moments
m1 = moment(it, jt, 0, 1)
m2 = moment(it, jt, 1, 0)
# find the 3 kinds of second degree moments
m3 = moment(it, jt, 1, 1)
m4 = moment(it, jt, 2, 0)
m5 = moment(it, jt, 0, 2)
# find the 4 kinds of third degree moments
m6 = moment(it, jt, 1, 2)
m7 = moment(it, jt, 2, 1)
m8 = moment(it, jt, 0, 3)
m9 = moment(it, jt, 3, 0)
# represent features as numpy array
FR[j, 0] = area
FR[j, 1] = perimeter
FR[j, 2] = r_mean
FR[j, 3] = r_std
FR[j, 4] = theta_mean
FR[j, 5] = theta_std
FR[j, 6] = x_range
FR[j, 7] = y_range
FR[j, 8] = m1
FR[j, 9] = m2
FR[j, 10] = m3
FR[j, 11] = m4
FR[j, 12] = m5
FR[j, 13] = m6
FR[j, 14] = m7
FR[j, 15] = m8
FR[j, 16] = m9
# normalize features and write to np array
print("Writing to disk")
norm_FR = np.zeros(FR.shape)
for k in range(FR.shape[1]):
col = FR[:, k]
new_col = (col - np.mean(col)) / np.std(col, ddof=1)
norm_FR[:, k] = new_col
np.save(write_path, norm_FR)
###########################
versions = [1]
try:
args.version in versions
except ValueError:
print(f"Version {args.version} is not supported. Supported versions are {versions}")
funcs = [feature_transform_1, feature_transform_2]
func = funcs[args.version - 1]
print(f"Converting data to feature representation {args.version}")
Xtrain, ytrain = loadlocal_mnist(
images_path='emnist/emnist-letters-train-images-idx3-ubyte',
labels_path='emnist/emnist-letters-train-labels-idx1-ubyte')
Xtest, ytest = loadlocal_mnist(
images_path='emnist/emnist-letters-test-images-idx3-ubyte',
labels_path='emnist/emnist-letters-test-labels-idx1-ubyte')
if not os.path.exists(os.getcwd()+'/feature_representations'):
os.system('mkdir feature_representations/')
if not os.path.exists(os.getcwd()+'/feature_representations/ytrain.npy'):
np.save(os.getcwd()+'/feature_representations/ytrain.npy', ytrain)
if not os.path.exists(os.getcwd()+'/feature_representations/ytest.npy'):
np.save(os.getcwd()+'/feature_representations/ytest.npy', ytest)
func(Xtrain, Xtest)