Classification API¶
Classify pixels¶
obia.classification.classify_pixels(image, points, *, bands=None, label_column='class', method='rf', mask=None, invalid_samples='raise', test_size=0.2, compute_reports=False, scale_features='auto', split_random_state=42, stratify=True, split=None, batch_size=65536, return_probabilities=False, **kwargs)
¶
Learn from labelled point pixels and classify the raster directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Loaded raster. Source values are used without normalization. |
required |
points
|
GeoDataFrame
|
Labelled Point GeoDataFrame; see sample_pixels for sampling rules. |
required |
bands
|
Sequence[int] | None
|
Ordered zero-based band indices; None selects all loaded bands. |
None
|
label_column
|
str
|
Point attribute containing string or numeric class labels. |
'class'
|
method
|
str | BaseEstimator
|
Any CLASSIFICATION_METHODS name or compatible classifier/pipeline. |
'rf'
|
mask
|
ndarray | None
|
Boolean inclusion mask applied to both sampling and prediction. |
None
|
invalid_samples
|
Literal['raise', 'drop']
|
"raise" or "drop" for outside or invalid point pixels. |
'raise'
|
test_size
|
float | int | None
|
Random sample holdout fraction/count; None fits all samples. |
0.2
|
compute_reports
|
bool
|
Calculate holdout metrics; requires test samples. |
False
|
scale_features
|
bool | Literal['auto']
|
"auto", True, or False, as in object classification. Preprocessing is fitted only on training samples. |
'auto'
|
split_random_state
|
int | None
|
Random holdout seed, independent of model parameters. |
42
|
stratify
|
bool
|
Preserve class coverage in the default random holdout. |
True
|
split
|
ObjectSplit | None
|
Reusable split created from sample_pixels with the same settings. Overrides test_size, split_random_state, and stratify. Spatial, grouped, explicit, and cross-validation partitions are supported. |
None
|
batch_size
|
int
|
Maximum number of pixels processed per prediction batch. |
65536
|
return_probabilities
|
bool
|
Retain the full probability array when available. |
False
|
**kwargs
|
Any
|
Estimator constructor parameters or pipeline parameter overrides. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
ClassifiedRaster |
ClassifiedRaster
|
Class codes, original labels, fitted model, sampling diagnostics, optional holdout reports, and raster georeferencing. Invalid pixels have code 0. Prediction batches limit temporary feature memory; the source and output rasters remain in memory. |
Source code in obia/classification/pixels.py
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 | |
Sample labelled pixels¶
obia.classification.sample_pixels(image, points, *, bands=None, label_column='class', mask=None, invalid_samples='raise')
¶
Read the pixel containing each labelled point, without interpolation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Loaded raster with a CRS and affine transform. |
required |
points
|
GeoDataFrame
|
GeoDataFrame of finite, nonempty Point geometries with a CRS. Points are reprojected to the raster CRS when necessary. |
required |
bands
|
Sequence[int] | None
|
Ordered, zero-based indices into the loaded image; None uses all. |
None
|
label_column
|
str
|
Column containing string or numeric class labels. |
'class'
|
mask
|
ndarray | None
|
Boolean (height, width) inclusion mask, in addition to source masks. |
None
|
invalid_samples
|
Literal['raise', 'drop']
|
Raise for points outside the raster or on excluded, NoData, or nonfinite pixels. "drop" explicitly discards these points. |
'raise'
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
gpd.GeoDataFrame: One row per sampled pixel, with |
Source code in obia/classification/pixels.py
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 | |
Raster results¶
obia.classification.ClassifiedRaster
dataclass
¶
Pixel predictions, georeferencing, and the fitted classifier.
Attributes:
| Name | Type | Description |
|---|---|---|
classified |
ndarray
|
uint32 array (height, width). Codes 1..K follow |
crs |
Any
|
Raster coordinate reference system. |
transform |
Affine
|
Raster affine transform. |
model |
BaseEstimator
|
Fitted pipeline accepting columns named |
bands |
tuple[int, ...]
|
Ordered zero-based indices used for learning and prediction. |
classes |
ndarray
|
Original class labels, in code and probability-column order. |
params |
dict
|
Estimator parameters. |
prediction_margin |
ndarray
|
Top-two probability gap, or NaN for invalid pixels, one-class models, or estimators without probabilities. |
probabilities |
ndarray | None
|
Optional float32 (height, width, classes) array; invalid pixels are NaN. None when not requested or unavailable. |
samples |
GeoDataFrame | None
|
Sampled training/holdout table, or None on prediction-only results. |
split |
ObjectSplit | None
|
Sample partition used for fitting, or None on prediction-only results. |
confusion_matrix |
ndarray | None
|
Holdout matrix in class order, when requested. |
report |
str | None
|
Holdout classification report, when requested. |
Source code in obia/classification/pixels.py
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 | |
class_mapping
property
¶
Map positive raster codes to original class labels; 0 is NoData.
feature_columns
property
¶
Column order expected by the fitted model.
valid_mask
property
¶
Pixels with predictions.
predict(image, *, mask=None, batch_size=65536, return_probabilities=False)
¶
Predict another raster with the same band positions, without refitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Raster with matching band meanings, order, and value units. Its size, transform, and CRS may differ from the training raster. |
required |
mask
|
ndarray | None
|
Optional boolean (height, width) inclusion mask. |
None
|
batch_size
|
int
|
Maximum number of pixels processed per prediction batch. |
65536
|
return_probabilities
|
bool
|
Retain a full probability array when supported. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ClassifiedRaster |
ClassifiedRaster
|
Predictions on the new grid. Training samples, split, and holdout reports are not copied into this result. |
Source code in obia/classification/pixels.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
write_geotiff(output_path)
¶
Save uint32 class codes with CRS, transform, NoData=0, and label mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str
|
Destination GeoTIFF. An existing file is replaced. |
required |
The class_mapping dataset tag contains a JSON mapping of raster
codes to original labels. The band_indices tag records model inputs.
Source code in obia/classification/pixels.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
See pixel classification for sampling rules, class codes, raster exports, and prediction on another image.
Classify Objects¶
obia.classification.classify
¶
Train object classifiers and retain geospatial attributes in their predictions.
ClassifiedImage
¶
Classification output and its fitted, reusable preprocessing/model pipeline.
Attributes:
| Name | Type | Description |
|---|---|---|
classified |
Copy of the input segments with predictions and probability margins. |
|
model |
Fitted scikit-learn pipeline; accepts the selected feature columns. |
|
feature_columns |
Ordered feature names used for fitting and prediction. |
|
classes |
Class labels in probability-column and confusion-matrix order. |
|
probabilities |
Class probabilities indexed like the segments, or None. |
|
margin_kind |
|
|
confusion_matrix |
Held-out confusion matrix, or None. |
|
report |
Held-out classification report, or None. |
|
params |
Classifier parameters, excluding OBIA preprocessing options. |
|
shap_values |
SHAP values for training features, or None. |
|
split |
ObjectSplit with positional training/test/excluded assignments and class counts. |
Source code in obia/classification/classify.py
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 | |
write_geotiff(output_path)
¶
Write raster-valued classified data; polygon outputs must be rasterized first.
Source code in obia/classification/classify.py
60 61 62 | |
classify(segments, training_classes, acceptable_classes_gdf=None, method='rf', test_size=0.2, compute_reports=False, compute_shap=False, sample_shap=False, *, feature_columns=None, scale_features='auto', split_random_state=42, stratify=True, split=None, **kwargs)
¶
Fit a classifier on labelled objects and predict classes for segment polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segments
|
GeoDataFrame
|
Segment GeoDataFrame. The input is not modified. |
required |
training_classes
|
DataFrame
|
Table with numeric features and a |
required |
acceptable_classes_gdf
|
GeoDataFrame | None
|
Optional polygons with lists of allowed class labels. Requires probabilities; overlapping polygons intersect their allowed sets. |
None
|
method
|
str | BaseEstimator
|
Name in |
'rf'
|
test_size
|
float | int | None
|
Random holdout fraction or count; None trains on all labelled objects. Used only when split is None. |
0.2
|
compute_reports
|
bool
|
Report held-out performance; requires a test split. |
False
|
compute_shap
|
bool
|
Calculate SHAP explanations (requires the |
False
|
sample_shap
|
bool
|
Limit SHAP background and explained training rows to 500. |
False
|
feature_columns
|
Sequence[str] | None
|
Ordered feature names. Default selects numeric training columns, excluding IDs, labels, and previous prediction columns. |
None
|
scale_features
|
bool | Literal['auto']
|
|
'auto'
|
split_random_state
|
int | None
|
Seed for the holdout split, independent of estimator parameters. |
42
|
stratify
|
bool
|
Preserve class proportions in the holdout split (default True). |
True
|
split
|
ObjectSplit | None
|
Optional ObjectSplit from split_objects/cross_validation_splits. Reuses exactly that partition, including buffer exclusions, instead of test_size, split_random_state, and stratify. Named group columns are excluded from predictors. Reports require a nonempty test subset. |
None
|
**kwargs
|
Any
|
Estimator parameters, including nested parameters for supplied pipelines. |
{}
|
Returns:
| Type | Description |
|---|---|
ClassifiedImage
|
Object table, fitted model, feature order, probabilities, optional holdout |
ClassifiedImage
|
reports, and optional SHAP values. Probability margins are NaN for |
ClassifiedImage
|
estimators without probabilities or fewer than two allowed classes. |
Source code in obia/classification/classify.py
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 | |
Results¶
obia.classification.ClassifiedImage
¶
Classification output and its fitted, reusable preprocessing/model pipeline.
Attributes:
| Name | Type | Description |
|---|---|---|
classified |
Copy of the input segments with predictions and probability margins. |
|
model |
Fitted scikit-learn pipeline; accepts the selected feature columns. |
|
feature_columns |
Ordered feature names used for fitting and prediction. |
|
classes |
Class labels in probability-column and confusion-matrix order. |
|
probabilities |
Class probabilities indexed like the segments, or None. |
|
margin_kind |
|
|
confusion_matrix |
Held-out confusion matrix, or None. |
|
report |
Held-out classification report, or None. |
|
params |
Classifier parameters, excluding OBIA preprocessing options. |
|
shap_values |
SHAP values for training features, or None. |
|
split |
ObjectSplit with positional training/test/excluded assignments and class counts. |
Source code in obia/classification/classify.py
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 | |
write_geotiff(output_path)
¶
Write raster-valued classified data; polygon outputs must be rasterized first.
Source code in obia/classification/classify.py
60 61 62 | |
Holdout Splits¶
obia.classification.split_objects(data, *, method='random', test_size=0.2, random_state=42, stratify=True, groups=None, block_size=None, block_origin=(0.0, 0.0), buffer_distance=0.0, train_indices=None, test_indices=None, n_candidates=128)
¶
Create a random, grouped, spatial, or explicitly assigned object holdout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Labelled DataFrame/GeoDataFrame with |
required |
method
|
Literal['random', 'grouped', 'spatial', 'explicit']
|
|
'random'
|
test_size
|
float | int | None
|
Fraction or integer count of rows for random splits, or of groups/occupied blocks for grouped/spatial splits. None fits all rows. Ignored for explicit partitions, whose indices determine their size. |
0.2
|
random_state
|
int | None
|
Seed for reproducible holdout selection. |
42
|
stratify
|
bool
|
Random splits use class stratification. Grouped/spatial splits search candidate group partitions for approximate class balance with all classes in both subsets. Explicit splits retain supplied subsets and check test-class coverage when True. Training always needs all classes. |
True
|
groups
|
str | Sequence[Hashable] | Series | ndarray | None
|
Group column name or row-ordered labels; required for grouped splits and optional for enforcing group separation in explicit splits. A named group column is excluded from classifier features. |
None
|
block_size
|
float | None
|
Positive square-grid width in projected CRS units, required for spatial splits. Each object's representative point selects its block, and the entire object stays in that block. |
None
|
block_origin
|
tuple[float, float]
|
Fixed grid origin (x, y), default (0, 0). |
(0.0, 0.0)
|
buffer_distance
|
float
|
Exclude training geometries at distance <= this value from any test geometry. Zero disables buffering. If groups/blocks are used, exclude the entire affected training group/block. |
0.0
|
train_indices
|
ArrayLike | None
|
Explicit zero-based row positions or a boolean mask. |
None
|
test_indices
|
ArrayLike | None
|
Explicit zero-based row positions or a boolean mask. Rows in neither subset are marked excluded. |
None
|
n_candidates
|
int
|
Number of random group partitions considered for stratified grouped/spatial holdouts. The search is approximate and can fail even if a feasible partition exists; increase this or supply explicit indices. |
128
|
Returns:
| Name | Type | Description |
|---|---|---|
ObjectSplit |
ObjectSplit
|
Reusable indices, map-ready assignments, and class counts. Positive buffers can reduce training size and alter class balance. |
Source code in obia/classification/splitting.py
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 | |
Cross-Validation Folds¶
obia.classification.cross_validation_splits(data, *, method='random', n_splits=5, random_state=42, stratify=True, groups=None, block_size=None, block_origin=(0.0, 0.0), buffer_distance=0.0)
¶
Create reusable random, grouped, or spatial cross-validation folds.
Each object is tested once. Buffers remove training objects separately for
each fold; test objects are never removed. Arguments have the same meaning
as in split_objects. Grouped/spatial stratification uses scikit-learn's
StratifiedGroupKFold and is approximate. Non-stratified group folds use
GroupKFold's deterministic allocation (random_state has no effect there).
All folds require every class in training; stratify=True also requires every class in each test fold. Insufficient class/group coverage raises an error, rather than silently moving objects between groups. Reduce n_splits or change the partition when necessary. No models are fitted by this function.
Returns:
| Type | Description |
|---|---|
list[ObjectSplit]
|
list[ObjectSplit]: Pass each split to |
Source code in obia/classification/splitting.py
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 | |
Split Assignments and Diagnostics¶
obia.classification.ObjectSplit
dataclass
¶
A reusable partition of a labelled object table, created by split helpers.
Attributes:
| Name | Type | Description |
|---|---|---|
train_indices |
ndarray
|
Zero-based row positions for fitting, suitable for |
test_indices |
ndarray
|
Zero-based row positions for evaluation. |
excluded_indices |
ndarray
|
Positions omitted from both subsets, including buffers. |
assignments |
DataFrame
|
Copy of an inspectable table with |
class_counts |
DataFrame
|
Counts of each class in train, test, and excluded subsets. |
metadata |
dict
|
Method, settings, and achieved sample sizes. Distances and grid sizes use projected CRS units, not necessarily metres. |
feature_exclusions |
tuple
|
Grouping column names, excluded from model predictors. |
Indices are positional even when the source index contains duplicates. A split can be reused after changing feature values/columns, but its index, labels, IDs, geometry, CRS, and named group columns must remain unchanged.
Source code in obia/classification/splitting.py
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 | |
as_sklearn()
¶
Return (train_indices, test_indices) for scikit-learn's cv iterable.
Source code in obia/classification/splitting.py
110 111 112 | |
validate_for(data)
¶
Reject reuse on reordered or different objects; feature changes are allowed.
Source code in obia/classification/splitting.py
114 115 116 117 118 119 120 121 | |
See the validation guide for choosing groups, block sizes, and buffers, inspecting assignments, and keeping a final test set separate from model selection.
Create a Classifier¶
obia.classification.create_classifier(method='rf', **kwargs)
¶
Create an unfitted classifier, or clone a supplied estimator or pipeline.
method accepts a name in CLASSIFICATION_METHODS, a scikit-learn
class name (for example "SVC"), or a classifier instance. Keyword
arguments are constructor parameters for named methods and set_params
overrides for instances. XGBoost ships with OBIA and is imported only when
requested. Composite classifiers such as
voting and stacking require their usual estimators argument.
Source code in obia/classification/estimators.py
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 | |
Supported Method Names¶
obia.classification.estimators.CLASSIFICATION_METHODS = tuple(_CLASSIFIERS) + tuple(_XGBOOST_METHODS)
module-attribute
¶
Method names accepted by object and pixel classification and create_classifier.
See the classification guide for the complete estimator table, scaling rules, XGBoost options, and pipeline examples.