-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclassifier.py
1059 lines (884 loc) · 37.9 KB
/
classifier.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
# Copyright (C) 2016,2017 Marcus Soll
# Copyright (C) 2016,2017 Malte Vosgerau
#
# This file is part of ClassifyHub.
#
# ClassifyHub is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ClassifyHub is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ClassifyHub. If not, see <http://www.gnu.org/licenses/>.
import modelstore
import utility
import github
import logging
import pickle
import base64
import sklearn.tree
import sklearn.neighbors
##
# \brief Returns all implemented classifiers.
#
# \return List of classifiers.
def get_all_classifiers():
return [FileClassifier(),
ReadmeClassifier(),
MetadataClassifier(),
LanguageClassifier(),
LanguageDetailsClassifier(),
NameClassifier(),
CommitMessageClassifier(),
RepositoryStructureClassifier(),
]
##
# \brief Base class for all classifier.
#
# The classifier class is the base class for all weak classifier.
# A weak classifier is an algorithm which solves the 'GitHub Classification Problem' better than random guessing.
#
# All weak classifier have to implement all methods of Classifier to be considered as a valid classifier.
class Classifier:
##
# \brief Constructor.
def __init__(self):
pass
##
# \brief Returns the name of the classifier.
#
# The name should be unique as it may be used to identify the classifier.
#
# \return Name of the classifier as string.
def name(self):
raise NotImplementedError('The method "name" of Classifier is not implemented')
##
# \brief Classifies the given repository.
#
# It is necessary to first train the classifier using the Classifier.learn method, otherwise this method might
# not work.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
# Data: Single github class
raise NotImplementedError('The method "classify" of Classifier is not implemented')
##
# \brief Trains the classifier on the given data set.
#
# After training the resulting model is saved to permanent memory and the Classifier.classify method might be
# invoked.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
# learn, test: Array of github classes
raise NotImplementedError('The method "learn" of Classifier is not implemented')
##
# \brief The FileClassifier rates the repositories based on the file type.
#
# The file type is determined from the file extension.
class FileClassifier(Classifier):
##
# \brief Constructor.
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('FileClassifier')
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'FileClassifier'
##
# \brief Classifies the repo based on the type of the files contained in the repository.
#
# The probability for each class given a file type is determined at the learning.
# The classifier averages the probability over all files it found in the repository.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
result = utility.get_zero_class_dict()
try:
all_files = data.get_all_files()
except github.GithubError:
return result
if len(all_files) == 0:
return result
for file in all_files:
file = file.split('/')[-1]
file = file.split('.')[-1]
file = file.lower()
if file in self._model.config:
for c in self._model.config[file]:
result[c] += self._model.config[file][c]
for key in result.keys():
result[key] /= len(all_files)
return result
##
# \brief Learns the probability of a class given the file type.
#
# This is achieved by looking through all provided learning repositories and calculating the probability as
# \f$P(Class | File) = \frac{N_{Files\ from\ class}}{N_{Files\ from\ all\ classes}}\f$.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
for data in learn:
try:
file_list = data[0].get_all_files()
except github.GithubError:
continue
for file in file_list:
file = file.split('/')[-1]
file = file.split('.')[-1]
file = file.lower()
if file not in self._model.config:
self._model.config[file] = utility.get_zero_class_dict()
self._model.config[file][data[1]] += 1
for file in self._model.config:
count = 0
for c in self._model.config[file]:
count += self._model.config[file][c]
if count <= 1:
continue
for c in self._model.config[file]:
self._model.config[file][c] /= count
self._model.save()
##
# \brief The ReadmeClassifier calculates the probability of classes from the content of README files.
#
# For this the classifier puts the readme into a <em>Bag-of-words</em> and comparing that to all READMEs encountered
# at learning time using <em>k-Nearest Neighbors</em>.
class ReadmeClassifier(Classifier):
##
# \brief Constructor.
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('ReadmeClassifier')
self._knn = None
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'ReadmeClassifier'
##
# \brief Classifies the repositories based on the README.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if 'version' not in self._model.config:
logging.error('Trying to use ReadmeClassifier without learning first')
return utility.get_zero_class_dict()
if self._model.config['version'] != sklearn.__version__:
logging.error('Using ReadmeClassifier with different scikit learn version (trained on: {}, used: {}) - relearn classifier first'.format(self._model.config['version'], sklearn.__version__))
return utility.get_zero_class_dict()
try:
readme = data.get_readme()
except github.GithubError:
return utility.get_zero_class_dict()
if self._knn is None:
self._knn = pickle.loads(base64.b64decode(self._model.config['knn']))
bow = [False for _ in self._model.config['bow']]
for word in readme.split():
i = self._find_position(word.decode('utf-8').lower())
if i != -1:
bow[i] = True
probability = self._knn.predict_proba([bow])
result = utility.get_zero_class_dict()
for i in range(len(self._knn.classes_)):
result[self._knn.classes_[i]] = probability[0][i]
return result
##
# \brief Finds the position of word in the <em>Bag-of-words</em>.
#
# This needs the 'lookup' attribute in the model which is created at learning.
#
# \param word Word for which the position should be found.
# \return Position or -1 if not in <em>Bag-of-words</em>.
def _find_position(self, word):
if word not in self._model.config['lookup']:
return -1
return self._model.config['lookup'][word]
##
# \brief Learns the <em>Bag-of-words</em> and the model from all provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
self._model.config['version'] = sklearn.__version__
self._knn = None
word_dict = dict()
# Find common words
for data in learn:
try:
readme = data[0].get_readme()
except github.GithubError:
continue
word_set = set(readme.decode('utf-8').lower().split())
for word in word_set:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
bow = []
for word in word_dict:
if word_dict[word] >= 2:
bow += [word]
# Save guard
if len(bow) == 0:
bow = list(word_dict)
self._model.config['bow'] = bow
# Create lookup
lookup = dict()
for i in range(len(bow)):
lookup[bow[i]] = i
self._model.config['lookup'] = lookup
# Build KNN
dataset = []
labels = []
for data in learn:
try:
readme = data[0].get_readme()
except github.GithubError:
continue
bow_data = [False for _ in bow]
for word in readme.split():
i = self._find_position(word.decode('utf-8'))
if i != -1:
bow_data[i] = True
dataset += [bow_data]
labels += [data[1]]
# Check for empty data set
if len(dataset) == 0 or len(labels) == 0:
logging.error('Trying to learn ReadmeClassifier with an empty data set. This is not possible.\n'
'Possible errors:\n'
' * Your learning folder is not set up correctly\n'
' * Your rate limit is exhausted\n'
' * There is an error with your internet connection\n'
' * There is an error while connecting to GitHub\n')
self._model.clear()
self._model.save()
return
knn = sklearn.neighbors.KNeighborsClassifier(n_neighbors=10, metric='jaccard')
knn.fit(dataset, labels)
# Save results
self._knn = knn
self._model.config['knn'] = base64.b64encode(pickle.dumps(knn)).decode()
self._model.save()
##
# \brief The MetadataClassifier ates the repositories based on the metadata.
#
# A <em>Decision Tree</em> is used for the classification. The following metadata is used;
# - Is the repository a fork?
# - Has the repository a website?
# - Size of repository
# - Number of stargazers
# - Number of watchers
# - Has the project a wiki?
# - Has the project 'Pages'?
# - Number of forks
# - Number of issues
# - Number of subscribers
class MetadataClassifier(Classifier):
##
# \brief Constructor.
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('MetadataClassifier')
self._tree = None
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'MetadataClassifier'
##
# \brief Creates the input array out of the repository.
#
# \param github_object github.Github object representing the repository.
# \return Array of metadata.
def _get_input(self, github_object):
try:
metadata = github_object.get_repository_data()
input = [
metadata['fork'],
True if metadata['homepage'] is not None else False,
metadata['size'],
metadata['stargazers_count'],
metadata['watchers_count'],
metadata['has_wiki'],
metadata['has_pages'],
metadata['forks_count'],
metadata['open_issues_count'],
metadata['subscribers_count']
]
return input
except github.GithubError:
return [0.0 for _ in range(10)]
##
# \brief Classifies the repository based on the learned <em>Decision Tree</em>.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if 'version' not in self._model.config:
logging.error('Trying to use MetadataClassifier without learning first')
return utility.get_zero_class_dict()
if self._model.config['version'] != sklearn.__version__:
logging.error('Using MetadataClassifier with different scikit learn version (trained on: {}, used: {}) - relearn classifier first'.format(self._model.config['version'], sklearn.__version__))
return utility.get_zero_class_dict()
if self._tree is None:
self._tree = pickle.loads(base64.b64decode(self._model.config['tree']))
probability = self._tree.predict_proba([self._get_input(data)])
result = utility.get_zero_class_dict()
for i in range(len(self._tree.classes_)):
result[self._tree.classes_[i]] = probability[0][i]
return result
##
# \brief Trains a <em>Decision Tree</em> based on the provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
self._model.config['version'] = sklearn.__version__
self._tree = None
input = []
classes = []
for data in learn:
try:
input += [self._get_input(data[0])]
classes += [data[1]]
except github.GithubError:
continue
# Check for empty data set
if len(input) == 0 or len(classes) == 0:
logging.error('Trying to learn MetadataClassifier with an empty data set. This is not possible.\n'
'Possible errors:\n'
' * Your learning folder is not set up correctly\n'
' * Your rate limit is exhausted\n'
' * There is an error with your internet connection\n'
' * There is an error while connecting to GitHub\n')
self._model.clear()
self._model.save()
return
tree = sklearn.tree.DecisionTreeClassifier(min_samples_leaf=3)
tree.fit(input, classes)
self._tree = tree
self._model.config['tree'] = base64.b64encode(pickle.dumps(tree)).decode()
self._model.save()
##
# \brief The LanguageClassifier classifies the repositories based on the main language (as reported by GitHub).
#
# The probability of a class given the language is calculated from the learning data as following:
# \f$P(Class | Language) = \frac{N_{Repositories\ from\ class\ with\ language}}{N_{Repositories\ with\ language}}\f$.
class LanguageClassifier(Classifier):
##
# \brief Constructor
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('LanguageClassifier')
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'LanguageClassifier'
##
# \brief Classifies the repositories based on the main language.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
try:
language = data.get_repository_data()['language']
except github.GithubError:
return utility.get_zero_class_dict()
if language is None:
language = '_None_'
if language in self._model.config:
return self._model.config[language].copy()
else:
return utility.get_zero_class_dict()
##
# \brief Learns the distribution of the languages based on the provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
for data in learn:
try:
language = data[0].get_repository_data()['language']
except github.GithubError:
continue
if language is None:
language = '_None_'
if language not in self._model.config:
self._model.config[language] = utility.get_zero_class_dict()
self._model.config[language][data[1]] += 1
for language in self._model.config:
count = 0
for c in self._model.config[language]:
count += self._model.config[language][c]
# Saveguard - should never be true
if count == 0:
logging.error('LanguageClassifier has zero count for {}'.format(language))
continue
for c in self._model.config[language]:
self._model.config[language][c] /= count
self._model.save()
##
# \brief The LanguageDetailsClassifier classifies the repositories based on the language distribution.
#
# The language distribution of a repository is measured in the combined size of the files containing the language, as
# reported by GitHub. The classification is done based on a <em>Decision Tree</em> trained on the language distribution.
class LanguageDetailsClassifier(Classifier):
##
# \brief Constructor
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('LanguageDetailsClassifier')
self._tree = None
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'LanguageDetailsClassifier'
##
# \brief Returns the distribution of languages based on known languages.
#
# \param languages Set {LANGUAGE: SIZE} containing the size of files with a given language.
# \param known_languages List of known languages.
# \return List containing the distribution of languages.
def _get_entry(self, languages, known_languages):
entry = []
for language in known_languages:
if language in languages:
entry += [languages[language]]
else:
entry += [0]
sum_entry = sum(entry)
if sum_entry != 0:
entry = [x / sum_entry for x in entry]
return entry
##
# \brief Classifies the reoisitory based on the learned <em>Decision Tree</em>.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if 'version' not in self._model.config:
logging.error('Trying to use LanguageDetailsClassifier without learning first')
return utility.get_zero_class_dict()
if self._model.config['version'] != sklearn.__version__:
logging.error('Using LanguageDetailsClassifier with different scikit learn version (trained on: {}, used: {}) - relearn classifier first'.format(self._model.config['version'], sklearn.__version__))
return utility.get_zero_class_dict()
if self._tree is None:
self._tree = pickle.loads(base64.b64decode(self._model.config['tree']))
try:
languages = data.get_languages()
except github.GithubError:
return utility.get_zero_class_dict()
probability = self._tree.predict_proba([self._get_entry(languages, self._model.config['known_languages'])])
result = utility.get_zero_class_dict()
for i in range(len(self._tree.classes_)):
result[self._tree.classes_[i]] = probability[0][i]
return result
##
# \brief Learns the <em>Decision Tree</em> based on the language distribution.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
self._model.config['version'] = sklearn.__version__
self._tree = None
known_languages = set()
for data in learn:
try:
languages = data[0].get_languages()
except github.GithubError:
continue
for language in languages:
known_languages.add(language)
known_languages = list(known_languages)
dataset = []
labels = []
for data in learn:
try:
languages = data[0].get_languages()
except github.GithubError:
continue
entry = self._get_entry(languages, known_languages)
dataset += [entry]
labels += [data[1]]
# Check for empty data set
if len(dataset) == 0 or len(labels) == 0:
logging.error('Trying to learn LanguageDetailsClassifier with an empty data set. This is not possible.\n'
'Possible errors:\n'
' * Your learning folder is not set up correctly\n'
' * Your rate limit is exhausted\n'
' * There is an error with your internet connection\n'
' * There is an error while connecting to GitHub\n')
self._model.clear()
self._model.save()
return
tree = sklearn.tree.DecisionTreeClassifier(min_samples_leaf=3)
tree.fit(dataset, labels)
self._tree = tree
self._model.config['tree'] = base64.b64encode(pickle.dumps(tree)).decode()
self._model.config['known_languages'] = known_languages
self._model.save()
##
# \brief The NameClassifier classifies the repositories based on the name similarity.
#
# The similarity is determined by using the Levenshtein distance. The classification is done using the
# <em>k-Nearest Neighbors</em> algorithm.
class NameClassifier(Classifier):
##
# \brief Constructor
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('NameClassifier')
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'NameClassifier'
##
# \brief Classifies a repository based on its name.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if len(self._model.config) is 0:
logging.error('Trying to use NameClassifier without learning first')
return utility.get_zero_class_dict()
try:
repo_name = data.get_repository_data()['name']
except github.GithubError:
return utility.get_zero_class_dict()
distances = []
for target in self._model.config:
distances += [(target, utility.edit_distance(repo_name, target))]
distances.sort(key=lambda x: x[1])
result = utility.get_zero_class_dict()
nn = 1
for c in utility.get_classes():
result[c] += self._model.config[distances[0][0]][c]
while nn < len(distances) and distances[nn - 1][1] == distances[nn][1]:
for c in utility.get_classes():
result[c] += self._model.config[distances[nn][0]][c]
nn += 1
for c in utility.get_classes():
result[c] /= nn
return result
##
# \brief Builds the <em>k-Nearest Neighbors</em> classifier based on the provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
for data in learn:
try:
repo_name = data[0].get_repository_data()['name']
except github.GithubError:
continue
if repo_name not in self._model.config:
self._model.config[repo_name] = utility.get_zero_class_dict()
self._model.config[repo_name][data[1]] += 1
for repo_name in self._model.config:
count = 0
for c in self._model.config[repo_name]:
count += self._model.config[repo_name][c]
# Saveguard - should never be true
if count == 0:
logging.error('NameClassifier has zero count for {}'.format(repo_name))
continue
for c in self._model.config[repo_name]:
self._model.config[repo_name][c] /= count
self._model.save()
##
# \brief The CommitMessageClassifier calculates the probability of classes from the content of the commits.
#
# For this the classifier puts the commit messages into a <em>Bag-of-words</em> and comparing that to all
# commit messages of projects encountered at learning time using <em>k-Nearest Neighbors</em>.
class CommitMessageClassifier(Classifier):
##
# \brief Constructor
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('CommitMessageClassifier')
self._knn = None
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'CommitMessageClassifier'
##
# \brief Classifies the repositories based on the commit messages.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if 'version' not in self._model.config:
logging.error('Trying to use CommitMessageClassifier without learning first')
return utility.get_zero_class_dict()
if self._model.config['version'] != sklearn.__version__:
logging.error('Using CommitMessageClassifier with different scikit learn version (trained on: {}, used: {}) - relearn classifier first'.format(self._model.config['version'], sklearn.__version__))
return utility.get_zero_class_dict()
try:
commits = data.get_commits()
except github.GithubError:
return utility.get_zero_class_dict()
if self._knn is None:
self._knn = pickle.loads(base64.b64decode(self._model.config['knn']))
bow = [False for _ in self._model.config['bow']]
for commit in commits:
for word in commit['commit']['message'].split():
i = self._find_position(word.lower())
if i != -1:
bow[i] = True
probability = self._knn.predict_proba([bow])
result = utility.get_zero_class_dict()
for i in range(len(self._knn.classes_)):
result[self._knn.classes_[i]] = probability[0][i]
return result
##
# \brief Finds the position of word in the <em>Bag-of-words</em>.
#
# This needs the 'lookup' attribute in the model which is created at learning.
#
# \param word Word for which the position should be found.
# \return Position or -1 if not in <em>Bag-of-words</em>.
def _find_position(self, word):
if word not in self._model.config['lookup']:
return -1
return self._model.config['lookup'][word]
##
# \brief Learns the <em>Bag-of-words</em> and the model from all provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
self._model.config['version'] = sklearn.__version__
self._knn = None
word_dict = dict()
# Find common words
for data in learn:
try:
commits = data[0].get_commits()
except github.GithubError:
continue
word_set = set()
for commit in commits:
word_set.update(set(commit['commit']['message'].lower().split()))
for word in word_set:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
bow = []
for word in word_dict:
if word_dict[word] >= 2:
bow += [word]
# Save guard
if len(bow) == 0:
bow = list(word_dict)
self._model.config['bow'] = bow
# Create lookup
lookup = dict()
for i in range(len(bow)):
lookup[bow[i]] = i
self._model.config['lookup'] = lookup
# Build KNN
dataset = []
labels = []
for data in learn:
try:
commits = data[0].get_commits()
except github.GithubError:
continue
bow_data = [False for _ in bow]
for commit in commits:
for word in commit['commit']['message'].split():
i = self._find_position(word)
if i != -1:
bow_data[i] = True
dataset += [bow_data]
labels += [data[1]]
# Check for empty data set
if len(dataset) == 0 or len(labels) == 0:
logging.error('Trying to learn CommitMessageClassifier with an empty data set. This is not possible.\n'
'Possible errors:\n'
' * Your learning folder is not set up correctly\n'
' * Your rate limit is exhausted\n'
' * There is an error with your internet connection\n'
' * There is an error while connecting to GitHub\n')
self._model.clear()
self._model.save()
return
knn = sklearn.neighbors.KNeighborsClassifier(n_neighbors=10, metric='jaccard')
knn.fit(dataset, labels)
# Save results
self._knn = knn
self._model.config['knn'] = base64.b64encode(pickle.dumps(knn)).decode()
self._model.save()
##
# \brief The RepositoryStructureClassifier calculates the probability of the classes by comparing the structure of a repository.
#
# For this the classifier puts the objects in the git tree into a <em>Bag-of-words</em> and compares that to all
# git trees of projects encountered at learning time using <em>k-Nearest Neighbors</em>.
#
# For improved results all appearence of the repo name are replaced by a placeholder. This should generalize more e.g. if the
# repository name is used as a folder name.
class RepositoryStructureClassifier(Classifier):
##
# \brief Constructor.
def __init__(self):
super().__init__()
self._model = modelstore.ModelStore('RepositoryStructureClassifier')
self._knn = None
##
# \brief Returns the name of the classifier.
#
# \return Name of the classifier as string.
def name(self):
return 'RepositoryStructureClassifier'
##
# \brief Classifies the repositories based on the commit messages.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
def classify(self, data):
if 'version' not in self._model.config:
logging.error('Trying to use RepositoryStructureClassifier without learning first')
return utility.get_zero_class_dict()
if self._model.config['version'] != sklearn.__version__:
logging.error('Using RepositoryStructureClassifier with different scikit learn version (trained on: {}, used: {}) - relearn classifier first'.format(self._model.config['version'], sklearn.__version__))
return utility.get_zero_class_dict()
try:
tree = data.get_tree()
except github.GithubError:
return utility.get_zero_class_dict()
name = data.get_dev_repo()[1].lower()
if self._knn is None:
self._knn = pickle.loads(base64.b64decode(self._model.config['knn']))
bow = [False for _ in self._model.config['bow']]
for object in tree['tree']:
i = self._find_position(object['path'].lower().replace(name, '$REPO'))
if i != -1:
bow[i] = True
probability = self._knn.predict_proba([bow])
result = utility.get_zero_class_dict()
for i in range(len(self._knn.classes_)):
result[self._knn.classes_[i]] = probability[0][i]
return result
##
# \brief Finds the position of word in the <em>Bag-of-words</em>.
#
# This needs the 'lookup' attribute in the model which is created at learning.
#
# \param word Word for which the position should be found.
# \return Position or -1 if not in <em>Bag-of-words</em>.
def _find_position(self, word):
if word not in self._model.config['lookup']:
return -1
return self._model.config['lookup'][word]
##
# \brief Learns the <em>Bag-of-words</em> and the model from all provided repositories.
#
# \param learn List containing Tupel (GITHUB, CLASS), where GITHUB is the repository as a github.Github class and
# CLASS is the class label of the repository as a string.
def learn(self, learn):
self._model.clear()
self._model.config['version'] = sklearn.__version__
self._knn = None
object_dict = dict()
# Find common structure
for data in learn:
try:
tree = data[0].get_tree()
except github.GithubError:
continue
name = data[0].get_dev_repo()[1].lower()
object_set = set()
for object in tree['tree']:
object_set.update({object['path'].lower().replace(name, '$REPO')})
for word in object_set:
if word in object_dict:
object_dict[word] += 1
else: