-
Notifications
You must be signed in to change notification settings - Fork 30
/
classifiers.py
2708 lines (2330 loc) · 76.2 KB
/
classifiers.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
"""
A module of classification schemes for choropleth mapping.
"""
import numpy as np
import scipy.stats as stats
import scipy as sp
import copy
from sklearn.cluster import KMeans as KMEANS
from warnings import warn as Warn
__author__ = "Sergio J. Rey"
__all__ = [
"MapClassifier",
"quantile",
"BoxPlot",
"EqualInterval",
"FisherJenks",
"FisherJenksSampled",
"JenksCaspall",
"JenksCaspallForced",
"JenksCaspallSampled",
"HeadTailBreaks",
"MaxP",
"MaximumBreaks",
"NaturalBreaks",
"Quantiles",
"Percentiles",
"StdMean",
"UserDefined",
"gadf",
"KClassifiers",
"CLASSIFIERS",
]
CLASSIFIERS = (
"BoxPlot",
"EqualInterval",
"FisherJenks",
"FisherJenksSampled",
"HeadTailBreaks",
"JenksCaspall",
"JenksCaspallForced",
"JenksCaspallSampled",
"MaxP",
"MaximumBreaks",
"NaturalBreaks",
"Quantiles",
"Percentiles",
"StdMean",
"UserDefined",
)
K = 5 # default number of classes in any map scheme with this as an argument
SEEDRANGE = 1000000 # range for drawing random integers from for Natural Breaks
FMT = "{:.2f}"
try:
from numba import jit
except ImportError:
def jit(func):
return func
def _format_intervals(mc, fmt="{:.0f}"):
"""
Helper methods to format legend intervals
Parameters
----------
mc: MapClassifier
fmt: str
specification of formatting for legend
Returns
-------
tuple:
edges: list
k strings for class intervals
max_width: int
length of largest interval string
lower_open: boolean
True: lower bound of first interval is open
False: lower bound of first interval is closed
Notes
-----
For some classifiers, it is possible that the upper bound of the first interval is less than the minimum value of the attribute that is being classified. In these cases `lower_open=True` and the lower bound of the interval is set to `np.NINF`.
"""
lowest = mc.y.min()
lower_open = False
if lowest > mc.bins[0]:
lowest = np.NINF
lower_open = True
edges = [lowest]
edges.extend(mc.bins)
edges = [fmt.format(edge) for edge in edges]
max_width = max([len(edge) for edge in edges])
return edges, max_width, lower_open
def _get_mpl_labels(mc, fmt="{:.1f}"):
"""
Helper method to format legend intervals for matplotlib (and geopandas)
Parameters
----------
mc: MapClassifier
fmt: str
specification of formatting for legend
Returns
-------
intervals: list
k strings for class intervals
"""
edges, max_width, lower_open = _format_intervals(mc, fmt)
k = len(edges) - 1
left = ["["]
if lower_open:
left = ["("]
left.extend("(" * k)
right = "]" * (k + 1)
lower = ["{:>{width}}".format(edges[i], width=max_width) for i in range(k)]
upper = ["{:>{width}}".format(edges[i], width=max_width) for i in range(1, k + 1)]
lower = [l + r for l, r in zip(left, lower)]
upper = [l + r for l, r in zip(upper, right)]
intervals = [l + ", " + r for l, r in zip(lower, upper)]
return intervals
def _get_table(mc, fmt="{:.2f}"):
"""
Helper function to generate tabular classification report
Parameters
----------
mc: MapClassifier
fmt: str
specification of formatting for legend
Returns
-------
table: string
formatted table of classification results
"""
intervals = _get_mpl_labels(mc, fmt)
interval_width = len(intervals[0])
counts = list(map(str, mc.counts))
count_width = max([len(count) for count in counts])
count_width = max(count_width, len("count"))
interval_width = max(interval_width, len("interval"))
header = "{:^{width}}".format("Interval", width=interval_width)
header += " " + "{:>{width}}".format("Count", width=count_width)
title = "{:<{width}}".format(mc.name, width=len(header))
header += "\n" + "-" * len(header)
table = [title, "", header]
for i, interval in enumerate(intervals):
row = interval + " | " + "{:>{width}}".format(counts[i], width=count_width)
table.append(row)
return "\n".join(table)
def head_tail_breaks(values, cuts):
"""
head tail breaks helper function
"""
values = np.array(values)
mean = np.mean(values)
cuts.append(mean)
if len(set(values)) > 1:
return head_tail_breaks(values[values >= mean], cuts)
return cuts
def quantile(y, k=4):
"""
Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import numpy as np
>>> import mapclassify as mc
>>> x = np.arange(1000)
>>> mc.classifiers.quantile(x)
array([249.75, 499.5 , 749.25, 999. ])
>>> mc.classifiers.quantile(x, k = 3)
array([333., 666., 999.])
Note that if there are enough ties that the quantile values repeat, we
collapse to pseudo quantiles in which case the number of classes will be
less than k
>>> x = [1.0] * 100
>>> x.extend([3.0] * 40)
>>> len(x)
140
>>> y = np.array(x)
>>> mc.classifiers.quantile(y)
array([1., 3.])
"""
w = 100.0 / k
p = np.arange(w, 100 + w, w)
if p[-1] > 100.0:
p[-1] = 100.0
q = np.array([stats.scoreatpercentile(y, pct) for pct in p])
q = np.unique(q)
k_q = len(q)
if k_q < k:
Warn(
"Warning: Not enough unique values in array to form k classes", UserWarning
)
Warn("Warning: setting k to %d" % k_q, UserWarning)
return q
def binC(y, bins):
"""
Bin categorical/qualitative data
Parameters
----------
y : array
(n,q), categorical values
bins : array
(k,1), unique values associated with each bin
Return
------
b : array
(n,q), bin membership, values between 0 and k-1
Examples
--------
>>> import numpy as np
>>> import mapclassify as mc
>>> np.random.seed(1)
>>> x = np.random.randint(2, 8, (10, 3))
>>> bins = list(range(2, 8))
>>> x
array([[7, 5, 6],
[2, 3, 5],
[7, 2, 2],
[3, 6, 7],
[6, 3, 4],
[6, 7, 4],
[6, 5, 6],
[4, 6, 7],
[4, 6, 3],
[3, 2, 7]])
>>> y = mc.classifiers.binC(x, bins)
>>> y
array([[5, 3, 4],
[0, 1, 3],
[5, 0, 0],
[1, 4, 5],
[4, 1, 2],
[4, 5, 2],
[4, 3, 4],
[2, 4, 5],
[2, 4, 1],
[1, 0, 5]])
"""
if np.ndim(y) == 1:
k = 1
n = np.shape(y)[0]
else:
n, k = np.shape(y)
b = np.zeros((n, k), dtype="int")
for i, bin in enumerate(bins):
b[np.nonzero(y == bin)] = i
# check for non-binned items and warn if needed
vals = set(y.flatten())
for val in vals:
if val not in bins:
Warn("value not in bin: {}".format(val), UserWarning)
Warn("bins: {}".format(bins), UserWarning)
return b
def bin(y, bins):
"""
bin interval/ratio data
Parameters
----------
y : array
(n,q), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
b : array
(n,q), values of values between 0 and k-1
Examples
--------
>>> import numpy as np
>>> import mapclassify as mc
>>> np.random.seed(1)
>>> x = np.random.randint(2, 20, (10, 3))
>>> bins = [10, 15, 20]
>>> b = mc.classifiers.bin(x, bins)
>>> x
array([[ 7, 13, 14],
[10, 11, 13],
[ 7, 17, 2],
[18, 3, 14],
[ 9, 15, 8],
[ 7, 13, 12],
[16, 6, 11],
[19, 2, 15],
[11, 11, 9],
[ 3, 2, 19]])
>>> b
array([[0, 1, 1],
[0, 1, 1],
[0, 2, 0],
[2, 0, 1],
[0, 1, 0],
[0, 1, 1],
[2, 0, 1],
[2, 0, 1],
[1, 1, 0],
[0, 0, 2]])
"""
if np.ndim(y) == 1:
k = 1
n = np.shape(y)[0]
else:
n, k = np.shape(y)
b = np.zeros((n, k), dtype="int")
i = len(bins)
if type(bins) != list:
bins = bins.tolist()
binsc = copy.copy(bins)
while binsc:
i -= 1
c = binsc.pop(-1)
b[np.nonzero(y <= c)] = i
return b
def bin1d(x, bins):
"""
Place values of a 1-d array into bins and determine counts of values in
each bin
Parameters
----------
x : array
(n, 1), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
binIds : array
1-d array of integer bin Ids
counts : int
number of elements of x falling in each bin
Examples
--------
>>> import numpy as np
>>> import mapclassify as mc
>>> x = np.arange(100, dtype = 'float')
>>> bins = [25, 74, 100]
>>> binIds, counts = mc.classifiers.bin1d(x, bins)
>>> binIds
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
>>> counts
array([26, 49, 25])
"""
left = [-float("inf")]
left.extend(bins[0:-1])
right = bins
cuts = list(zip(left, right))
k = len(bins)
binIds = np.zeros(x.shape, dtype="int")
while cuts:
k -= 1
l, r = cuts.pop(-1)
binIds += (x > l) * (x <= r) * k
counts = np.bincount(binIds, minlength=len(bins))
return (binIds, counts)
def load_example():
"""
Helper function for doc tests
"""
from .datasets import calemp
return calemp.load()
def _kmeans(y, k=5, n_init=10):
"""
Helper function to do k-means in one dimension
Parameters
----------
y : array
(n,1), values to classify
k : int
number of classes to form
n_init : int, default: 10
number of initial solutions. Best of initial results is returned.
"""
y = y * 1.0 # KMEANS needs float or double dtype
y.shape = (-1, 1)
result = KMEANS(n_clusters=k, init="k-means++", n_init=n_init).fit(y)
class_ids = result.labels_
centroids = result.cluster_centers_
binning = []
for c in range(k):
values = y[class_ids == c]
binning.append([values.max(), len(values)])
binning = np.array(binning)
binning = binning[binning[:, 0].argsort()]
cuts = binning[:, 0]
y_cent = np.zeros_like(y)
for c in range(k):
y_cent[class_ids == c] = centroids[c]
diffs = y - y_cent
diffs *= diffs
return class_ids, cuts, diffs.sum(), centroids
def natural_breaks(values, k=5, init=10):
"""
natural breaks helper function
Jenks natural breaks is kmeans in one dimension
Parameters
----------
values : array
(n, 1) values to bin
k : int
Number of classes
init: int, default:10
Number of different solutions to obtain using different centroids. Best solution is returned.
"""
values = np.array(values)
uv = np.unique(values)
uvk = len(uv)
if uvk < k:
Warn(
"Warning: Not enough unique values in array to form k classes", UserWarning
)
Warn("Warning: setting k to %d" % uvk, UserWarning)
k = uvk
kres = _kmeans(values, k, n_init=init)
sids = kres[-1] # centroids
fit = kres[-2]
class_ids = kres[0]
cuts = kres[1]
return (sids, class_ids, fit, cuts)
@jit
def _fisher_jenks_means(values, classes=5, sort=True):
"""
Jenks Optimal (Natural Breaks) algorithm implemented in Python.
Notes
-----
The original Python code comes from here:
http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
and is based on a JAVA and Fortran code available here:
https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html
Returns class breaks such that classes are internally homogeneous while
assuring heterogeneity among classes.
"""
if sort:
values.sort()
n_data = len(values)
mat1 = np.zeros((n_data + 1, classes + 1), dtype=np.int32)
mat2 = np.zeros((n_data + 1, classes + 1), dtype=np.float32)
mat1[1, 1:] = 1
mat2[2:, 1:] = np.inf
v = np.float32(0)
for l in range(2, len(values) + 1):
s1 = np.float32(0)
s2 = np.float32(0)
w = np.float32(0)
for m in range(1, l + 1):
i3 = l - m + 1
val = np.float32(values[i3 - 1])
s2 += val * val
s1 += val
w += np.float32(1)
v = s2 - (s1 * s1) / w
i4 = i3 - 1
if i4 != 0:
for j in range(2, classes + 1):
if mat2[l, j] >= (v + mat2[i4, j - 1]):
mat1[l, j] = i3
mat2[l, j] = v + mat2[i4, j - 1]
mat1[l, 1] = 1
mat2[l, 1] = v
k = len(values)
kclass = np.zeros(classes + 1, dtype=values.dtype)
kclass[classes] = values[len(values) - 1]
kclass[0] = values[0]
for countNum in range(classes, 1, -1):
pivot = mat1[k, countNum]
id = int(pivot - 2)
kclass[countNum - 1] = values[id]
k = int(pivot - 1)
return kclass
class MapClassifier(object):
r"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on different criteria,
but in all cases the following hold for the classifiers in PySAL:
.. math:: C_j^l < y_i \le C_j^u \ \forall i \in C_j
where :math:`C_j` denotes class :math:`j` which has lower bound
:math:`C_j^l` and upper bound :math:`C_j^u`.
Map Classifiers Supported
* :class:`mapclassify.classifiers.BoxPlot`
* :class:`mapclassify.classifiers.EqualInterval`
* :class:`mapclassify.classifiers.FisherJenks`
* :class:`mapclassify.classifiers.FisherJenksSampled`
* :class:`mapclassify.classifiers.HeadTailBreaks`
* :class:`mapclassify.classifiers.JenksCaspall`
* :class:`mapclassify.classifiers.JenksCaspallForced`
* :class:`mapclassify.classifiers.JenksCaspallSampled`
* :class:`mapclassify.classifiers.MaxP`
* :class:`mapclassify.classifiers.MaximumBreaks`
* :class:`mapclassify.classifiers.NaturalBreaks`
* :class:`mapclassify.classifiers.Quantiles`
* :class:`mapclassify.classifiers.Percentiles`
* :class:`mapclassify.classifiers.StdMean`
* :class:`mapclassify.classifiers.UserDefined`
Utilities:
In addition to the classifiers, there are several utility functions that
can be used to evaluate the properties of a specific classifier,
or for automatic selection of a classifier and
number of classes.
* :func:`mapclassify.classifiers.gadf`
* :class:`mapclassify.classifiers.K_classifiers`
"""
def __init__(self, y):
y = np.asarray(y).flatten()
self.name = "Map Classifier"
self.fmt = FMT
self.y = y
self._classify()
self._summary()
def get_fmt(self):
return self._fmt
def set_fmt(self, fmt):
self._fmt = fmt
fmt = property(get_fmt, set_fmt)
def _summary(self):
yb = self.yb
self.classes = [np.nonzero(yb == c)[0].tolist() for c in range(self.k)]
self.tss = self.get_tss()
self.adcm = self.get_adcm()
self.gadf = self.get_gadf()
def _classify(self):
self._set_bins()
self.yb, self.counts = bin1d(self.y, self.bins)
def _update(self, data, *args, **kwargs):
"""
The only thing that *should* happen in this function is
1. input sanitization for pandas
2. classification/reclassification.
Using their __init__ methods, all classifiers can re-classify given
different input parameters or additional data.
If you've got a cleverer updating equation than the intial estimation
equation, remove the call to self.__init__ below and replace it with
the updating function.
"""
if data is not None:
data = np.asarray(data).flatten()
data = np.append(data.flatten(), self.y)
else:
data = self.y
self.__init__(data, *args, **kwargs)
@classmethod
def make(cls, *args, **kwargs):
"""
Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` creates a function that returns classifications; it
does not actually do the classification.
If you want to classify data directly, use the appropriate class
constructor, like Quantiles, Max_Breaks, etc.
If you *have* a classifier object, but want to find which bins new data
falls into, use find_bin.
Parameters
----------
*args : required positional arguments
all positional arguments required by the classifier,
excluding the input data.
rolling : bool
a boolean configuring the outputted classifier to use
a rolling classifier rather than a new classifier for
each input. If rolling, this adds the current data to
all of the previous data in the classifier, and
rebalances the bins, like a running median
computation.
return_object : bool
a boolean configuring the outputted classifier to
return the classifier object or not
return_bins : bool
a boolean configuring the outputted classifier to
return the bins/breaks or not
return_counts : bool
a boolean configuring the outputted classifier to
return the histogram of objects falling into each bin
or not
Returns
-------
A function that consumes data and returns their bins (and object,
bins/breaks, or counts, if requested).
Note
----
This is most useful when you want to run a classifier many times
with a given configuration, such as when classifying many columns of an
array or dataframe using the same configuration.
Examples
--------
>>> import libpysal as ps
>>> import mapclassify as mc
>>> import geopandas as gpd
>>> df = gpd.read_file(ps.examples.get_path('columbus.dbf'))
>>> classifier = mc.Quantiles.make(k=9)
>>> cl = df[['HOVAL', 'CRIME', 'INC']].apply(classifier)
>>> cl["HOVAL"].values[:10]
array([8, 7, 2, 4, 1, 3, 8, 5, 7, 8])
>>> cl["CRIME"].values[:10]
array([0, 1, 3, 4, 6, 2, 0, 5, 3, 4])
>>> cl["INC"].values[:10]
array([7, 8, 5, 0, 3, 5, 0, 3, 6, 4])
>>> import pandas as pd; from numpy import linspace as lsp
>>> data = [lsp(3,8,num=10), lsp(10, 0, num=10), lsp(-5, 15, num=10)]
>>> data = pd.DataFrame(data).T
>>> data
0 1 2
0 3.000000 10.000000 -5.000000
1 3.555556 8.888889 -2.777778
2 4.111111 7.777778 -0.555556
3 4.666667 6.666667 1.666667
4 5.222222 5.555556 3.888889
5 5.777778 4.444444 6.111111
6 6.333333 3.333333 8.333333
7 6.888889 2.222222 10.555556
8 7.444444 1.111111 12.777778
9 8.000000 0.000000 15.000000
>>> data.apply(mc.Quantiles.make(rolling=True))
0 1 2
0 0 4 0
1 0 4 0
2 1 4 0
3 1 3 0
4 2 2 1
5 2 1 2
6 3 0 4
7 3 0 4
8 4 0 4
9 4 0 4
>>> dbf = ps.io.open(ps.examples.get_path('baltim.dbf'))
>>> data = dbf.by_col_array('PRICE', 'LOTSZ', 'SQFT')
>>> my_bins = [1, 10, 20, 40, 80]
>>> cl = [mc.UserDefined.make(bins=my_bins)(a) for a in data.T]
>>> len(cl)
3
>>> cl[0][:10]
array([4, 5, 5, 5, 4, 4, 5, 4, 4, 5])
"""
# only flag overrides return flag
to_annotate = copy.deepcopy(kwargs)
return_object = kwargs.pop("return_object", False)
return_bins = kwargs.pop("return_bins", False)
return_counts = kwargs.pop("return_counts", False)
rolling = kwargs.pop("rolling", False)
if rolling:
# just initialize a fake classifier
data = list(range(10))
cls_instance = cls(data, *args, **kwargs)
# and empty it, since we'll be using the update
cls_instance.y = np.array([])
else:
cls_instance = None
# wrap init in a closure to make a consumer.
# Qc Na: "Objects/Closures are poor man's Closures/Objects"
def classifier(data, cls_instance=cls_instance):
if rolling:
cls_instance.update(data, inplace=True, **kwargs)
yb = cls_instance.find_bin(data)
else:
cls_instance = cls(data, *args, **kwargs)
yb = cls_instance.yb
outs = [yb, None, None, None]
outs[1] = cls_instance if return_object else None
outs[2] = cls_instance.bins if return_bins else None
outs[3] = cls_instance.counts if return_counts else None
outs = [a for a in outs if a is not None]
if len(outs) == 1:
return outs[0]
else:
return outs
# for debugging/jic, keep around the kwargs.
# in future, we might want to make this a thin class, so that we can
# set a custom repr. Call the class `Binner` or something, that's a
# pre-configured Classifier that just consumes data, bins it, &
# possibly updates the bins.
classifier._options = to_annotate
return classifier
def update(self, y=None, inplace=False, **kwargs):
"""
Add data or change classification parameters.
Parameters
----------
y : array
(n,1) array of data to classify
inplace : bool
whether to conduct the update in place or to return a copy
estimated from the additional specifications.
Additional parameters provided in **kwargs are passed to the init
function of the class. For documentation, check the class constructor.
"""
kwargs.update({"k": kwargs.pop("k", self.k)})
if inplace:
self._update(y, **kwargs)
else:
new = copy.deepcopy(self)
new._update(y, **kwargs)
return new
def __str__(self):
return self.table()
def __repr__(self):
return self.table()
def table(self):
fmt = self.fmt
return _get_table(self, fmt=fmt)
def __call__(self, *args, **kwargs):
"""
This will allow the classifier to be called like it's a function.
Whether or not we want to make this be "find_bin" or "update" is a
design decision.
I like this as find_bin, since a classifier's job should be to classify
the data given to it using the rules estimated from the `_classify()`
function.
"""
return self.find_bin(*args)
def get_tss(self):
"""
Total sum of squares around class means
Returns sum of squares over all class means
"""
tss = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
tss += sum(css)
return tss
def _set_bins(self):
pass
def get_adcm(self):
"""
Absolute deviation around class median (ADCM).
Calculates the absolute deviations of each observation about its class
median as a measure of fit for the classification method.
Returns sum of ADCM over all classes
"""
adcm = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
yc_med = np.median(yc)
ycd = np.abs(yc - yc_med)
adcm += sum(ycd)
return adcm
def get_gadf(self):
"""
Goodness of absolute deviation of fit
"""
adam = (np.abs(self.y - np.median(self.y))).sum()
gadf = 1 - self.adcm / adam
return gadf
def _table_string(self, width=12, decimal=3):
labels, largest = self.get_legend_classes(table=True)
h1 = "Lower"
h1 = h1.center(largest)
h2 = " "
h2 = h2.center(10)
h3 = "Upper"
h3 = h3.center(largest + 1)
largest = "%d" % max(self.counts)
largest = len(largest) + 15
h4 = "Count"
h4 = h4.rjust(largest)
table = []
header = h1 + h2 + h3 + h4
table.append(header)
table.append("=" * len(header))
for i, label in enumerate(labels):
left, right = label.split()
if i == 0:
left = " " * largest
left += " x[i] <= "
else:
left += " < x[i] <= "
row = left + right
cnt = "%d" % self.counts[i]
cnt = cnt.rjust(largest)
row += cnt
table.append(row)
name = self.name
top = name.center(len(row))
table.insert(0, top)
table.insert(1, " ")
table = "\n".join(table)
return table
def find_bin(self, x):
"""
Sort input or inputs according to the current bin estimate
Parameters
----------
x : array or numeric
a value or array of values to fit within the estimated
bins
Returns
-------
a bin index or array of bin indices that classify the input into one of
the classifiers' bins.
Note that this differs from similar functionality in
numpy.digitize(x, classi.bins, right=True).
This will always provide the closest bin, so data "outside" the classifier,
above and below the max/min breaks, will be classified into the nearest bin.
numpy.digitize returns k+1 for data greater than the greatest bin, but retains 0
for data below the lowest bin.
"""
x = np.asarray(x).flatten()
right = np.digitize(x, self.bins, right=True)
if right.max() == len(self.bins):
right[right == len(self.bins)] = len(self.bins) - 1
return right
def get_legend_classes(self, fmt=FMT):
"""
Format the strings for the classes on the legend
Parameters
==========
fmt : string
formatting specification
Returns
=======
classes: list
k strings with class interval definitions
"""
return _get_mpl_labels(self, fmt)
def plot(
self,
gdf,
border_color="lightgrey",
border_width=0.10,
title=None,
legend=False,
cmap="YlGnBu",
axis_on=True,
legend_kwds={"loc": "lower right", "fmt": FMT},
file_name=None,
dpi=600,
ax=None,
):
"""
Plot Mapclassiifer
NOTE: Requires matplotlib, and implicitly requires geopandas
dataframe as input.
Parameters
---------
gdf : geopandas geodataframe
Contains the geometry column for the choropleth map
border_color : string, optional