Core API¶
This section documents the core components of OKAPI.
Okapi Class¶
The Okapi class is the main entry point for evolutionary model ensemble optimization.
Main class for evolutionary model ensemble optimization.
Okapi uses genetic programming to evolve tree-based ensembles of machine learning models. The algorithm creates a population of trees where each tree represents a different way of combining model predictions. Through evolution (crossover and mutation), it searches for optimal ensemble structures that maximize a fitness function.
Each tree has ValueNodes that contain tensor predictions from individual models, and OperatorNodes that define how to combine these predictions (e.g., mean, min, max, weighted mean). The evolution process selects and combines high-performing trees to produce better ensembles.
Attributes:
| Name | Type | Description |
|---|---|---|
population_size |
Number of individuals in the population |
|
population_multiplier |
Factor determining how many additional trees to generate in each iteration |
|
tournament_size |
Number of trees to consider in tournament selection |
|
fitness_function |
Function used to evaluate the fitness of each tree |
|
callbacks |
Collection of callbacks for monitoring/modifying the evolution process |
|
allowed_ops |
Operator node types allowed in tree construction |
|
train_tensors |
Dictionary mapping model names to their prediction tensors |
|
gt_tensor |
Ground truth tensor for comparison |
|
population |
Current population of trees |
|
additional_population |
List[Tree]
|
Additional trees generated during evolution |
Source code in okapi/okapi.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 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 | |
__init__(preds_source, gt_path, population_size, population_multiplier, tournament_size, minimize_node_count=True, objective_functions=(average_precision_fitness,), objectives=(maximize,), allowed_ops=(MEAN, MIN, MAX, WEIGHTED_MEAN, FAR_THRESHOLD, CLOSE_THRESHOLD), callbacks=tuple(), backend=None, seed=0, postprocessing_function=None)
¶
Initialize the Okapi evolutionary algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preds_source
|
Union[Path, str, Iterable[Path], Iterable[str]]
|
Source of model predictions, can be a path to directory or iterable of paths |
required |
gt_path
|
Union[Path, str, Iterable[Path], Iterable[str]]
|
Path to ground truth data, can be a single path or iterable of paths. Should match preds_source by order |
required |
population_size
|
int
|
Size of the population to evolve |
required |
population_multiplier
|
int
|
Factor determining how many additional trees to generate |
required |
tournament_size
|
int
|
Number of trees to consider in tournament selection |
required |
minimize_node_count
|
bool
|
Whether the pareto frontier models should also consider node count. |
True
|
objective_functions
|
Sequence[Callable[[Tree, Tensor], float]]
|
Functions that calculate the fitnesses that are to be optimized |
(average_precision_fitness,)
|
objectives
|
Sequence[Callable[[float, float], bool]]
|
Functions that copare two fitnesses and return True if first is better than second. Usually maximize or minimize |
(maximize,)
|
allowed_ops
|
Sequence[Type[OperatorNode]]
|
Sequence of operator node types that can be used in trees |
(MEAN, MIN, MAX, WEIGHTED_MEAN, FAR_THRESHOLD, CLOSE_THRESHOLD)
|
callbacks
|
Iterable[Callback]
|
Iterable of callback objects for monitoring/modifying evolution |
tuple()
|
backend
|
Union[str, None]
|
Optional backend implementation for tensor operations |
None
|
seed
|
int
|
Random seed for reproducibility |
0
|
postprocessing_function
|
Function applied after each Op Node. |
None
|
Source code in okapi/okapi.py
run_iteration()
¶
Run a single iteration of the evolutionary algorithm.
This method: 1. Calculates fitness values for the current population 2. Performs tournament selection and crossover to create new trees 3. Applies mutations to some of the new trees 4. Removes duplicate trees from the population
Source code in okapi/okapi.py
train(iterations)
¶
Run the evolutionary algorithm for a specified number of iterations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterations
|
int
|
Number of evolution iterations to run |
required |
Source code in okapi/okapi.py
Tree Class¶
The Tree class represents a computational tree structure for model ensemble composition.
Represents a computational tree structure for model ensemble composition.
The Tree class is a central component in OKAPI, representing a hierarchical structure of nodes that define how different models are combined. Each tree has a ValueNode as its root, and may contain multiple ValueNodes and OperatorNodes arranged in a tree structure.
ValueNodes contain tensor data (model predictions), while OperatorNodes define operations to combine these predictions (such as mean, min, max, weighted mean). The tree's evaluation produces a combined prediction by recursively applying these operations.
Trees can be manipulated through various operations like pruning, appending, and replacing nodes, making them suitable for evolutionary algorithms where trees evolve over generations.
Attributes:
| Name | Type | Description |
|---|---|---|
root |
The root node of the tree (must be a ValueNode) |
|
nodes |
dict[str, list]
|
Dictionary containing lists of all value nodes and operator nodes in the tree |
mutation_chance |
Probability of mutation for this tree during evolution |
Source code in okapi/tree.py
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 | |
evaluation
property
¶
Calculate and return the evaluation of the tree.
The evaluation is the result of recursively applying all operations in the tree, starting from the root node.
Returns:
| Type | Description |
|---|---|
|
The tensor resulting from evaluating the tree |
nodes_count
property
¶
Count the total number of nodes in the tree.
Returns:
| Type | Description |
|---|---|
|
The sum of value nodes and operator nodes |
unique_value_node_ids
property
¶
Get the unique IDs of all value nodes in the tree.
Returns:
| Type | Description |
|---|---|
|
A list of unique IDs from all value nodes |
__repr__()
¶
Get a string representation of the tree.
Returns:
| Type | Description |
|---|---|
|
A string representation formed by concatenating the code of all nodes |
append_after(node, new_node)
¶
Append a new node as a child of an existing node.
The new node must be of a different type than the existing node (i.e., value nodes can only append operator nodes and vice versa).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
The existing node to which the new node will be appended |
required |
new_node
|
Node
|
The new node to append |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the node is not found in the tree or if attempting to append a node of the same type |
Source code in okapi/tree.py
copy()
¶
Create a deep copy of the tree.
Returns:
| Type | Description |
|---|---|
|
A new Tree instance that is a deep copy of the current tree |
Source code in okapi/tree.py
create_tree_from_root(root, mutation_chance=0.1)
staticmethod
¶
Create a new tree with the given root node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
ValueNode
|
The ValueNode to use as the root of the new tree |
required |
mutation_chance
|
Probability of mutation for the new tree |
0.1
|
Returns:
| Type | Description |
|---|---|
|
A new Tree instance |
Source code in okapi/tree.py
get_random_node(nodes_type=None, allow_root=True, allow_leaves=True)
¶
Get a random node from the tree based on specified constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes_type
|
str | None
|
Optional type of nodes to consider ('value_nodes' or 'op_nodes') If None, a random type will be chosen |
None
|
allow_root
|
Whether to allow selecting the root node |
True
|
|
allow_leaves
|
Whether to allow selecting leaf nodes |
True
|
Returns:
| Type | Description |
|---|---|
|
A randomly selected node that satisfies the constraints |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no node satisfying the constraints is found |
Source code in okapi/tree.py
load_tree(architecture_path, preds_directory, tensors=None)
staticmethod
¶
Load a complete tree with tensor values from files.
This method loads a tree architecture and then loads the associated tensor values for each value node from the specified directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
architecture_path
|
Path to the saved tree architecture file |
required | |
preds_directory
|
Directory containing the tensor files |
required | |
tensors
|
Optional dictionary of pre-loaded tensors |
None
|
Returns:
| Type | Description |
|---|---|
Tree
|
A tuple containing: |
dict
|
|
Tuple[Tree, dict]
|
|
Source code in okapi/tree.py
load_tree_architecture(architecture_path)
staticmethod
¶
Load a tree architecture from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
architecture_path
|
Path to the saved tree architecture file |
required |
Returns:
| Type | Description |
|---|---|
Tree
|
The loaded Tree object without tensor values |
Source code in okapi/tree.py
prune_at(node)
¶
Remove a node and its subtree from the tree.
This method removes the specified node and all its descendants from the tree. If the node is the only child of an operator node, that operator node will also be pruned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
The node to prune from the tree |
required |
Returns:
| Type | Description |
|---|---|
Node
|
The pruned node (which is no longer part of the tree). If parent was pruned, the parent will be returned. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the node is not found in the tree or if attempting to prune the root node |
Source code in okapi/tree.py
recalculate()
¶
Force recalculation of the tree evaluation.
This method clears any cached evaluations and triggers a fresh calculation. It also updates the nodes dictionary
Returns:
| Type | Description |
|---|---|
|
The newly calculated evaluation of the tree |
Source code in okapi/tree.py
replace_at(at, replacement)
¶
Replace a node in the tree with another node.
The replacement node must be of the same type as the node being replaced. This operation preserves the parent-child relationships.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at
|
Node
|
The node to be replaced |
required |
replacement
|
Node
|
The new node that will replace the existing node |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Self reference to allow method chaining |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the replacement node is not of the same type as the node being replaced |
Source code in okapi/tree.py
save_tree_architecture(output_path)
¶
Save the tree's architecture to a file.
This method creates a copy of the tree with tensor values removed and saves it to the specified path using pickle serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path where the tree architecture will be saved |
required |
Source code in okapi/tree.py
update_nodes()
¶
Update the internal collections of nodes in the tree.
This method traverses the tree and categorizes all nodes into value nodes and operator nodes,
updating the internal nodes dictionary.