-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2278 lines (2047 loc) · 83 KB
/
main.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import pyodbc
import pymorphy2
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import gensim.parsing.preprocessing as prep
from nltk.stem import SnowballStemmer
from nltk.stem.snowball import RussianStemmer
import binascii
import operator
import math
from sklearn.neighbors import KNeighborsClassifier
import numpy
from sklearn.metrics import precision_score,recall_score,f1_score,jaccard_similarity_score, roc_auc_score
from sklearn.model_selection import GridSearchCV
import time
from PIL import Image
import imagehash
import cv2
import scipy as sp
import sys
from matplotlib import pyplot as plt
from ImageWorker import ImageWorker
from sklearn import preprocessing
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.ensemble import RandomForestClassifier
def showCategory():
FILENAME = "E:\Study\Diploma\Avito duplicates\Category.csv\Category.csv"
with open(FILENAME, encoding='utf-8', mode = "r", newline="") as file:
reader = csv.reader(file)
i=0
for row in reader:
if i < 100:
print(row)
i+=1
else:
break
def showItemInfo():
FILENAME = "E:\Study\Diploma\Avito duplicates\ItemInfo_train.csv_2\ItemInfo_train.csv"
with open(FILENAME, encoding='utf-8', mode = "r", newline="") as file:
reader = csv.reader(file)
i=0
for row in reader:
if i < 100:
print(row)
i+=1
else:
break
def writeCategory(cursor):
FILENAME = "E:\Study\Diploma\Avito duplicates\Category.csv\Category.csv"
insertQuery = "INSERT INTO Category (categoryID, parentCategoryID) VALUES (?,?);"
with open(FILENAME, encoding='utf-8', mode = "r", newline="") as file:
reader = csv.reader(file)
i=0
for row in reader:
if i==0:
i+=1
continue
catID = int(row[0])
pcatID = int(row[1])
with cursor.execute(insertQuery, catID, pcatID):
print ('Successfully Inserted!')
def writeItemInfo(cursor, conn):
dropQuery = 'drop table if exists ItemInfo'
createTableQuery = 'create table ItemInfo( itemID int,' \
' categoryID int references Category(categoryID) on delete cascade, title nvarchar(1000),' \
'description nvarchar(max),' \
'images_array nvarchar(1000),' \
'attrsJSON nvarchar(max),' \
'price float,' \
'locationID int,' \
'metroID int,' \
'lat decimal(9,6),' \
'lon decimal(9,6))'
with cursor.execute(dropQuery):
print("ItemInfo dropped")
with cursor.execute(createTableQuery):
print("Table created")
FILENAME = "E:\Study\Diploma\Avito duplicates\ItemInfo_train.csv_2\ItemInfo_train.csv"
insertQuery = "INSERT INTO ItemInfo (itemID, categoryID, title, description, images_array, attrsJSON," \
"price, locationID, metroID, lat, lon ) VALUES (?,?,?,?,?,?,?,?,?,?,?);"
with open(FILENAME, encoding='utf-8', mode = "r", newline="") as file:
reader = csv.reader(file)
i=0
data = []
for row in reader:
if i==0:
i+=1
continue
itemID = categoryID = title = description=images_array=attrsJSON=price=locationID=metroID=lat=lon = None
try:
itemID = int(row[0])
categoryID = int(row[1])
title = row[2]
description = row[3]
images_array = row[4]
attrsJSON = row[5]
if row[6] == '':
price = 0
else:
price = float(row[6])
locationID = int(row[7])
if row[8] == '':
metroID = None
else:
metroID = int(float(row[8]))
lat = float(row[9])
lon = float(row[10])
data.append((itemID,categoryID,title,description,images_array,attrsJSON,price,locationID,metroID,lat,lon))
if i % 10000 == 0:
cursor.executemany(insertQuery,data)
conn.commit()
data=[]
except ValueError:
print("Value error")
print("Price = ",row[6])
print("ItemID = ",row[0])
with cursor.execute(insertQuery, itemID, categoryID, title,description,images_array,attrsJSON,
price,locationID,metroID,lat,lon):
print ('Inserted in exeption!')
finally:
i+=1
cursor.executemany(insertQuery,data)
conn.commit()
conn.close()
def writeDuplicate(cursor):
selectQuery = 'select top 1000 itemID_1,itemID_2 from ItemPairs where isDuplicate=1'
itemID = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
row = cursor.fetchone()
dropQuery = 'drop table if exists Duplicate'
createTableQuery = 'create table Duplicate(' \
'id int identity(1,1),'\
'itemID_1 int,' \
'categoryID_1 int,' \
' title_1 nvarchar(1000),' \
'description_1 nvarchar(max),' \
'images_array_1 nvarchar(1000),' \
'attrsJSON_1 nvarchar(max),' \
'price_1 float,' \
'locationID_1 int,' \
'metroID_1 int,' \
'lat_1 decimal(9,6),' \
'lon_1 decimal(9,6),' \
'itemID_2 int,' \
'categoryID_2 int,' \
' title_2 nvarchar(1000),' \
'description_2 nvarchar(max),' \
'images_array_2 nvarchar(1000),' \
'attrsJSON_2 nvarchar(max),' \
'price_2 float,' \
'locationID_2 int,' \
'metroID_2 int,' \
'lat_2 decimal(9,6),' \
'lon_2 decimal(9,6))'
with cursor.execute(dropQuery):
print("Duplicate dropped")
with cursor.execute(createTableQuery):
print("Duplicate created")
insertQuery = 'insert into Duplicate(itemID_1,categoryID_1,title_1,description_1,' \
'images_array_1,attrsJSON_1,price_1,locationID_1,metroID_1,lat_1,lon_1,' \
'itemID_2,categoryID_2,title_2,description_2,' \
'images_array_2,attrsJSON_2,price_2,locationID_2,metroID_2,lat_2,lon_2)' \
'values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
data = []
for id in itemID:
with cursor.execute(selectQuery, id):
row = cursor.fetchone()
data.extend(row)
row = cursor.fetchone()
data.extend(row)
with cursor.execute(insertQuery,data):
data=[]
print("Data inserted")
def writeDuplicateGenM(cursor, genMethod, size=1000):
selectQuery = 'select top ' + str(size) + ' itemID_1,itemID_2 from ItemPairs where isDuplicate=1 and generationMethod= ' + str(genMethod)
itemID = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
row = cursor.fetchone()
dropQuery = 'drop table if exists DuplicateGenM' + str(genMethod) + "_" + str(size)
createTableQuery = 'create table DuplicateGenM' + str(genMethod) + "_" + str(size) + '(' \
'id int identity(1,1),' \
'itemID_1 int,' \
'categoryID_1 int,' \
' title_1 nvarchar(1000),' \
'description_1 nvarchar(max),' \
'images_array_1 nvarchar(1000),' \
'attrsJSON_1 nvarchar(max),' \
'price_1 float,' \
'locationID_1 int,' \
'metroID_1 int,' \
'lat_1 decimal(9,6),' \
'lon_1 decimal(9,6),' \
'itemID_2 int,' \
'categoryID_2 int,' \
' title_2 nvarchar(1000),' \
'description_2 nvarchar(max),' \
'images_array_2 nvarchar(1000),' \
'attrsJSON_2 nvarchar(max),' \
'price_2 float,' \
'locationID_2 int,' \
'metroID_2 int,' \
'lat_2 decimal(9,6),' \
'lon_2 decimal(9,6))'
with cursor.execute(dropQuery):
print("Duplicate dropped")
with cursor.execute(createTableQuery):
print("Duplicate created")
insertQuery = 'insert into DuplicateGenM' + str(genMethod) + "_" + str(size) + '(itemID_1,categoryID_1,title_1,description_1,' \
'images_array_1,attrsJSON_1,price_1,locationID_1,metroID_1,lat_1,lon_1,' \
'itemID_2,categoryID_2,title_2,description_2,' \
'images_array_2,attrsJSON_2,price_2,locationID_2,metroID_2,lat_2,lon_2)' \
'values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
data = []
for id in itemID:
with cursor.execute(selectQuery, id):
row = cursor.fetchone()
data.extend(row)
row = cursor.fetchone()
data.extend(row)
with cursor.execute(insertQuery,data):
data=[]
print("Data inserted")
def writeNotDuplicate(cursor):
selectQuery = 'select top 1000 itemID_1,itemID_2 from ItemPairs where isDuplicate=0'
itemID = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
row = cursor.fetchone()
dropQuery = 'drop table if exists NoDuplicate'
createTableQuery = 'create table NoDuplicate(' \
'id int identity(1,1),' \
'itemID_1 int,' \
'categoryID_1 int,' \
' title_1 nvarchar(1000),' \
'description_1 nvarchar(max),' \
'images_array_1 nvarchar(1000),' \
'attrsJSON_1 nvarchar(max),' \
'price_1 float,' \
'locationID_1 int,' \
'metroID_1 int,' \
'lat_1 decimal(9,6),' \
'lon_1 decimal(9,6),' \
'itemID_2 int,' \
'categoryID_2 int,' \
' title_2 nvarchar(1000),' \
'description_2 nvarchar(max),' \
'images_array_2 nvarchar(1000),' \
'attrsJSON_2 nvarchar(max),' \
'price_2 float,' \
'locationID_2 int,' \
'metroID_2 int,' \
'lat_2 decimal(9,6),' \
'lon_2 decimal(9,6))'
with cursor.execute(dropQuery):
print("NoDuplicate dropped")
with cursor.execute(createTableQuery):
print("NoDuplicate created")
insertQuery = 'insert into NoDuplicate(itemID_1,categoryID_1,title_1,description_1,' \
'images_array_1,attrsJSON_1,price_1,locationID_1,metroID_1,lat_1,lon_1,' \
'itemID_2,categoryID_2,title_2,description_2,' \
'images_array_2,attrsJSON_2,price_2,locationID_2,metroID_2,lat_2,lon_2)' \
'values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
data = []
for id in itemID:
with cursor.execute(selectQuery, id):
row = cursor.fetchone()
data.extend(row)
row = cursor.fetchone()
data.extend(row)
with cursor.execute(insertQuery,data):
data=[]
print("Data inserted")
def writeNoDuplicateGenM(cursor, genMethod, size=1000):
selectQuery = 'select top ' + str(size) + ' itemID_1,itemID_2 from ItemPairs where isDuplicate=0 and generationMethod=' + str(genMethod)
itemID = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
row = cursor.fetchone()
dropQuery = 'drop table if exists NoDuplicateGenM' + str(genMethod) + '_' + str(size)
createTableQuery = 'create table NoDuplicateGenM' + str(genMethod) + '_' + str(size) + '(' \
'id int identity(1,1),' \
'itemID_1 int,' \
'categoryID_1 int,' \
' title_1 nvarchar(1000),' \
'description_1 nvarchar(max),' \
'images_array_1 nvarchar(1000),' \
'attrsJSON_1 nvarchar(max),' \
'price_1 float,' \
'locationID_1 int,' \
'metroID_1 int,' \
'lat_1 decimal(9,6),' \
'lon_1 decimal(9,6),' \
'itemID_2 int,' \
'categoryID_2 int,' \
' title_2 nvarchar(1000),' \
'description_2 nvarchar(max),' \
'images_array_2 nvarchar(1000),' \
'attrsJSON_2 nvarchar(max),' \
'price_2 float,' \
'locationID_2 int,' \
'metroID_2 int,' \
'lat_2 decimal(9,6),' \
'lon_2 decimal(9,6))'
with cursor.execute(dropQuery):
print("Duplicate dropped")
with cursor.execute(createTableQuery):
print("Duplicate created")
insertQuery = 'insert into NoDuplicateGenM' + str(genMethod) + '_' + str(size) + '(itemID_1,categoryID_1,title_1,description_1,' \
'images_array_1,attrsJSON_1,price_1,locationID_1,metroID_1,lat_1,lon_1,' \
'itemID_2,categoryID_2,title_2,description_2,' \
'images_array_2,attrsJSON_2,price_2,locationID_2,metroID_2,lat_2,lon_2)' \
'values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
data = []
for id in itemID:
with cursor.execute(selectQuery, id):
row = cursor.fetchone()
data.extend(row)
row = cursor.fetchone()
data.extend(row)
with cursor.execute(insertQuery,data):
data=[]
print("Data inserted")
def writeItemPairs(cursor):
dropQuery = 'drop table if exists ItemPairs'
createTableQuery = 'create table ItemPairs( itemID_1 int,' \
' itemID_2 int,' \
'isDuplicate tinyint,' \
'generationMethod tinyint)'
with cursor.execute(dropQuery):
print("ItemPairs dropped")
with cursor.execute(createTableQuery):
print("Table created")
FILENAME = "E:\Study\Diploma\Avito duplicates\ItemPairs_train.csv_2\ItemPairs_train.csv"
insertQuery = "INSERT INTO ItemPairs (itemID_1, itemID_2, isDuplicate, generationMethod)" \
" VALUES (?,?,?,?);"
with open(FILENAME, encoding='utf-8', mode = "r", newline="") as file:
reader = csv.reader(file)
i=0
for row in reader:
if i==0:
i+=1
continue
itemID_1 = int(row[0])
itemID_2 = int(row[1])
isDuplicate = int(row[2])
generationMethod = int(row[3])
with cursor.execute(insertQuery, itemID_1, itemID_2, isDuplicate,generationMethod):
print ('Successfully Inserted!')
def test_normalization(text1,text2):
morph = pymorphy2.MorphAnalyzer()
tokenizer = RegexpTokenizer(r'[^\W\d_]+|\d+')
stemmer = SnowballStemmer(language='russian',ignore_stopwords=True)
stop_words = stopwords.words('russian')
prep_text1 = prep.stem_text(prep.strip_short(text1))
tokens = tokenizer.tokenize(prep_text1)
tokens = [i.lower() for i in tokens if ( i not in stop_words and len(i)>3 )]
stems = [stemmer.stem(word)[:4] for word in tokens]
# morphs = [morph.parse(token)[0].normal_form for token in tokens ]
print('stems',stems)
tokens = tokenizer.tokenize(text2)
tokens = [i.lower() for i in tokens if ( i not in stop_words and len(i)>3 )]
# morphs = [morph.parse(token)[0].normal_form for token in tokens ]
stems = [stemmer.stem(word)[:4] for word in tokens]
print('stems',stems)
def textToVec(text):
text = text.lower()
tokenizer = RegexpTokenizer(r'[^\W\d_]+|\d+')
stop_words = stopwords.words('russian')
stemmer = SnowballStemmer(language='russian',ignore_stopwords=True)
morph = pymorphy2.MorphAnalyzer()
tokens = tokenizer.tokenize(text)
digits = []
for i in range(len(tokens)):
try:
token = tokens[i]
if token.isdigit():
float(token) # test digit
digits.append(token)
except ValueError:
print("ValueError has happened")
tokens = [i for i in tokens if (i not in stop_words and len(i)>=3 )]
stems = [stemmer.stem(word)[:3] for word in tokens]
morphs = [morph.parse(token)[0].normal_form for token in tokens if token not in stop_words and len(token)>=3 ]
stems.extend(digits)
morphs.extend(digits)
return stems
def dot_product2(v1, v2):
return sum(map(operator.mul, v1, v2))
def computeDistance(text1, text2):
words = []
tokenizer = RegexpTokenizer(r'[^\W\d_]+|\d+')
stemmer = SnowballStemmer(language='russian',ignore_stopwords=True)
stop_words = stopwords.words('russian')
tokens = tokenizer.tokenize(text1)
tokens = [i for i in tokens if ( i not in stop_words and len(i)>3 )]
stems1 = [stemmer.stem(word)[:4] for word in tokens]
words.extend(stems1)
tokens = tokenizer.tokenize(text2)
tokens = [i for i in tokens if ( i not in stop_words and len(i)>3 )]
stems2 = [stemmer.stem(word)[:4] for word in tokens]
words.extend(stems2)
words = set(words)
v1 = []
v2 = []
for word in words:
if word in stems1:
v1.append(1)
else:
v1.append(0)
if word in stems2:
v2.append(1)
else:
v2.append(0)
prod = dot_product2(v1, v2)
len1 = math.sqrt(dot_product2(v1, v1))
len2 = math.sqrt(dot_product2(v2, v2))
return prod / (len1 * len2)
def readDuplicates(cursor, limit):
selectQuery = 'select top ' + str(limit) + ' id, description_1, description_2 from Duplicate'
data = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
id = row[0]
desc_1 = row[1]
desc_2 = row[2]
data.append((id,desc_1,desc_2))
row = cursor.fetchone()
return data
def readAttrs(cursor, limit, tableName):
selectQuery = 'select top ' + str(limit) + ' id, attrsJSON_1, attrsJSON_2 from ' + tableName
data = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
id = row[0]
attrs_1 = row[1]
attrs_2 = row[2]
data.append((id,attrs_1,attrs_2))
row = cursor.fetchone()
return data
def readNoDuplicates(cursor, limit):
selectQuery = 'select top ' + str(limit) + ' id, description_1, description_2 from NoDuplicate'
data = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
id = row[0]
desc_1 = row[1]
desc_2 = row[2]
data.append((id,desc_1,desc_2))
row = cursor.fetchone()
return data
def prepareDuplicates(data):
vec=[]
for row in data:
id = row[0]
t1 = row[1]
v1 = textToVec(t1)
t2 = row[2]
v2 = textToVec(t2)
vec.append((id,v1,v2))
return vec
def computeSimilarity(words1,words2):
words=[]
words.extend(words1)
words.extend(words2)
words=set(words)
v1 = []
v2 = []
for word in words:
if word in words1:
v1.append(1)
else:
v1.append(0)
if word in words2:
v2.append(1)
else:
v2.append(0)
prod = dot_product2(v1, v2)
v1_dot_prod = dot_product2(v1, v1)
v2_dot_prod = dot_product2(v2, v2)
if v1_dot_prod == v2_dot_prod==prod:
return 1
else:
len1 = math.sqrt(dot_product2(v1, v1))
len2 = math.sqrt(dot_product2(v2, v2))
if len1==0 or len2==0: return 0
return prod / (len1 * len2)
def computeJakkarSimilarity(words1,words2):
words=[]
words.extend(words1)
words.extend(words2)
words = set(words)
v1 = []
v2 = []
for word in words:
if word in words1:
v1.append(1)
else:
v1.append(0)
if word in words2:
v2.append(1)
else:
v2.append(0)
if(len(words)==0):
return 0
return jaccard_similarity_score(v1,v2)
def computeShinglesJakkarSimilarity(words1, words2, shinglesLen):
text1 = ''
text2 = ''
for shingle in words1:
text1 = text1 + shingle
for shingle in words2:
text2 = text2 + shingle
shingles1 = []
for i in range(0, len(text1) - shinglesLen):
shingles1.append(text1[i:i+shinglesLen])
shingles2 = []
for i in range(0, len(text2) - shinglesLen):
shingles2.append(text2[i:i+shinglesLen])
shingles = []
shingles.extend(shingles1)
shingles.extend(shingles2)
shingles = set(shingles)
v1 = []
v2 = []
for shingle in shingles:
if shingle in shingles1:
v1.append(1)
else:
v1.append(0)
if shingle in shingles2:
v2.append(1)
else:
v2.append(0)
if(len(shingles)==0):
return 0
return jaccard_similarity_score(v1,v2)
def checkDuplicates(vectors):
sim = []
for row in vectors:
id = row[0]
v1 = row[1]
v2 = row[2]
similarity = computeJakkarSimilarity(v1,v2)
sim.append((id,v1, v2, similarity))
return sim
def computePercent(res):
sum = 0
for value in res:
if value[3]>=0.5:
sum+=1
return sum/len(res)
def readData(cursor, limit, generationMethod):
if generationMethod != 0:
selectQuery = 'select top ' + str(limit) + ' itemID_1,itemID_2,isDuplicate from ItemPairs where generationMethod= ' + str(generationMethod)
else:
selectQuery = 'select top ' + str(limit) + ' itemID_1,itemID_2,isDuplicate from ItemPairs'
itemID = []
Y = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
Y.append(row[2])
row = cursor.fetchone()
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
X = []
for pair in itemID:
with cursor.execute(selectQuery,pair):
row1 = cursor.fetchone()
row2 = cursor.fetchone()
X.append((row1,row2))
data = (X,Y)
return data
def writeMixedDataM1_20000(cursor):
duplicates_query = "select * from DuplicateGenM1_10000"
not_duplicates_query = "select * from NoDuplicateGenM1_10000"
mixedData = []
duplicatesData = []
notDuplicatesData = []
with cursor.execute(duplicates_query):
row = cursor.fetchone()
while row:
duplicatesData.append(row[1:])
row = cursor.fetchone()
with cursor.execute(not_duplicates_query):
row = cursor.fetchone()
while row:
notDuplicatesData.append(row[1:])
row = cursor.fetchone()
for i in range(10000):
item = []
item.append(1) # duplicate label
item.extend(duplicatesData[i])
mixedData.append(item)
item = []
item.append(0) # not duplicate label
item.extend(notDuplicatesData[i])
mixedData.append(item)
print("Mixed data shape", numpy.array(mixedData).shape)
dropQuery = 'drop table if exists MixedData'
createTableQuery = 'create table MixedData(' \
'id int PRIMARY KEY identity(1,1),' \
'Y int,' \
'itemID_1 int,' \
'categoryID_1 int,' \
'title_1 nvarchar(1000),' \
'description_1 nvarchar(max),' \
'images_array_1 nvarchar(1000),' \
'attrsJSON_1 nvarchar(max),' \
'price_1 float,' \
'locationID_1 int,' \
'metroID_1 int,' \
'lat_1 decimal(9,6),' \
'lon_1 decimal(9,6),' \
'itemID_2 int,' \
'categoryID_2 int,' \
'title_2 nvarchar(1000),' \
'description_2 nvarchar(max),' \
'images_array_2 nvarchar(1000),' \
'attrsJSON_2 nvarchar(max),' \
'price_2 float,' \
'locationID_2 int,' \
'metroID_2 int,' \
'lat_2 decimal(9,6),' \
'lon_2 decimal(9,6))'
with cursor.execute(dropQuery):
print("Table dropped")
with cursor.execute(createTableQuery):
print("Table created")
insertQuery = 'insert into MixedData' + \
'(' \
'Y, ' \
'itemID_1,' \
'categoryID_1,' \
'title_1,' \
'description_1,' \
'images_array_1,' \
'attrsJSON_1,' \
'price_1,' \
'locationID_1,' \
'metroID_1,' \
'lat_1,' \
'lon_1,' \
'itemID_2,' \
'categoryID_2,' \
'title_2,' \
'description_2,' \
'images_array_2,' \
'attrsJSON_2,' \
'price_2,' \
'locationID_2,' \
'metroID_2,' \
'lat_2,' \
'lon_2)' \
'values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
for i in range(2*10000):
with cursor.execute(insertQuery, mixedData[i]):
print("Data inserted")
def readMixedDataNew(cursor, limit):
selectQuery = "select top " + str(limit) + " * from MixedData"
X = []
Y = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
Y.append(row[1])
x1 = row[2:13]
x2 = row[13:]
X.append((x1,x2))
row = cursor.fetchone()
return X, Y
# read duplicate and not duplicate together
def readMixedData(cursor, limit, generationMethod):
if generationMethod != 0:
selectQuery = 'select top ' + str(int(limit / 2)) + ' itemID_1,itemID_2,isDuplicate from ItemPairs where isDuplicate=1 and generationMethod= ' + str(generationMethod) + \
'union select top ' + str(int(limit / 2)) + ' itemID_1,itemID_2,isDuplicate from ItemPairs where isDuplicate=0 and generationMethod= ' + str(generationMethod)
else:
selectQuery = 'select top ' + str(limit) + ' itemID_1,itemID_2,isDuplicate from ItemPairs'
itemID = []
Y = []
with cursor.execute(selectQuery):
row = cursor.fetchone()
while row:
itemID.append((row[0],row[1]))
Y.append(row[2])
row = cursor.fetchone()
selectQuery = 'select * from ItemInfo where itemID in (?,?)'
X = []
for pair in itemID:
with cursor.execute(selectQuery, pair):
row1 = cursor.fetchone()
row2 = cursor.fetchone()
X.append((row1,row2))
data = (X,Y)
return data
def compareNumbers(ad1, ad2):
numbers1 = [i for i in ad1 if (i.isdigit())]
numbers2 = [i for i in ad2 if (i.isdigit())]
return computeJakkarSimilarity(numbers1,numbers2)
def readFeatures(cursor, data_size):
select_query = "select top " + str(data_size) + " * from Features"
X = []
Y = []
with cursor.execute(select_query):
data = cursor.fetchall()
for row in data:
Y.append(row[1])
X.append(list(row[4:]))
result = (X,Y)
return result
def readNewFeatures(cursor, data_size):
select_query = "select top " + str(data_size) + " * from FeaturesNew"
X = []
Y = []
with cursor.execute(select_query):
data = cursor.fetchall()
for row in data:
Y.append(row[1])
X.append(row[4:])
X = preprocessing.normalize(X, norm='max', axis=0)
result = (X,Y)
return result
def readTextFeatures(cursor, data_size):
select_query = "select top " + str(data_size) + " * from FeaturesNew"
X = []
Y = []
with cursor.execute(select_query):
data = cursor.fetchall()
for row in data:
Y.append(row[1])
tmp = list(row[4:20])
tmp.extend(row[24:])
X.append(tmp)
X = preprocessing.normalize(X, norm='max', axis=0)
result = (X,Y)
return result
def writeFeaturesNew(cursor, data, hash=0, shinglesLen=0):
tableName = "FeaturesNew"
dropQuery = 'drop table if exists ' + tableName
createTableQuery = 'create table ' + tableName + '(' \
'id int identity(1,1),' \
'Y int,' \
'id1 int,' \
'id2 int,' \
'constraint PK_FEATURES_NEW PRIMARY KEY (id1, id2),' \
'cat int,' \
'title float,' \
'titNumbLen int,' \
'titNumbSim int,' \
'titNumbMed int,' \
'descr float,' \
'descNumbLen int,' \
'descNumbSim int,' \
'descNumbMed int,' \
'title1desc2 float,' \
'title2desc1 float,' \
'titleDesc float,' \
'titDescNumbLen int,' \
'titDescNumbSim int,' \
'titDescNumbMed int,' \
'imgNumb int,' \
'ahash int,' \
'phash int,' \
'dhash int, ' \
'hist int,' \
'attrs float,' \
'price int,' \
'priceDif float,' \
'loc int,' \
'metro int,' \
'lat int,' \
'lon int,' \
'latDif float,' \
'lonDif float)'
with cursor.execute(dropQuery):
print("Table have been dropped")
with cursor.execute(createTableQuery):
print("Table have been created")
insertQuery = 'insert into ' + tableName +'(Y, id1, id2, cat, title, titNumbLen, titNumbSim, titNumbMed,' \
'descr, descNumbLen, descNumbSim, descNumbMed,' \
' title1desc2, title2desc1, titleDesc, titDescNumbLen,' \
'titDescNumbSim, titDescNumbMed, imgNumb, ahash, phash, dhash,' \
'hist, attrs, price, priceDif, loc, metro, lat, lon, latDif, lonDif)' \
' values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
pairs = data[0]
Y = data[1]
insert_values = []
for i in range(len(Y)):
y = Y[i]
first = pairs[i][0]
second = pairs[i][1]
item = []
item.append(y)
item.append(first[0])
print("itemID_1 = ", first[0])
item.append(second[0])
print("itemID_2 = ", second[0])
cat1 = first[1]
cat2 = second[1]
if cat1==cat2:
item.append(1)
else:
item.append(0)
if hash == 1:
title1 = wordsToNumbers(textToVec(first[2]))
title2 = wordsToNumbers(textToVec(second[2]))
else:
title1 = textToVec(first[2])
title2 = textToVec(second[2])
if shinglesLen == 0:
titleSimilarity = computeJakkarSimilarity(title1,title2)
else:
titleSimilarity = computeShinglesJakkarSimilarity(title1,title2,shinglesLen)
item.append(titleSimilarity)
# Does the number of numbers in the titles match?
numbers1 = [float(i) for i in title1 if (i.isdigit())]
numbers2 = [float(i) for i in title2 if (i.isdigit())]
if len(numbers1) == 0 and len(numbers2) == 0:
item.append(1) # lengths equals
item.append(1) # sim=1
item.append(1) # median = 1
elif len(numbers1) == 0 or len(numbers2) == 0:
item.append(0)
item.append(0)
item.append(0)
else:
item.append(int(len(numbers1) == len(numbers2)))
# the percentage of matching numbers
title_numbers_similarity = compareNumbers(title1, title2)
item.append(title_numbers_similarity)
# median
item.append(int(numpy.median(numbers1) == numpy.median(numbers2)))
if hash == 1:
description1 = wordsToNumbers(textToVec(first[3]))
description2 = wordsToNumbers(textToVec(second[3]))
else:
description1 = textToVec(first[3])
description2 = textToVec(second[3])
if shinglesLen == 0:
descriptionSimilarity = computeJakkarSimilarity(description1,description2)
else:
descriptionSimilarity = computeShinglesJakkarSimilarity(description1,description2,shinglesLen)
item.append(descriptionSimilarity)
# Does the number of numbers in the descriptions match?
numbers1 = [float(i) for i in description1 if (i.isdigit())]
numbers2 = [float(i) for i in description2 if (i.isdigit())]
if len(numbers1) == 0 and len(numbers2) == 0:
item.append(1) # lengths equals
item.append(1) # sim=1
item.append(1) # median = 1
elif len(numbers1) == 0 or len(numbers2) == 0:
item.append(0)
item.append(0)
item.append(0)
else:
item.append(int(len(numbers1) == len(numbers2)))
# the percentage of matching numbers
title_numbers_similarity = compareNumbers(title1, title2)
item.append(title_numbers_similarity)
# median
item.append(int(numpy.median(numbers1) == numpy.median(numbers2)))
# compare title vs description and so on
if shinglesLen == 0:
title1Desc2 = computeJakkarSimilarity(title1,description2)
title2Desc1 = computeJakkarSimilarity(title2, description1)
item.append(title1Desc2)
item.append(title2Desc1)
else:
title1Desc2 = computeShinglesJakkarSimilarity(title1, description2,shinglesLen)
title2Desc1 = computeShinglesJakkarSimilarity(title2, description1,shinglesLen)
item.append(title1Desc2)
item.append(title2Desc1)
title1.extend(description1)
title2.extend(description2)
if shinglesLen == 0:
titleDescSim = computeJakkarSimilarity(title1,title2)
else:
titleDescSim = computeShinglesJakkarSimilarity(title1,title2,shinglesLen)
item.append(titleDescSim)
# Does the number of numbers in the title + description match?
numbers1 = [float(i) for i in title1 if (i.isdigit())]
numbers2 = [float(i) for i in title2 if (i.isdigit())]
if len(numbers1) == 0 and len(numbers2) == 0:
item.append(1) # lengths equals
item.append(1) # sim=1
item.append(1) # median = 1
elif len(numbers1) == 0 or len(numbers2) == 0:
item.append(0)
item.append(0)
item.append(0)
else:
item.append(int(len(numbers1) == len(numbers2)))
# the percentage of matching numbers
title_numbers_similarity = compareNumbers(title1, title2)
item.append(title_numbers_similarity)
# median
item.append(int(numpy.median(numbers1) == numpy.median(numbers2)))
images_str1 = first[4]
images_str2 = second[4]
if images_str1 != '' and images_str2 != '':
img_nums1 = images_str1.split(', ')
img_nums2 = images_str2.split(', ')