pyearthforge 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyearthforge/__init__.py +27 -0
- pyearthforge/_errors.py +125 -0
- pyearthforge/add.py +21 -0
- pyearthforge/classifier.py +1154 -0
- pyearthforge/cluster.py +657 -0
- pyearthforge/pca.py +222 -0
- pyearthforge/raster.py +3326 -0
- pyearthforge/subtract.py +21 -0
- pyearthforge/vector.py +2080 -0
- pyearthforge-0.1.0.dist-info/METADATA +233 -0
- pyearthforge-0.1.0.dist-info/RECORD +14 -0
- pyearthforge-0.1.0.dist-info/WHEEL +5 -0
- pyearthforge-0.1.0.dist-info/licenses/LICENSE +21 -0
- pyearthforge-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1154 @@
|
|
|
1
|
+
# classifier.py -> supervised classification and regression for images and tables
|
|
2
|
+
#
|
|
3
|
+
# Usage:
|
|
4
|
+
# from pyearthforge import raster, vector, classifier
|
|
5
|
+
# img = raster.image("sampleImage1.tif")
|
|
6
|
+
# bands = ["B2", "B3", "B4", "B8", "B11", "B12"]
|
|
7
|
+
# points = vector.Open("sample_data/training_points.geojson") # has a "landcover" column
|
|
8
|
+
# training = img.select(bands).sampleRegions(points, properties=["landcover"])
|
|
9
|
+
# trained = classifier.randomForest(100).train(training, "landcover", bands)
|
|
10
|
+
# classified = img.classify(trained) # lazy, one band
|
|
11
|
+
# classified.save("landcover.tif") # streamed, block by block
|
|
12
|
+
#
|
|
13
|
+
# test = training.randomColumn().filter(vector.Filter.gte("random", 0.7))
|
|
14
|
+
# test.classify(trained).errorMatrix("landcover", "classification").info()
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import threading
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
from ._errors import LibraryError, clean_class, clean_errors
|
|
24
|
+
|
|
25
|
+
_MODES = ("CLASSIFICATION", "REGRESSION", "PROBABILITY", "MULTIPROBABILITY")
|
|
26
|
+
_KERNELS = {"LINEAR": "linear", "POLY": "poly", "RBF": "rbf", "SIGMOID": "sigmoid"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MissingDependencyError(LibraryError, ImportError):
|
|
30
|
+
"""Raised when an optional package (e.g. xgboost) is needed but not installed."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ====================================================================== #
|
|
34
|
+
# Training data
|
|
35
|
+
# ====================================================================== #
|
|
36
|
+
|
|
37
|
+
def _labels(values):
|
|
38
|
+
"""Class values as a clean numpy array: whole numbers -> int64, other numbers -> float64."""
|
|
39
|
+
values = pd.Series(values)
|
|
40
|
+
if pd.api.types.is_bool_dtype(values):
|
|
41
|
+
return values.astype("int64").to_numpy()
|
|
42
|
+
if pd.api.types.is_numeric_dtype(values):
|
|
43
|
+
arr = values.to_numpy(dtype="float64")
|
|
44
|
+
if np.all(np.isfinite(arr)) and np.all(arr == np.round(arr)):
|
|
45
|
+
return arr.astype("int64")
|
|
46
|
+
return arr
|
|
47
|
+
return values.astype(str).to_numpy(dtype=object)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _training_data(features, classProperty, inputProperties, regression):
|
|
51
|
+
"""Vector / DataFrame -> (X float64, y, input names). Rows with gaps are dropped."""
|
|
52
|
+
from .raster import Image
|
|
53
|
+
from .vector import Vector
|
|
54
|
+
if isinstance(features, Image):
|
|
55
|
+
raise TypeError("train() needs a table of training samples, not an image. Sample the image at your "
|
|
56
|
+
"training data first, e.g. training = img.sampleRegions(points, properties=['landcover']).")
|
|
57
|
+
if isinstance(features, Vector):
|
|
58
|
+
table = features.data
|
|
59
|
+
elif isinstance(features, pd.DataFrame):
|
|
60
|
+
table = features
|
|
61
|
+
else:
|
|
62
|
+
raise TypeError("train() expects training samples as a Vector, e.g. img.sampleRegions(points, "
|
|
63
|
+
"properties=['landcover']), or a pandas DataFrame.")
|
|
64
|
+
geom = getattr(table, "_geometry_column_name", None)
|
|
65
|
+
columns = [c for c in table.columns if c != geom]
|
|
66
|
+
if not isinstance(classProperty, str):
|
|
67
|
+
raise TypeError(f"classProperty must be a column name, got {classProperty!r}")
|
|
68
|
+
if classProperty not in table.columns:
|
|
69
|
+
raise ValueError(f"Column '{classProperty}' not found. Columns: {columns}")
|
|
70
|
+
if inputProperties is None:
|
|
71
|
+
names = [c for c in columns if c != classProperty and pd.api.types.is_numeric_dtype(table[c])
|
|
72
|
+
and not pd.api.types.is_bool_dtype(table[c])]
|
|
73
|
+
if not names:
|
|
74
|
+
raise ValueError("The training data has no numeric columns to learn from.")
|
|
75
|
+
else:
|
|
76
|
+
names = [inputProperties] if isinstance(inputProperties, str) else list(inputProperties)
|
|
77
|
+
for n in names:
|
|
78
|
+
if n not in table.columns:
|
|
79
|
+
raise ValueError(f"Column '{n}' not found. Columns: {columns}")
|
|
80
|
+
if not pd.api.types.is_numeric_dtype(table[n]):
|
|
81
|
+
raise ValueError(f"Column '{n}' is not numeric, so it can't be used for training.")
|
|
82
|
+
if classProperty in names:
|
|
83
|
+
raise ValueError(f"'{classProperty}' is the class column; it can't also be an input.")
|
|
84
|
+
X = table[names].to_numpy(dtype="float64")
|
|
85
|
+
target = table[classProperty]
|
|
86
|
+
if regression:
|
|
87
|
+
if not pd.api.types.is_numeric_dtype(target):
|
|
88
|
+
raise ValueError(f"Column '{classProperty}' must hold numbers for regression.")
|
|
89
|
+
y = target.to_numpy(dtype="float64")
|
|
90
|
+
keep = np.isfinite(X).all(axis=1) & np.isfinite(y)
|
|
91
|
+
return X[keep], y[keep], [str(n) for n in names]
|
|
92
|
+
keep = np.isfinite(X).all(axis=1) & target.notna().to_numpy()
|
|
93
|
+
return X[keep], _labels(target[keep]), [str(n) for n in names]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _check_count(value, label, minimum=1, allow_none=False):
|
|
97
|
+
if value is None and allow_none:
|
|
98
|
+
return None
|
|
99
|
+
if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < minimum:
|
|
100
|
+
raise ValueError(f"{label} must be a whole number of {minimum} or more, got {value!r}")
|
|
101
|
+
return int(value)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _check_fraction(value, label, allow_none=True):
|
|
105
|
+
if value is None and allow_none:
|
|
106
|
+
return None
|
|
107
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, np.number)) or not 0 < value <= 1:
|
|
108
|
+
raise ValueError(f"{label} must be a number above 0 and at most 1, got {value!r}")
|
|
109
|
+
return float(value)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ====================================================================== #
|
|
113
|
+
# Confusion matrix
|
|
114
|
+
# ====================================================================== #
|
|
115
|
+
|
|
116
|
+
class ConfusionMatrix:
|
|
117
|
+
"""A confusion (error) matrix with accuracy measures.
|
|
118
|
+
|
|
119
|
+
Rows are the actual (reference) classes, columns the predicted classes,
|
|
120
|
+
in the order given by ``order()``. Get one from
|
|
121
|
+
``trained.confusionMatrix()`` (training accuracy) or from
|
|
122
|
+
``validated.errorMatrix("landcover", "classification")`` (accuracy on
|
|
123
|
+
independent validation samples).
|
|
124
|
+
|
|
125
|
+
Examples
|
|
126
|
+
--------
|
|
127
|
+
>>> matrix = validated.errorMatrix("landcover", "classification")
|
|
128
|
+
>>> matrix.accuracy()
|
|
129
|
+
0.947
|
|
130
|
+
>>> matrix.info()
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, actual, predicted, order=None, title="Confusion matrix"):
|
|
134
|
+
# Built by errorMatrix() / confusionMatrix(); users don't call this directly.
|
|
135
|
+
actual, predicted = _labels(actual), _labels(predicted)
|
|
136
|
+
if order is None:
|
|
137
|
+
order = sorted(set(actual.tolist()) | set(predicted.tolist()), key=lambda v: (str(type(v)), v))
|
|
138
|
+
order = list(order)
|
|
139
|
+
index = {value: i for i, value in enumerate(order)}
|
|
140
|
+
matrix = np.zeros((len(order), len(order)), dtype="int64")
|
|
141
|
+
for a, p in zip(actual.tolist(), predicted.tolist()):
|
|
142
|
+
if a in index and p in index:
|
|
143
|
+
matrix[index[a], index[p]] += 1
|
|
144
|
+
self._order = order
|
|
145
|
+
self._matrix = matrix
|
|
146
|
+
self._title = title
|
|
147
|
+
|
|
148
|
+
def array(self):
|
|
149
|
+
"""Returns the matrix as a numpy array (rows: actual classes, columns: predicted classes).
|
|
150
|
+
|
|
151
|
+
Examples
|
|
152
|
+
--------
|
|
153
|
+
>>> matrix.array()
|
|
154
|
+
array([[52, 0, 1, 0],
|
|
155
|
+
[ 0, 47, 3, 0],
|
|
156
|
+
...])
|
|
157
|
+
"""
|
|
158
|
+
return self._matrix.copy()
|
|
159
|
+
|
|
160
|
+
def order(self):
|
|
161
|
+
"""Returns the class values in the order of the matrix rows and columns.
|
|
162
|
+
|
|
163
|
+
Examples
|
|
164
|
+
--------
|
|
165
|
+
>>> matrix.order()
|
|
166
|
+
[0, 1, 2, 3]
|
|
167
|
+
"""
|
|
168
|
+
return list(self._order)
|
|
169
|
+
|
|
170
|
+
def accuracy(self):
|
|
171
|
+
"""Returns the overall accuracy: the share of samples that were classified correctly (0 to 1).
|
|
172
|
+
|
|
173
|
+
Examples
|
|
174
|
+
--------
|
|
175
|
+
>>> matrix.accuracy()
|
|
176
|
+
0.947
|
|
177
|
+
"""
|
|
178
|
+
total = self._matrix.sum()
|
|
179
|
+
return float(np.trace(self._matrix) / total) if total else float("nan")
|
|
180
|
+
|
|
181
|
+
def kappa(self):
|
|
182
|
+
"""Returns Cohen's kappa: agreement beyond what chance alone would give (1 = perfect, 0 = chance).
|
|
183
|
+
|
|
184
|
+
Examples
|
|
185
|
+
--------
|
|
186
|
+
>>> matrix.kappa()
|
|
187
|
+
0.928
|
|
188
|
+
"""
|
|
189
|
+
total = self._matrix.sum()
|
|
190
|
+
if not total:
|
|
191
|
+
return float("nan")
|
|
192
|
+
observed = np.trace(self._matrix) / total
|
|
193
|
+
expected = float((self._matrix.sum(axis=1) * self._matrix.sum(axis=0)).sum()) / total ** 2
|
|
194
|
+
return float((observed - expected) / (1 - expected)) if expected < 1 else float("nan")
|
|
195
|
+
|
|
196
|
+
def producersAccuracy(self):
|
|
197
|
+
"""Returns the producer's accuracy (recall) per class.
|
|
198
|
+
|
|
199
|
+
Of all samples that truly belong to a class, the share that was
|
|
200
|
+
classified as that class. Low values mean the class is missed
|
|
201
|
+
(omission errors).
|
|
202
|
+
|
|
203
|
+
Returns
|
|
204
|
+
-------
|
|
205
|
+
dict
|
|
206
|
+
class value -> accuracy (0 to 1; NaN when the class has no samples).
|
|
207
|
+
|
|
208
|
+
Examples
|
|
209
|
+
--------
|
|
210
|
+
>>> matrix.producersAccuracy()
|
|
211
|
+
{0: 0.98, 1: 0.94, 2: 0.9, 3: 0.97}
|
|
212
|
+
"""
|
|
213
|
+
return self._per_class(self._matrix.sum(axis=1))
|
|
214
|
+
|
|
215
|
+
def consumersAccuracy(self):
|
|
216
|
+
"""Returns the consumer's (user's) accuracy, or precision, per class.
|
|
217
|
+
|
|
218
|
+
Of all samples classified as a class, the share that truly belongs to
|
|
219
|
+
it. Low values mean other classes leak into it (commission errors).
|
|
220
|
+
|
|
221
|
+
Returns
|
|
222
|
+
-------
|
|
223
|
+
dict
|
|
224
|
+
class value -> accuracy (0 to 1; NaN when nothing was classified as the class).
|
|
225
|
+
|
|
226
|
+
Examples
|
|
227
|
+
--------
|
|
228
|
+
>>> matrix.consumersAccuracy()
|
|
229
|
+
{0: 1.0, 1: 0.96, 2: 0.88, 3: 0.95}
|
|
230
|
+
"""
|
|
231
|
+
return self._per_class(self._matrix.sum(axis=0))
|
|
232
|
+
|
|
233
|
+
def fscore(self, beta=1):
|
|
234
|
+
"""Returns the F-score per class: the balance of producer's and consumer's accuracy.
|
|
235
|
+
|
|
236
|
+
Parameters
|
|
237
|
+
----------
|
|
238
|
+
beta : float, default 1
|
|
239
|
+
1 weighs both equally (F1). Larger values favour producer's accuracy (recall).
|
|
240
|
+
|
|
241
|
+
Returns
|
|
242
|
+
-------
|
|
243
|
+
dict
|
|
244
|
+
class value -> F-score (0 to 1).
|
|
245
|
+
|
|
246
|
+
Examples
|
|
247
|
+
--------
|
|
248
|
+
>>> matrix.fscore()
|
|
249
|
+
{0: 0.99, 1: 0.95, 2: 0.89, 3: 0.96}
|
|
250
|
+
"""
|
|
251
|
+
if isinstance(beta, bool) or not isinstance(beta, (int, float)) or beta <= 0:
|
|
252
|
+
raise ValueError(f"beta must be a positive number, got {beta!r}")
|
|
253
|
+
recall, precision = self.producersAccuracy(), self.consumersAccuracy()
|
|
254
|
+
b2 = beta ** 2
|
|
255
|
+
out = {}
|
|
256
|
+
for c in self._order:
|
|
257
|
+
r, p = recall[c], precision[c]
|
|
258
|
+
out[c] = float((1 + b2) * p * r / (b2 * p + r)) if (b2 * p + r) > 0 else float("nan")
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
def table(self, labels=None):
|
|
262
|
+
"""Returns the matrix as a table with row and column totals.
|
|
263
|
+
|
|
264
|
+
Parameters
|
|
265
|
+
----------
|
|
266
|
+
labels : dict, optional
|
|
267
|
+
Names for the class values, e.g. ``{0: "Water", 1: "Built-up"}``.
|
|
268
|
+
|
|
269
|
+
Returns
|
|
270
|
+
-------
|
|
271
|
+
pandas.DataFrame
|
|
272
|
+
|
|
273
|
+
Examples
|
|
274
|
+
--------
|
|
275
|
+
>>> matrix.table(labels={0: "Water", 1: "Built-up", 2: "Grassland", 3: "Forest"})
|
|
276
|
+
"""
|
|
277
|
+
names = [self._name(c, labels) for c in self._order]
|
|
278
|
+
table = pd.DataFrame(self._matrix, index=names, columns=names)
|
|
279
|
+
table["Total"] = table.sum(axis=1)
|
|
280
|
+
table.loc["Total"] = table.sum(axis=0)
|
|
281
|
+
table.index.name = "actual \\ predicted"
|
|
282
|
+
return table
|
|
283
|
+
|
|
284
|
+
def info(self, labels=None):
|
|
285
|
+
"""Prints the matrix, overall accuracy, kappa and the per-class accuracies.
|
|
286
|
+
|
|
287
|
+
Parameters
|
|
288
|
+
----------
|
|
289
|
+
labels : dict, optional
|
|
290
|
+
Names for the class values, e.g. ``{0: "Water", 1: "Built-up"}``.
|
|
291
|
+
|
|
292
|
+
Returns
|
|
293
|
+
-------
|
|
294
|
+
dict
|
|
295
|
+
accuracy, kappa, producersAccuracy, consumersAccuracy, fscore, order, matrix.
|
|
296
|
+
|
|
297
|
+
Examples
|
|
298
|
+
--------
|
|
299
|
+
>>> validated.errorMatrix("landcover", "classification").info(labels=names)
|
|
300
|
+
"""
|
|
301
|
+
recall, precision, f1 = self.producersAccuracy(), self.consumersAccuracy(), self.fscore()
|
|
302
|
+
m = {"accuracy": self.accuracy(), "kappa": self.kappa(), "producersAccuracy": recall,
|
|
303
|
+
"consumersAccuracy": precision, "fscore": f1, "order": self.order(),
|
|
304
|
+
"matrix": self._matrix.tolist()}
|
|
305
|
+
print("=" * 64)
|
|
306
|
+
print(f" {self._title} (rows: actual, columns: predicted)")
|
|
307
|
+
print("=" * 64)
|
|
308
|
+
print(" " + self.table(labels).to_string().replace("\n", "\n "))
|
|
309
|
+
print("-" * 64)
|
|
310
|
+
print(f" Overall accuracy : {m['accuracy']:.4f}")
|
|
311
|
+
print(f" Kappa : {m['kappa']:.4f}")
|
|
312
|
+
per_class = pd.DataFrame({"producer's": recall, "consumer's": precision, "F1": f1})
|
|
313
|
+
per_class.index = [self._name(c, labels) for c in self._order]
|
|
314
|
+
with pd.option_context("display.precision", 3):
|
|
315
|
+
print(" " + per_class.to_string().replace("\n", "\n "))
|
|
316
|
+
print("=" * 64)
|
|
317
|
+
return m
|
|
318
|
+
|
|
319
|
+
def visualize(self, labels=None, normalize=False, palette="Blues", save_chart=False, dpi=200):
|
|
320
|
+
"""Draws the matrix as a colour-coded chart with the counts written in each cell.
|
|
321
|
+
|
|
322
|
+
Parameters
|
|
323
|
+
----------
|
|
324
|
+
labels : dict, optional
|
|
325
|
+
Names for the class values, e.g. ``{0: "Water", 1: "Built-up"}``.
|
|
326
|
+
normalize : bool, default False
|
|
327
|
+
Show each row as shares of the actual class (0 to 1) instead of counts.
|
|
328
|
+
palette : str, default "Blues"
|
|
329
|
+
A matplotlib colour map name.
|
|
330
|
+
save_chart : bool, default False
|
|
331
|
+
Also save the chart as a PNG named "confusion_matrix_<epoch time>.png".
|
|
332
|
+
dpi : int, default 200
|
|
333
|
+
Resolution of the saved PNG.
|
|
334
|
+
|
|
335
|
+
Returns
|
|
336
|
+
-------
|
|
337
|
+
str or None
|
|
338
|
+
The path of the saved PNG, when `save_chart` is True.
|
|
339
|
+
|
|
340
|
+
Examples
|
|
341
|
+
--------
|
|
342
|
+
>>> matrix.visualize(labels=names)
|
|
343
|
+
>>> matrix.visualize(labels=names, normalize=True, save_chart=True)
|
|
344
|
+
"""
|
|
345
|
+
import time
|
|
346
|
+
import matplotlib.pyplot as plt
|
|
347
|
+
values = self._matrix.astype("float64")
|
|
348
|
+
if normalize:
|
|
349
|
+
rows = values.sum(axis=1, keepdims=True)
|
|
350
|
+
values = np.divide(values, rows, out=np.zeros_like(values), where=rows > 0)
|
|
351
|
+
names = [self._name(c, labels) for c in self._order]
|
|
352
|
+
size = max(4.0, 0.9 * len(names) + 2.5)
|
|
353
|
+
fig, ax = plt.subplots(figsize=(size + 1, size))
|
|
354
|
+
shown = ax.imshow(values, cmap=palette, vmin=0, vmax=1 if normalize else max(1.0, values.max()))
|
|
355
|
+
fig.colorbar(shown, ax=ax, fraction=0.046, pad=0.04, label="share of actual class" if normalize else "samples")
|
|
356
|
+
ax.set_xticks(range(len(names)), names, rotation=45, ha="right")
|
|
357
|
+
ax.set_yticks(range(len(names)), names)
|
|
358
|
+
ax.set_xlabel("Predicted")
|
|
359
|
+
ax.set_ylabel("Actual")
|
|
360
|
+
ax.set_title(f"{self._title}\naccuracy {self.accuracy():.3f}, kappa {self.kappa():.3f}")
|
|
361
|
+
limit = (1 if normalize else max(1.0, values.max())) / 2
|
|
362
|
+
for i in range(len(names)):
|
|
363
|
+
for j in range(len(names)):
|
|
364
|
+
text = f"{values[i, j]:.2f}" if normalize else f"{int(values[i, j])}"
|
|
365
|
+
ax.text(j, i, text, ha="center", va="center",
|
|
366
|
+
color="white" if values[i, j] > limit else "black", fontsize=9)
|
|
367
|
+
fig.tight_layout()
|
|
368
|
+
path = None
|
|
369
|
+
if save_chart:
|
|
370
|
+
path = os.path.abspath(f"confusion_matrix_{int(time.time())}.png")
|
|
371
|
+
fig.savefig(path, dpi=dpi, bbox_inches="tight")
|
|
372
|
+
print(f"Chart saved: {path} ({dpi} dpi)")
|
|
373
|
+
plt.show()
|
|
374
|
+
return path
|
|
375
|
+
|
|
376
|
+
def _per_class(self, totals):
|
|
377
|
+
diag = np.diag(self._matrix)
|
|
378
|
+
return {c: (float(diag[i] / totals[i]) if totals[i] else float("nan")) for i, c in enumerate(self._order)}
|
|
379
|
+
|
|
380
|
+
@staticmethod
|
|
381
|
+
def _name(value, labels):
|
|
382
|
+
return str(labels.get(value, value)) if labels else str(value)
|
|
383
|
+
|
|
384
|
+
def __repr__(self):
|
|
385
|
+
return (f"ConfusionMatrix ({self._title}): accuracy {self.accuracy():.4f}, kappa {self.kappa():.4f}\n"
|
|
386
|
+
+ self.table().to_string())
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# ====================================================================== #
|
|
390
|
+
# Regression accuracy
|
|
391
|
+
# ====================================================================== #
|
|
392
|
+
|
|
393
|
+
def _regression_metrics(actual, predicted):
|
|
394
|
+
actual = np.asarray(actual, dtype="float64")
|
|
395
|
+
predicted = np.asarray(predicted, dtype="float64")
|
|
396
|
+
keep = np.isfinite(actual) & np.isfinite(predicted)
|
|
397
|
+
a, p = actual[keep], predicted[keep]
|
|
398
|
+
n = int(len(a))
|
|
399
|
+
if n == 0:
|
|
400
|
+
raise ValueError("No rows have both an actual and a predicted value.")
|
|
401
|
+
err = p - a
|
|
402
|
+
ss_tot = float(np.square(a - a.mean()).sum())
|
|
403
|
+
r = float(np.corrcoef(a, p)[0, 1]) if n > 1 and a.std() > 0 and p.std() > 0 else float("nan")
|
|
404
|
+
return {"n": n,
|
|
405
|
+
"rmse": float(np.sqrt(np.mean(err ** 2))),
|
|
406
|
+
"mae": float(np.mean(np.abs(err))),
|
|
407
|
+
"bias": float(np.mean(err)),
|
|
408
|
+
"r2": float(1 - np.square(err).sum() / ss_tot) if ss_tot > 0 else float("nan"),
|
|
409
|
+
"pearsonR": r}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# ====================================================================== #
|
|
413
|
+
# Classifier (untrained) and TrainedClassifier
|
|
414
|
+
# ====================================================================== #
|
|
415
|
+
|
|
416
|
+
class Classifier:
|
|
417
|
+
"""A supervised classifier, ready to be trained.
|
|
418
|
+
|
|
419
|
+
Create one with classifier.randomForest(), classifier.xgboost(), ...
|
|
420
|
+
By default it predicts classes; ``setOutputMode("REGRESSION")`` makes it
|
|
421
|
+
predict numbers instead, and "PROBABILITY" / "MULTIPROBABILITY" give class
|
|
422
|
+
probabilities.
|
|
423
|
+
|
|
424
|
+
Examples
|
|
425
|
+
--------
|
|
426
|
+
>>> rf = classifier.randomForest(100)
|
|
427
|
+
>>> trained = rf.train(training, "landcover", bands)
|
|
428
|
+
>>> regressor = classifier.randomForest(100).setOutputMode("REGRESSION")
|
|
429
|
+
"""
|
|
430
|
+
|
|
431
|
+
def __init__(self, name, params, build, regression=True, probability=True, mode="CLASSIFICATION"):
|
|
432
|
+
# Built by the functions in this module; users don't call this directly.
|
|
433
|
+
self._name = name
|
|
434
|
+
self._params = params
|
|
435
|
+
self._build = build
|
|
436
|
+
self._regression = regression
|
|
437
|
+
self._probability = probability
|
|
438
|
+
self._mode = mode
|
|
439
|
+
|
|
440
|
+
@property
|
|
441
|
+
def mode(self):
|
|
442
|
+
"""The output mode: "CLASSIFICATION", "REGRESSION", "PROBABILITY" or "MULTIPROBABILITY".
|
|
443
|
+
|
|
444
|
+
Examples
|
|
445
|
+
--------
|
|
446
|
+
>>> classifier.randomForest(50).setOutputMode("REGRESSION").mode
|
|
447
|
+
'REGRESSION'
|
|
448
|
+
"""
|
|
449
|
+
return self._mode
|
|
450
|
+
|
|
451
|
+
def setOutputMode(self, mode):
|
|
452
|
+
"""Returns a copy of the classifier that gives a different kind of output.
|
|
453
|
+
|
|
454
|
+
Parameters
|
|
455
|
+
----------
|
|
456
|
+
mode : str
|
|
457
|
+
- "CLASSIFICATION" (default): the class value.
|
|
458
|
+
- "REGRESSION": a number (train on a numeric column, e.g. biomass).
|
|
459
|
+
- "PROBABILITY": the probability (0 to 1) that the predicted class is right.
|
|
460
|
+
- "MULTIPROBABILITY": one probability per class (one band / column per class).
|
|
461
|
+
|
|
462
|
+
Returns
|
|
463
|
+
-------
|
|
464
|
+
Classifier
|
|
465
|
+
|
|
466
|
+
Raises
|
|
467
|
+
------
|
|
468
|
+
ValueError
|
|
469
|
+
If the mode is unknown or the method doesn't support it.
|
|
470
|
+
|
|
471
|
+
Examples
|
|
472
|
+
--------
|
|
473
|
+
>>> regressor = classifier.randomForest(100).setOutputMode("REGRESSION")
|
|
474
|
+
>>> probs = classifier.randomForest(100).setOutputMode("MULTIPROBABILITY")
|
|
475
|
+
"""
|
|
476
|
+
if not isinstance(mode, str) or mode.upper() not in _MODES:
|
|
477
|
+
raise ValueError(f"mode must be one of {list(_MODES)}, got {mode!r}")
|
|
478
|
+
mode = mode.upper()
|
|
479
|
+
if mode == "REGRESSION" and not self._regression:
|
|
480
|
+
raise ValueError(f"{self._name} can't do regression. Use e.g. classifier.randomForest().")
|
|
481
|
+
if mode in ("PROBABILITY", "MULTIPROBABILITY") and not self._probability:
|
|
482
|
+
raise ValueError(f"{self._name} doesn't give probabilities.")
|
|
483
|
+
return Classifier(self._name, self._params, self._build, self._regression, self._probability, mode)
|
|
484
|
+
|
|
485
|
+
def train(self, features, classProperty, inputProperties=None, subsampling=None, subsamplingSeed=0):
|
|
486
|
+
"""Trains the classifier on training samples.
|
|
487
|
+
|
|
488
|
+
Parameters
|
|
489
|
+
----------
|
|
490
|
+
features : vector.Vector or pandas.DataFrame
|
|
491
|
+
Training samples: one row per sample, with the known class (or
|
|
492
|
+
value) and the predictor values, usually from
|
|
493
|
+
``img.sampleRegions(points, properties=["landcover"])``.
|
|
494
|
+
classProperty : str
|
|
495
|
+
Column holding the known class (whole numbers or text) or, in
|
|
496
|
+
"REGRESSION" mode, the known value.
|
|
497
|
+
inputProperties : list of str, optional
|
|
498
|
+
The columns (bands) to learn from. Default: every numeric column
|
|
499
|
+
except `classProperty`. Name them explicitly when the table has
|
|
500
|
+
extra numeric columns (e.g. "random" from randomColumn()).
|
|
501
|
+
subsampling : float, optional
|
|
502
|
+
Train on only this share (0 to 1) of the rows, picked at random.
|
|
503
|
+
subsamplingSeed : int, default 0
|
|
504
|
+
Random seed for `subsampling`, and for the method itself.
|
|
505
|
+
|
|
506
|
+
Returns
|
|
507
|
+
-------
|
|
508
|
+
TrainedClassifier
|
|
509
|
+
|
|
510
|
+
Raises
|
|
511
|
+
------
|
|
512
|
+
ValueError
|
|
513
|
+
If a column is missing, there are too few samples, or fewer than two classes.
|
|
514
|
+
|
|
515
|
+
Examples
|
|
516
|
+
--------
|
|
517
|
+
>>> bands = ["B2", "B3", "B4", "B8", "B11", "B12"]
|
|
518
|
+
>>> training = img.select(bands).sampleRegions(points, properties=["landcover"])
|
|
519
|
+
>>> trained = classifier.randomForest(100).train(training, "landcover", bands)
|
|
520
|
+
>>> model = classifier.xgboost().setOutputMode("REGRESSION").train(plots, "canopy_cover_pct", bands)
|
|
521
|
+
"""
|
|
522
|
+
regression = self._mode == "REGRESSION"
|
|
523
|
+
X, y, names = _training_data(features, classProperty, inputProperties, regression)
|
|
524
|
+
fraction = _check_fraction(subsampling, "subsampling")
|
|
525
|
+
seed = int(subsamplingSeed)
|
|
526
|
+
if fraction is not None and fraction < 1:
|
|
527
|
+
pick = np.random.default_rng(seed).random(len(X)) < fraction
|
|
528
|
+
X, y = X[pick], y[pick]
|
|
529
|
+
if len(X) < 2:
|
|
530
|
+
raise ValueError(f"Only {len(X)} valid training samples; need at least 2. "
|
|
531
|
+
"Check that the training data overlaps the image and has values.")
|
|
532
|
+
if regression:
|
|
533
|
+
classes = None
|
|
534
|
+
target = y
|
|
535
|
+
else:
|
|
536
|
+
classes, target = np.unique(y, return_inverse=True)
|
|
537
|
+
if len(classes) < 2:
|
|
538
|
+
raise ValueError(f"The training data has only one class ({classes.tolist()[0]!r}); "
|
|
539
|
+
"need at least two.")
|
|
540
|
+
estimator = self._build("regression" if regression else "classification", self._mode, seed)
|
|
541
|
+
with warnings.catch_warnings():
|
|
542
|
+
warnings.simplefilter("ignore") # e.g. "some inputs have no out-of-bag score"
|
|
543
|
+
estimator.fit(X, target)
|
|
544
|
+
return TrainedClassifier(self._name, dict(self._params), self._mode, names, classes,
|
|
545
|
+
estimator, X, target, seed)
|
|
546
|
+
|
|
547
|
+
def __repr__(self):
|
|
548
|
+
params = ", ".join(f"{k}={v!r}" for k, v in self._params.items())
|
|
549
|
+
return f"Classifier {self._name}({params}), mode {self._mode}, not trained yet"
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
class TrainedClassifier:
|
|
553
|
+
"""A trained classifier: apply it with ``img.classify(trained)`` or ``table.classify(trained)``.
|
|
554
|
+
|
|
555
|
+
Examples
|
|
556
|
+
--------
|
|
557
|
+
>>> trained = classifier.randomForest(100).train(training, "landcover", bands)
|
|
558
|
+
>>> trained.info()
|
|
559
|
+
>>> classified = img.classify(trained)
|
|
560
|
+
"""
|
|
561
|
+
|
|
562
|
+
def __init__(self, name, params, mode, names, classes, estimator, X, target, seed):
|
|
563
|
+
self._name = name
|
|
564
|
+
self._params = params
|
|
565
|
+
self._mode = mode
|
|
566
|
+
self._names = names
|
|
567
|
+
self._classes = classes # None for regression
|
|
568
|
+
self._estimator = estimator
|
|
569
|
+
self._X = X # training data, for confusionMatrix() / importance()
|
|
570
|
+
self._target = target # class indexes (0..k-1) or values
|
|
571
|
+
self._seed = seed
|
|
572
|
+
self._importance = None
|
|
573
|
+
self._threads = None
|
|
574
|
+
self._lock = threading.Lock()
|
|
575
|
+
|
|
576
|
+
# ---- what it is ---------------------------------------------------- #
|
|
577
|
+
|
|
578
|
+
@property
|
|
579
|
+
def mode(self):
|
|
580
|
+
"""The output mode the classifier was trained in.
|
|
581
|
+
|
|
582
|
+
Examples
|
|
583
|
+
--------
|
|
584
|
+
>>> trained.mode
|
|
585
|
+
'CLASSIFICATION'
|
|
586
|
+
"""
|
|
587
|
+
return self._mode
|
|
588
|
+
|
|
589
|
+
@property
|
|
590
|
+
def classes(self):
|
|
591
|
+
"""The class values seen in training, in order (None for regression).
|
|
592
|
+
|
|
593
|
+
Examples
|
|
594
|
+
--------
|
|
595
|
+
>>> trained.classes
|
|
596
|
+
[0, 1, 2, 3]
|
|
597
|
+
"""
|
|
598
|
+
return None if self._classes is None else self._classes.tolist()
|
|
599
|
+
|
|
600
|
+
def schema(self):
|
|
601
|
+
"""Returns the names of the bands / columns the classifier was trained on.
|
|
602
|
+
|
|
603
|
+
Images and tables you classify must have these bands / columns.
|
|
604
|
+
|
|
605
|
+
Examples
|
|
606
|
+
--------
|
|
607
|
+
>>> trained.schema()
|
|
608
|
+
['B2', 'B3', 'B4', 'B8', 'B11', 'B12']
|
|
609
|
+
"""
|
|
610
|
+
return list(self._names)
|
|
611
|
+
|
|
612
|
+
def confusionMatrix(self):
|
|
613
|
+
"""Returns the confusion matrix of the training samples (training, or resubstitution, accuracy).
|
|
614
|
+
|
|
615
|
+
Training accuracy is usually optimistic: a random forest often scores
|
|
616
|
+
close to 1.0 on the samples it learned from. Judge a classifier on
|
|
617
|
+
separate validation samples with ``errorMatrix()`` instead.
|
|
618
|
+
|
|
619
|
+
Returns
|
|
620
|
+
-------
|
|
621
|
+
ConfusionMatrix
|
|
622
|
+
|
|
623
|
+
Raises
|
|
624
|
+
------
|
|
625
|
+
ValueError
|
|
626
|
+
In "REGRESSION" mode.
|
|
627
|
+
|
|
628
|
+
Examples
|
|
629
|
+
--------
|
|
630
|
+
>>> trained.confusionMatrix().accuracy()
|
|
631
|
+
1.0
|
|
632
|
+
"""
|
|
633
|
+
if self._classes is None:
|
|
634
|
+
raise ValueError("confusionMatrix() is for classification. For regression use "
|
|
635
|
+
"table.classify(trained).regressionMetrics('actual', 'classification').")
|
|
636
|
+
predicted = self._classes[self._predict_index(self._X)]
|
|
637
|
+
return ConfusionMatrix(self._classes[self._target], predicted, order=self.classes,
|
|
638
|
+
title="Training confusion matrix")
|
|
639
|
+
|
|
640
|
+
def importance(self):
|
|
641
|
+
"""Returns how much each input contributed to the predictions, in percent (adds up to 100).
|
|
642
|
+
|
|
643
|
+
Tree methods (randomForest, cart, xgboost) report how much each input
|
|
644
|
+
improved their splits. For the others, it is measured by shuffling one
|
|
645
|
+
input at a time and seeing how much the training accuracy (or R²) drops.
|
|
646
|
+
|
|
647
|
+
Returns
|
|
648
|
+
-------
|
|
649
|
+
pandas.Series
|
|
650
|
+
Input name -> percent, largest first.
|
|
651
|
+
|
|
652
|
+
Examples
|
|
653
|
+
--------
|
|
654
|
+
>>> trained.importance()
|
|
655
|
+
B11 24.1
|
|
656
|
+
B8 21.7
|
|
657
|
+
...
|
|
658
|
+
"""
|
|
659
|
+
if self._importance is None:
|
|
660
|
+
est = self._estimator
|
|
661
|
+
values = getattr(est, "feature_importances_", None)
|
|
662
|
+
if values is None:
|
|
663
|
+
from sklearn.inspection import permutation_importance
|
|
664
|
+
X, y = self._X, self._target
|
|
665
|
+
if len(X) > 5000: # enough for a stable estimate
|
|
666
|
+
pick = np.random.default_rng(self._seed).choice(len(X), 5000, replace=False)
|
|
667
|
+
X, y = X[pick], y[pick]
|
|
668
|
+
with warnings.catch_warnings():
|
|
669
|
+
warnings.simplefilter("ignore")
|
|
670
|
+
values = permutation_importance(est, X, y, n_repeats=5,
|
|
671
|
+
random_state=self._seed).importances_mean
|
|
672
|
+
values = np.clip(np.asarray(values, dtype="float64"), 0, None)
|
|
673
|
+
total = values.sum()
|
|
674
|
+
percent = values / total * 100 if total > 0 else values
|
|
675
|
+
self._importance = pd.Series(percent, index=self._names, name="importance (%)")
|
|
676
|
+
return self._importance.sort_values(ascending=False)
|
|
677
|
+
|
|
678
|
+
def explain(self):
|
|
679
|
+
"""Returns a description of the trained classifier as a dictionary.
|
|
680
|
+
|
|
681
|
+
Returns
|
|
682
|
+
-------
|
|
683
|
+
dict
|
|
684
|
+
classifier, params, outputMode, inputs, classes, trainingSamples,
|
|
685
|
+
importance (percent per input) and, for randomForest,
|
|
686
|
+
outOfBagErrorEstimate (classification) or outOfBagR2 (regression).
|
|
687
|
+
|
|
688
|
+
Examples
|
|
689
|
+
--------
|
|
690
|
+
>>> trained.explain()["outOfBagErrorEstimate"]
|
|
691
|
+
0.031
|
|
692
|
+
"""
|
|
693
|
+
info = {"classifier": self._name, "params": dict(self._params), "outputMode": self._mode,
|
|
694
|
+
"inputs": self.schema(), "classes": self.classes, "trainingSamples": int(len(self._X)),
|
|
695
|
+
"importance": {k: round(float(v), 2) for k, v in self.importance().items()}}
|
|
696
|
+
oob = getattr(self._estimator, "oob_score_", None)
|
|
697
|
+
if oob is not None:
|
|
698
|
+
if self._classes is None:
|
|
699
|
+
info["outOfBagR2"] = float(oob)
|
|
700
|
+
else:
|
|
701
|
+
info["outOfBagErrorEstimate"] = float(1 - oob)
|
|
702
|
+
return info
|
|
703
|
+
|
|
704
|
+
def info(self):
|
|
705
|
+
"""Prints a summary: method, settings, inputs, classes, sample counts, accuracy and importance.
|
|
706
|
+
|
|
707
|
+
Returns
|
|
708
|
+
-------
|
|
709
|
+
dict
|
|
710
|
+
The same as ``explain()``.
|
|
711
|
+
|
|
712
|
+
Examples
|
|
713
|
+
--------
|
|
714
|
+
>>> trained.info()
|
|
715
|
+
"""
|
|
716
|
+
m = self.explain()
|
|
717
|
+
print("=" * 60)
|
|
718
|
+
print(f" Classifier : {self._name} ({self._mode})")
|
|
719
|
+
print(f" Settings : {', '.join(f'{k}={v!r}' for k, v in self._params.items())}")
|
|
720
|
+
print(f" Inputs : {self._names}")
|
|
721
|
+
print(f" Samples : {m['trainingSamples']}")
|
|
722
|
+
if self._classes is not None:
|
|
723
|
+
counts = np.bincount(self._target, minlength=len(self._classes))
|
|
724
|
+
print(f" Classes : " + ", ".join(f"{c} ({n})" for c, n in zip(self.classes, counts)))
|
|
725
|
+
print(f" Training accuracy : {self.confusionMatrix().accuracy():.4f} (optimistic; validate separately)")
|
|
726
|
+
else:
|
|
727
|
+
fit = _regression_metrics(self._target, self._estimator.predict(self._X))
|
|
728
|
+
print(f" Training fit: RMSE {fit['rmse']:.4g}, R² {fit['r2']:.4f} (optimistic; validate separately)")
|
|
729
|
+
if "outOfBagErrorEstimate" in m:
|
|
730
|
+
print(f" Out-of-bag error : {m['outOfBagErrorEstimate']:.4f}")
|
|
731
|
+
if "outOfBagR2" in m:
|
|
732
|
+
print(f" Out-of-bag R² : {m['outOfBagR2']:.4f}")
|
|
733
|
+
print(" Importance (%):")
|
|
734
|
+
for name, value in m["importance"].items():
|
|
735
|
+
print(f" {name:<12} {value:6.2f} " + "#" * int(round(value / 2)))
|
|
736
|
+
print("=" * 60)
|
|
737
|
+
return m
|
|
738
|
+
|
|
739
|
+
def plotImportance(self, save_chart=False, dpi=200):
|
|
740
|
+
"""Draws a bar chart of the importance of each input (see ``importance()``).
|
|
741
|
+
|
|
742
|
+
Parameters
|
|
743
|
+
----------
|
|
744
|
+
save_chart : bool, default False
|
|
745
|
+
Also save the chart as a PNG named "importance_<epoch time>.png".
|
|
746
|
+
dpi : int, default 200
|
|
747
|
+
Resolution of the saved PNG.
|
|
748
|
+
|
|
749
|
+
Returns
|
|
750
|
+
-------
|
|
751
|
+
str or None
|
|
752
|
+
The path of the saved PNG, when `save_chart` is True.
|
|
753
|
+
|
|
754
|
+
Examples
|
|
755
|
+
--------
|
|
756
|
+
>>> trained.plotImportance()
|
|
757
|
+
>>> trained.plotImportance(save_chart=True, dpi=300)
|
|
758
|
+
"""
|
|
759
|
+
import time
|
|
760
|
+
import matplotlib.pyplot as plt
|
|
761
|
+
values = self.importance().iloc[::-1]
|
|
762
|
+
fig, ax = plt.subplots(figsize=(6.5, max(2.5, 0.38 * len(values) + 1.2)))
|
|
763
|
+
ax.barh(values.index, values.values, color="#3b7dd8")
|
|
764
|
+
for y, v in enumerate(values.values):
|
|
765
|
+
ax.text(v, y, f" {v:.1f}", va="center", fontsize=8)
|
|
766
|
+
ax.set_xlabel("importance (%)")
|
|
767
|
+
ax.set_title(f"{self._name}: input importance")
|
|
768
|
+
ax.set_xlim(0, max(values.max() * 1.15, 1))
|
|
769
|
+
ax.spines[["top", "right"]].set_visible(False)
|
|
770
|
+
fig.tight_layout()
|
|
771
|
+
path = None
|
|
772
|
+
if save_chart:
|
|
773
|
+
path = os.path.abspath(f"importance_{int(time.time())}.png")
|
|
774
|
+
fig.savefig(path, dpi=dpi, bbox_inches="tight")
|
|
775
|
+
print(f"Chart saved: {path} ({dpi} dpi)")
|
|
776
|
+
plt.show()
|
|
777
|
+
return path
|
|
778
|
+
|
|
779
|
+
# ---- applying it (used by Image.classify and Vector.classify) ------ #
|
|
780
|
+
|
|
781
|
+
@property
|
|
782
|
+
def _integer_output(self):
|
|
783
|
+
"""True when the output is whole-number class values (so images can be saved as integers)."""
|
|
784
|
+
return (self._mode == "CLASSIFICATION" and self._classes is not None
|
|
785
|
+
and np.issubdtype(self._classes.dtype, np.integer))
|
|
786
|
+
|
|
787
|
+
def _output_names(self, outputName):
|
|
788
|
+
if self._mode == "MULTIPROBABILITY":
|
|
789
|
+
return [f"{outputName}_{c}" for c in self.classes]
|
|
790
|
+
return [outputName]
|
|
791
|
+
|
|
792
|
+
def _set_threads(self, n):
|
|
793
|
+
"""Use all cores when called from the main thread, one per worker thread otherwise
|
|
794
|
+
(the image engine already runs one worker per core)."""
|
|
795
|
+
if self._threads == n:
|
|
796
|
+
return
|
|
797
|
+
with self._lock:
|
|
798
|
+
if self._threads == n:
|
|
799
|
+
return
|
|
800
|
+
est = self._estimator
|
|
801
|
+
if self._name == "xgboost":
|
|
802
|
+
est.get_booster().set_param({"nthread": n})
|
|
803
|
+
elif hasattr(est, "n_jobs"):
|
|
804
|
+
est.n_jobs = n
|
|
805
|
+
self._threads = n
|
|
806
|
+
|
|
807
|
+
def _run(self, method, X):
|
|
808
|
+
main = threading.current_thread() is threading.main_thread()
|
|
809
|
+
self._set_threads((os.cpu_count() or 1) if main else 1)
|
|
810
|
+
return getattr(self._estimator, method)(X)
|
|
811
|
+
|
|
812
|
+
def _predict_index(self, X):
|
|
813
|
+
return np.asarray(self._run("predict", X)).astype("int64").reshape(-1)
|
|
814
|
+
|
|
815
|
+
def _predict(self, X):
|
|
816
|
+
"""Raw input values (rows, inputs) -> {"": values} or per-class probabilities, as numpy arrays."""
|
|
817
|
+
if self._mode == "REGRESSION":
|
|
818
|
+
return [np.asarray(self._run("predict", X), dtype="float64").reshape(-1)]
|
|
819
|
+
if self._mode == "CLASSIFICATION":
|
|
820
|
+
return [self._classes[self._predict_index(X)]]
|
|
821
|
+
proba = np.asarray(self._run("predict_proba", X), dtype="float64")
|
|
822
|
+
if self._mode == "PROBABILITY":
|
|
823
|
+
return [proba.max(axis=1)]
|
|
824
|
+
return [proba[:, i] for i in range(proba.shape[1])]
|
|
825
|
+
|
|
826
|
+
def _apply(self, X):
|
|
827
|
+
"""For the raster engine: (rows, inputs) -> (rows, outputs) float32."""
|
|
828
|
+
n_out = len(self._classes) if self._mode == "MULTIPROBABILITY" else 1
|
|
829
|
+
if len(X) == 0:
|
|
830
|
+
return np.empty((0, n_out), dtype="float32")
|
|
831
|
+
return np.stack([np.asarray(v, dtype="float32") for v in self._predict(X)], axis=1)
|
|
832
|
+
|
|
833
|
+
def __getstate__(self): # allow pickling (the lock can't be pickled)
|
|
834
|
+
state = dict(self.__dict__)
|
|
835
|
+
state["_lock"] = None
|
|
836
|
+
state["_threads"] = None
|
|
837
|
+
return state
|
|
838
|
+
|
|
839
|
+
def __setstate__(self, state):
|
|
840
|
+
self.__dict__.update(state)
|
|
841
|
+
self._lock = threading.Lock()
|
|
842
|
+
|
|
843
|
+
def __repr__(self):
|
|
844
|
+
what = f"{len(self._classes)} classes {self.classes}" if self._classes is not None else "regression"
|
|
845
|
+
return f"TrainedClassifier {self._name} ({self._mode}): {what} from {self._names}"
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
# ====================================================================== #
|
|
849
|
+
# The methods
|
|
850
|
+
# ====================================================================== #
|
|
851
|
+
|
|
852
|
+
def randomForest(numberOfTrees=100, variablesPerSplit=None, minLeafPopulation=1, bagFraction=None,
|
|
853
|
+
maxNodes=None, seed=0):
|
|
854
|
+
"""Creates a random forest classifier (scikit-learn's RandomForest).
|
|
855
|
+
|
|
856
|
+
Many decision trees, each trained on a random part of the samples and
|
|
857
|
+
choosing among a random few inputs at every split; the trees vote on the
|
|
858
|
+
class (or their values are averaged, in "REGRESSION" mode). Robust,
|
|
859
|
+
needs little tuning, and a good first choice for land-cover mapping.
|
|
860
|
+
|
|
861
|
+
Parameters
|
|
862
|
+
----------
|
|
863
|
+
numberOfTrees : int, default 100
|
|
864
|
+
Number of trees. More trees are steadier but slower.
|
|
865
|
+
variablesPerSplit : int, optional
|
|
866
|
+
Inputs considered at each split. Default: the square root of the
|
|
867
|
+
number of inputs (a third of them for regression).
|
|
868
|
+
minLeafPopulation : int, default 1
|
|
869
|
+
Smallest number of training samples in a leaf. Larger values make
|
|
870
|
+
smoother, less detailed trees.
|
|
871
|
+
bagFraction : float, optional
|
|
872
|
+
Share of the training samples (0 to 1) drawn for each tree.
|
|
873
|
+
Default: as many as there are samples (drawn with replacement).
|
|
874
|
+
maxNodes : int, optional
|
|
875
|
+
Maximum number of leaves per tree. Default: no limit.
|
|
876
|
+
seed : int, default 0
|
|
877
|
+
Random seed (same seed = same forest).
|
|
878
|
+
|
|
879
|
+
Returns
|
|
880
|
+
-------
|
|
881
|
+
Classifier
|
|
882
|
+
|
|
883
|
+
Examples
|
|
884
|
+
--------
|
|
885
|
+
>>> trained = classifier.randomForest(100).train(training, "landcover", bands)
|
|
886
|
+
>>> classified = img.classify(trained)
|
|
887
|
+
>>> classifier.randomForest(200, minLeafPopulation=2, bagFraction=0.5)
|
|
888
|
+
"""
|
|
889
|
+
trees = _check_count(numberOfTrees, "numberOfTrees")
|
|
890
|
+
per_split = _check_count(variablesPerSplit, "variablesPerSplit", allow_none=True)
|
|
891
|
+
leaf = _check_count(minLeafPopulation, "minLeafPopulation")
|
|
892
|
+
bag = _check_fraction(bagFraction, "bagFraction")
|
|
893
|
+
nodes = _check_count(maxNodes, "maxNodes", minimum=2, allow_none=True)
|
|
894
|
+
|
|
895
|
+
def build(task, mode, _seed):
|
|
896
|
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
|
897
|
+
common = dict(n_estimators=trees, min_samples_leaf=leaf, max_samples=bag, max_leaf_nodes=nodes,
|
|
898
|
+
oob_score=True, n_jobs=-1, random_state=seed)
|
|
899
|
+
if task == "regression":
|
|
900
|
+
return RandomForestRegressor(max_features=per_split or 1 / 3, **common)
|
|
901
|
+
return RandomForestClassifier(max_features=per_split or "sqrt", **common)
|
|
902
|
+
return Classifier("randomForest", {"numberOfTrees": trees, "variablesPerSplit": per_split,
|
|
903
|
+
"minLeafPopulation": leaf, "bagFraction": bag, "maxNodes": nodes,
|
|
904
|
+
"seed": seed}, build)
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def xgboost(numberOfTrees=100, learningRate=0.3, maxDepth=6, subsample=1.0, colsampleByTree=1.0,
|
|
908
|
+
minChildWeight=1.0, regLambda=1.0, regAlpha=0.0, seed=0):
|
|
909
|
+
"""Creates an XGBoost (extreme gradient boosting) classifier.
|
|
910
|
+
|
|
911
|
+
Builds trees one after another, each correcting the mistakes of the
|
|
912
|
+
trees before it. Often the most accurate method, especially with many
|
|
913
|
+
training samples; it has more settings to tune than a random forest.
|
|
914
|
+
Needs the xgboost package: ``pip install xgboost``.
|
|
915
|
+
|
|
916
|
+
Parameters
|
|
917
|
+
----------
|
|
918
|
+
numberOfTrees : int, default 100
|
|
919
|
+
Number of boosting rounds (trees).
|
|
920
|
+
learningRate : float, default 0.3
|
|
921
|
+
How much each tree contributes (0 to 1). Smaller values need more
|
|
922
|
+
trees but usually generalize better (e.g. 0.05 with 500 trees).
|
|
923
|
+
maxDepth : int, default 6
|
|
924
|
+
Maximum depth of each tree.
|
|
925
|
+
subsample : float, default 1.0
|
|
926
|
+
Share of the samples (0 to 1) used for each tree.
|
|
927
|
+
colsampleByTree : float, default 1.0
|
|
928
|
+
Share of the inputs (0 to 1) used for each tree.
|
|
929
|
+
minChildWeight : float, default 1.0
|
|
930
|
+
Minimum weight (about the number of samples) needed in a leaf.
|
|
931
|
+
regLambda, regAlpha : float, default 1.0 and 0.0
|
|
932
|
+
L2 and L1 regularization of the leaf values; larger is more conservative.
|
|
933
|
+
seed : int, default 0
|
|
934
|
+
Random seed.
|
|
935
|
+
|
|
936
|
+
Returns
|
|
937
|
+
-------
|
|
938
|
+
Classifier
|
|
939
|
+
|
|
940
|
+
Raises
|
|
941
|
+
------
|
|
942
|
+
MissingDependencyError
|
|
943
|
+
If xgboost isn't installed.
|
|
944
|
+
|
|
945
|
+
Examples
|
|
946
|
+
--------
|
|
947
|
+
>>> trained = classifier.xgboost(200, learningRate=0.1).train(training, "landcover", bands)
|
|
948
|
+
>>> classified = img.classify(trained)
|
|
949
|
+
>>> classifier.xgboost(300, learningRate=0.05, maxDepth=4, subsample=0.8)
|
|
950
|
+
"""
|
|
951
|
+
import importlib.util
|
|
952
|
+
if importlib.util.find_spec("xgboost") is None:
|
|
953
|
+
raise MissingDependencyError("XGBoost isn't installed. Install it with: pip install xgboost")
|
|
954
|
+
trees = _check_count(numberOfTrees, "numberOfTrees")
|
|
955
|
+
depth = _check_count(maxDepth, "maxDepth")
|
|
956
|
+
rate = _check_fraction(learningRate, "learningRate", allow_none=False)
|
|
957
|
+
sub = _check_fraction(subsample, "subsample", allow_none=False)
|
|
958
|
+
cols = _check_fraction(colsampleByTree, "colsampleByTree", allow_none=False)
|
|
959
|
+
for label, value in (("minChildWeight", minChildWeight), ("regLambda", regLambda), ("regAlpha", regAlpha)):
|
|
960
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
|
|
961
|
+
raise ValueError(f"{label} must be a number of 0 or more, got {value!r}")
|
|
962
|
+
|
|
963
|
+
def build(task, mode, _seed):
|
|
964
|
+
import xgboost as xgb
|
|
965
|
+
common = dict(n_estimators=trees, learning_rate=rate, max_depth=depth, subsample=sub,
|
|
966
|
+
colsample_bytree=cols, min_child_weight=minChildWeight, reg_lambda=regLambda,
|
|
967
|
+
reg_alpha=regAlpha, tree_method="hist", n_jobs=os.cpu_count() or 1, random_state=seed)
|
|
968
|
+
if task == "regression":
|
|
969
|
+
return xgb.XGBRegressor(**common)
|
|
970
|
+
return xgb.XGBClassifier(**common)
|
|
971
|
+
return Classifier("xgboost", {"numberOfTrees": trees, "learningRate": rate, "maxDepth": depth,
|
|
972
|
+
"subsample": sub, "colsampleByTree": cols, "minChildWeight": minChildWeight,
|
|
973
|
+
"regLambda": regLambda, "regAlpha": regAlpha, "seed": seed}, build)
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def gradientTreeBoost(numberOfTrees=100, shrinkage=0.1, maxNodes=31, maxDepth=None, minLeafPopulation=20,
|
|
977
|
+
seed=0):
|
|
978
|
+
"""Creates a gradient tree boosting classifier (scikit-learn's histogram gradient boosting).
|
|
979
|
+
|
|
980
|
+
Like xgboost (trees built one after another, each fixing the previous
|
|
981
|
+
ones' mistakes) but with no extra package to install. Fast on large
|
|
982
|
+
training sets.
|
|
983
|
+
|
|
984
|
+
Parameters
|
|
985
|
+
----------
|
|
986
|
+
numberOfTrees : int, default 100
|
|
987
|
+
Number of boosting rounds (trees per class).
|
|
988
|
+
shrinkage : float, default 0.1
|
|
989
|
+
Learning rate (0 to 1): how much each tree contributes.
|
|
990
|
+
maxNodes : int, default 31
|
|
991
|
+
Maximum number of leaves per tree.
|
|
992
|
+
maxDepth : int, optional
|
|
993
|
+
Maximum depth of each tree. Default: no limit (maxNodes limits size).
|
|
994
|
+
minLeafPopulation : int, default 20
|
|
995
|
+
Smallest number of training samples in a leaf.
|
|
996
|
+
seed : int, default 0
|
|
997
|
+
Random seed.
|
|
998
|
+
|
|
999
|
+
Returns
|
|
1000
|
+
-------
|
|
1001
|
+
Classifier
|
|
1002
|
+
|
|
1003
|
+
Examples
|
|
1004
|
+
--------
|
|
1005
|
+
>>> trained = classifier.gradientTreeBoost(200).train(training, "landcover", bands)
|
|
1006
|
+
>>> classifier.gradientTreeBoost(300, shrinkage=0.05).setOutputMode("REGRESSION")
|
|
1007
|
+
"""
|
|
1008
|
+
trees = _check_count(numberOfTrees, "numberOfTrees")
|
|
1009
|
+
rate = _check_fraction(shrinkage, "shrinkage", allow_none=False)
|
|
1010
|
+
nodes = _check_count(maxNodes, "maxNodes", minimum=2)
|
|
1011
|
+
depth = _check_count(maxDepth, "maxDepth", allow_none=True)
|
|
1012
|
+
leaf = _check_count(minLeafPopulation, "minLeafPopulation")
|
|
1013
|
+
|
|
1014
|
+
def build(task, mode, _seed):
|
|
1015
|
+
from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor
|
|
1016
|
+
common = dict(max_iter=trees, learning_rate=rate, max_leaf_nodes=nodes, max_depth=depth,
|
|
1017
|
+
min_samples_leaf=leaf, early_stopping=False, random_state=seed)
|
|
1018
|
+
if task == "regression":
|
|
1019
|
+
return HistGradientBoostingRegressor(**common)
|
|
1020
|
+
return HistGradientBoostingClassifier(**common)
|
|
1021
|
+
return Classifier("gradientTreeBoost", {"numberOfTrees": trees, "shrinkage": rate, "maxNodes": nodes,
|
|
1022
|
+
"maxDepth": depth, "minLeafPopulation": leaf, "seed": seed}, build)
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
def cart(maxNodes=None, minLeafPopulation=1, maxDepth=None, seed=0):
|
|
1026
|
+
"""Creates a CART (classification and regression tree) classifier: a single decision tree.
|
|
1027
|
+
|
|
1028
|
+
Easy to understand and very fast, but less accurate than a forest of
|
|
1029
|
+
trees (randomForest). Useful as a quick baseline.
|
|
1030
|
+
|
|
1031
|
+
Parameters
|
|
1032
|
+
----------
|
|
1033
|
+
maxNodes : int, optional
|
|
1034
|
+
Maximum number of leaves. Default: no limit.
|
|
1035
|
+
minLeafPopulation : int, default 1
|
|
1036
|
+
Smallest number of training samples in a leaf.
|
|
1037
|
+
maxDepth : int, optional
|
|
1038
|
+
Maximum depth of the tree. Default: no limit.
|
|
1039
|
+
seed : int, default 0
|
|
1040
|
+
Random seed (breaks ties between equally good splits).
|
|
1041
|
+
|
|
1042
|
+
Returns
|
|
1043
|
+
-------
|
|
1044
|
+
Classifier
|
|
1045
|
+
|
|
1046
|
+
Examples
|
|
1047
|
+
--------
|
|
1048
|
+
>>> trained = classifier.cart(maxDepth=8).train(training, "landcover", bands)
|
|
1049
|
+
"""
|
|
1050
|
+
nodes = _check_count(maxNodes, "maxNodes", minimum=2, allow_none=True)
|
|
1051
|
+
leaf = _check_count(minLeafPopulation, "minLeafPopulation")
|
|
1052
|
+
depth = _check_count(maxDepth, "maxDepth", allow_none=True)
|
|
1053
|
+
|
|
1054
|
+
def build(task, mode, _seed):
|
|
1055
|
+
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
|
|
1056
|
+
common = dict(max_leaf_nodes=nodes, min_samples_leaf=leaf, max_depth=depth, random_state=seed)
|
|
1057
|
+
return DecisionTreeRegressor(**common) if task == "regression" else DecisionTreeClassifier(**common)
|
|
1058
|
+
return Classifier("cart", {"maxNodes": nodes, "minLeafPopulation": leaf, "maxDepth": depth,
|
|
1059
|
+
"seed": seed}, build)
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def svm(kernelType="RBF", cost=1.0, gamma=None, degree=3, normalize=True):
|
|
1063
|
+
"""Creates a support vector machine (SVM) classifier (scikit-learn's SVC / SVR, based on LIBSVM).
|
|
1064
|
+
|
|
1065
|
+
Finds the boundaries that separate the classes with the widest margin.
|
|
1066
|
+
Works well with few training samples; slow to train on many thousands.
|
|
1067
|
+
Inputs are scaled to zero mean and unit variance by default, which SVMs need.
|
|
1068
|
+
|
|
1069
|
+
Parameters
|
|
1070
|
+
----------
|
|
1071
|
+
kernelType : str, default "RBF"
|
|
1072
|
+
"LINEAR", "POLY", "RBF" (radial basis function) or "SIGMOID".
|
|
1073
|
+
cost : float, default 1.0
|
|
1074
|
+
Penalty for misclassified training samples (C). Larger values fit the
|
|
1075
|
+
training data more closely.
|
|
1076
|
+
gamma : float, optional
|
|
1077
|
+
Kernel width for "RBF", "POLY" and "SIGMOID". Default: 1 / (inputs x variance).
|
|
1078
|
+
degree : int, default 3
|
|
1079
|
+
Degree of the "POLY" kernel.
|
|
1080
|
+
normalize : bool, default True
|
|
1081
|
+
Scale every input to zero mean and unit variance first.
|
|
1082
|
+
|
|
1083
|
+
Returns
|
|
1084
|
+
-------
|
|
1085
|
+
Classifier
|
|
1086
|
+
|
|
1087
|
+
Examples
|
|
1088
|
+
--------
|
|
1089
|
+
>>> trained = classifier.svm(cost=10).train(training, "landcover", bands)
|
|
1090
|
+
>>> classifier.svm("LINEAR", cost=0.5)
|
|
1091
|
+
"""
|
|
1092
|
+
if not isinstance(kernelType, str) or kernelType.upper() not in _KERNELS:
|
|
1093
|
+
raise ValueError(f"kernelType must be one of {list(_KERNELS)}, got {kernelType!r}")
|
|
1094
|
+
kernel = _KERNELS[kernelType.upper()]
|
|
1095
|
+
if isinstance(cost, bool) or not isinstance(cost, (int, float)) or cost <= 0:
|
|
1096
|
+
raise ValueError(f"cost must be a positive number, got {cost!r}")
|
|
1097
|
+
if gamma is not None and (isinstance(gamma, bool) or not isinstance(gamma, (int, float)) or gamma <= 0):
|
|
1098
|
+
raise ValueError(f"gamma must be a positive number, got {gamma!r}")
|
|
1099
|
+
deg = _check_count(degree, "degree")
|
|
1100
|
+
|
|
1101
|
+
def build(task, mode, seed):
|
|
1102
|
+
from sklearn.pipeline import make_pipeline
|
|
1103
|
+
from sklearn.preprocessing import StandardScaler
|
|
1104
|
+
from sklearn.svm import SVC, SVR
|
|
1105
|
+
common = dict(kernel=kernel, C=cost, gamma=gamma if gamma is not None else "scale", degree=deg)
|
|
1106
|
+
if task == "regression":
|
|
1107
|
+
model = SVR(**common)
|
|
1108
|
+
else:
|
|
1109
|
+
model = SVC(probability=mode in ("PROBABILITY", "MULTIPROBABILITY"), random_state=seed, **common)
|
|
1110
|
+
return make_pipeline(StandardScaler(), model) if normalize else model
|
|
1111
|
+
return Classifier("svm", {"kernelType": kernelType.upper(), "cost": cost, "gamma": gamma, "degree": deg,
|
|
1112
|
+
"normalize": normalize}, build)
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def naiveBayes(smoothing=1e-9):
|
|
1116
|
+
"""Creates a Gaussian naive Bayes classifier.
|
|
1117
|
+
|
|
1118
|
+
Treats each input as a bell curve per class and picks the most likely
|
|
1119
|
+
class. Very fast and needs few samples, but assumes the inputs are
|
|
1120
|
+
independent, so it is usually less accurate than tree methods.
|
|
1121
|
+
Classification only (no regression).
|
|
1122
|
+
|
|
1123
|
+
Parameters
|
|
1124
|
+
----------
|
|
1125
|
+
smoothing : float, default 1e-9
|
|
1126
|
+
Share of the largest input variance added to all variances, for stability.
|
|
1127
|
+
|
|
1128
|
+
Returns
|
|
1129
|
+
-------
|
|
1130
|
+
Classifier
|
|
1131
|
+
|
|
1132
|
+
Examples
|
|
1133
|
+
--------
|
|
1134
|
+
>>> trained = classifier.naiveBayes().train(training, "landcover", bands)
|
|
1135
|
+
"""
|
|
1136
|
+
if isinstance(smoothing, bool) or not isinstance(smoothing, (int, float)) or smoothing < 0:
|
|
1137
|
+
raise ValueError(f"smoothing must be a number of 0 or more, got {smoothing!r}")
|
|
1138
|
+
|
|
1139
|
+
def build(task, mode, seed):
|
|
1140
|
+
from sklearn.naive_bayes import GaussianNB
|
|
1141
|
+
return GaussianNB(var_smoothing=smoothing)
|
|
1142
|
+
return Classifier("naiveBayes", {"smoothing": smoothing}, build, regression=False)
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
# ---- short, clean tracebacks for every public entry point ----
|
|
1146
|
+
clean_class(Classifier)
|
|
1147
|
+
clean_class(TrainedClassifier)
|
|
1148
|
+
clean_class(ConfusionMatrix)
|
|
1149
|
+
randomForest = clean_errors(randomForest)
|
|
1150
|
+
xgboost = clean_errors(xgboost)
|
|
1151
|
+
gradientTreeBoost = clean_errors(gradientTreeBoost)
|
|
1152
|
+
cart = clean_errors(cart)
|
|
1153
|
+
svm = clean_errors(svm)
|
|
1154
|
+
naiveBayes = clean_errors(naiveBayes)
|