-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoverfind.py
327 lines (236 loc) · 6.99 KB
/
coverfind.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
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
import h5py
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import pdb
import cv2
from skimage.feature import hog
from skimage import data, color, exposure
from sklearn import svm
from skimage.transform import rotate
from skimage import transform as tf
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
import random
import cPickle
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from random import randint
import scipy.io
from sklearn import preprocessing
#classifier = SGDClassifier()
ntrain = 50000
nhalf = 40000
itrain = 0
print 'DFT Difference PC= 100'
matname = 'X2.mat'
clasname = 'cover_dft2.pkl'
n_components = 100
mat = scipy.io.loadmat('myFile.mat')
songData = mat['songData'][:,1:17000]
labels = mat['songData'][:,0]
songScaled = preprocessing.scale(songData)
ipca = IncrementalPCA(n_components=n_components, batch_size=2000)
X_ipca = ipca.fit_transform(songScaled,labels)
def getTrainData(X_ipca,labels):
i = 0
X_pos = []
y = []
while(i<15500):
label = labels[i]
j =0
temp = []
while(labels[i] == label):
temp.append(X_ipca[i])
j=j+1
i=i+1
for x1 in range(len(temp)/2):
for x2 in range(len(temp)):
if x1 != x2:
X_pos.append(np.concatenate((temp[x1],temp[x2]),axis=0))
itrain = i
print labels[i]
k = 0
X_neg = []
songRand = np.copy(X_ipca)
np.random.shuffle(songRand)
while(k < len(X_pos)):
m = randint(0,17999)
n = randint(0,17999)
if labels[m] != labels[n]:
X_neg.append(np.concatenate((X_ipca[m], X_ipca[n]),axis=0))
k = k+1
dic = {'X_pos': X_pos, 'X_neg': X_neg, 'X_ipca':X_ipca, 'labels':labels}
scipy.io.savemat(matname,dic)
def getTrainData2(X_ipca,labels):
i = 0
X_pos = []
y = []
while(i<15000):
label = labels[i]
j =0
temp = []
while(labels[i] == label):
temp.append(X_ipca[i])
j=j+1
i=i+1
for x1 in range(len(temp)/2):
for x2 in range(len(temp)):
if x1 != x2:
X_pos.append(abs(temp[x1]-temp[x2]))
itrain = i
print labels[i]
k = 0
X_neg = []
songRand = np.copy(X_ipca)
np.random.shuffle(songRand)
while(k < len(X_pos)):
m = randint(0,15000)
n = randint(0,15000)
if labels[m] != labels[n]:
X_neg.append(abs(X_ipca[m] - X_ipca[n]))
k = k+1
dic = {'X_pos': X_pos, 'X_neg': X_neg, 'X_ipca':X_ipca, 'labels':labels}
scipy.io.savemat(matname,dic)
#getTrainData(X_ipca,labels)
#ipca = IncrementalPCA(n_components=200, batch_size=1000)
def train_classifier():
global ntrain
global classifier
global n_components
all_classes = np.array([0, 1])
batch_size = 10000
mat2 = scipy.io.loadmat(matname)
#for batch in range(0, ntrain, batch_size):
for batch in range(0, 1):
#epochp = mat2['X_pos'][batch:batch+batch_size,:]
#epochn = mat2['X_neg'][batch:batch+batch_size,:]
epochp = mat2['X_pos']
epochn = mat2['X_neg']
train_data = np.append(epochp,epochn,0)
print train_data.shape
labels = np.ones(len(epochp)).reshape(-1,1)
labels = np.append(labels, np.zeros(len(epochn)).reshape(-1,1))
trainshuff = np.zeros([train_data.shape[0],n_components+1])
trainshuff[:,0] = labels
trainshuff[:,1:] = train_data
np.random.shuffle(trainshuff)
train_data = trainshuff[:,1:]
labels = trainshuff[:,0]
#pdb.set_trace()
print labels.shape
#Train the Classifier
classifier = svm.SVC()
classifier.fit(train_data,labels)
#classifier.fit(train_data,labels)
with open(clasname, 'wb') as fid:
cPickle.dump(classifier, fid)
# test_pos = mat2['X_pos'][:1000]
# test_neg = mat2['X_neg'][:1000]
# testset = np.append(test_pos,test_neg, 0)
# exp_labels = np.append((np.ones(len(test_pos)).reshape(-1,1)).T, (np.zeros(len(test_neg)).reshape(-1,1)).T,1)
# print classifier.score(testset,exp_labels.T)
# pred_labels = classifier.predict(np.array(testset)).T.astype(np.float32)
# mask = pred_labels==exp_labels
# correct = np.count_nonzero(mask)
# #pdb.set_trace()
# print correct*100.0/pred_labels.size
def test_classifier3():
#global labels
ntests = 500
with open(clasname, 'rb') as fid:
clf_loaded = cPickle.load(fid)
mat2 = scipy.io.loadmat(matname)
labels = mat2['labels'].T
avg = 0
nlabels = 0
i = 16200
nqueries = 0
while(nqueries < 500):
label = labels[i]
j =0
temp = []
while(labels[i] == label):
temp.append(mat2['X_ipca'][i])
j=j+1
i=i+1
for x1 in range(len(temp)):
for x2 in range(1):
test_pos =[]
test_neg =[]
query = []
if x1 != x2 and len(temp) >= 2:
test_pos.append(abs((temp[x1] - temp[x2])))
#test_pos.append(np.concatenate((temp[x1], temp[x2]),axis=0))
#print i
test_neg.append(abs((temp[x1] - mat2['X_ipca'][randint(0,10000)])))
#test_neg.append(np.concatenate((temp[x1], mat2['X_ipca'][randint(0,1000)]), axis=0))
query = np.append(np.array(test_pos),np.array(test_neg),0)
exp_labels = np.array([1,0])
pred_labels = clf_loaded.predict(np.array(query))
mask = pred_labels==exp_labels
correct = np.count_nonzero(mask)
#pdb.set_trace()
nqueries += 1
#print 'label=' +str(label)
#print correct*100.0/pred_labels.size
avg+=correct*100.0/pred_labels.size
print avg/500
def test_classifier():
#global labels
ntests = 2000
with open('cover3.pkl', 'rb') as fid:
clf_loaded = cPickle.load(fid)
mat2 = scipy.io.loadmat('X5.mat')
labels = mat2['labels'].T
avg = 0
nlabels = 0
i = 15500
while(i < 15500+ntests):
label = labels[i]
j =0
temp = []
test_pos =[]
test_neg =[]
while(labels[i] == label):
temp.append(mat2['X_ipca'][i])
j=j+1
i=i+1
for x1 in range(len(temp)):
for x2 in range(len(temp)):
if x1 != x2:
test_pos.append(abs((temp[x1] - temp[x2])))
test_neg.append(abs((temp[x1] - mat2['X_ipca'][randint(0,15500)])))
testset = np.append(np.array(test_pos),np.array(test_neg),0)
#pdb.set_trace()
if len(test_pos) > 0:
exp_labels = (np.ones(len(test_pos)).reshape(-1,1)).T
exp_labels = np.append((np.ones(len(test_pos)).reshape(-1,1)).T, (np.zeros(len(test_neg)).reshape(-1,1)).T,1)
pred_labels = clf_loaded.predict(np.array(testset)).T.astype(np.float32)
mask = pred_labels==exp_labels
correct = np.count_nonzero(mask)
#pdb.set_trace()
#print 'label=' +str(label)
#print correct*100.0/pred_labels.size
avg+=correct*100.0/pred_labels.size
nlabels = nlabels+1
print avg/nlabels
if __name__=="__main__":
getTrainData2(X_ipca,labels)
train_classifier()
test_classifier3()
# flip_id = np.fliplr(file['id'][0])
# flip_cam= np.fliplr(file['image'][0])
# print genFeatures(flip_id,flip_cam).shape
# id_img = file['id'][1]
# cam_img = file['image'][0]
# print genFeatures(id_img,cam_img).shape
# flip_id = flip_id.astype(np.uint8)
# T,R,F = get_random_transform()
# id_imgT = apply_transformation(id_img,T,R,F).astype(np.uint8)
# id_img = id_img.astype(np.uint8)
#cv2.imshow('Transformed',id_imgT)
#cv2.imshow('normal',id_img)
#cv2.waitKey(0)
cv2.destroyAllWindows()
#pdb.set_trace()