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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
|
"""Genetic Programming in Python, with a scikit-learn inspired API
The :mod:`gplearn.genetic` module implements Genetic Programming. These
are supervised learning methods based on applying evolutionary operations on
computer programs.
"""
# Author: Trevor Stephens <trevorstephens.com>
#
# License: BSD 3 clause
import itertools
from abc import ABCMeta, abstractmethod
from time import time
from warnings import warn
import numpy as np
from joblib import Parallel, delayed
from scipy.stats import rankdata
from sklearn.base import BaseEstimator
from sklearn.base import RegressorMixin, TransformerMixin, ClassifierMixin
from sklearn.exceptions import NotFittedError
from sklearn.utils import compute_sample_weight
from sklearn.utils.validation import check_array, _check_sample_weight
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.multiclass import type_of_target
from ._program import _Program
from .fitness import _fitness_map, _Fitness
from .functions import _function_map, _Function, sig1 as sigmoid
from .utils import _partition_estimators
from .utils import _sklearn_version_ge
from .utils import check_random_state
__all__ = ['SymbolicRegressor', 'SymbolicClassifier', 'SymbolicTransformer']
MAX_INT = np.iinfo(np.int32).max
def _parallel_evolve(n_programs, parents, X, y, sample_weight, seeds, params):
"""Private function used to build a batch of programs within a job."""
n_samples, n_features = X.shape
# Unpack parameters
tournament_size = params['tournament_size']
function_set = params['function_set']
arities = params['arities']
init_depth = params['init_depth']
init_method = params['init_method']
const_range = params['const_range']
metric = params['_metric']
transformer = params['_transformer']
parsimony_coefficient = params['parsimony_coefficient']
method_probs = params['method_probs']
p_point_replace = params['p_point_replace']
max_samples = params['max_samples']
feature_names = params['feature_names']
max_samples = int(max_samples * n_samples)
def _tournament():
"""Find the fittest individual from a sub-population."""
contenders = random_state.randint(0, len(parents), tournament_size)
fitness = [parents[p].fitness_ for p in contenders]
if metric.greater_is_better:
parent_index = contenders[np.argmax(fitness)]
else:
parent_index = contenders[np.argmin(fitness)]
return parents[parent_index], parent_index
# Build programs
programs = []
for i in range(n_programs):
random_state = check_random_state(seeds[i])
if parents is None:
program = None
genome = None
else:
method = random_state.uniform()
parent, parent_index = _tournament()
if method < method_probs[0]:
# crossover
donor, donor_index = _tournament()
program, removed, remains = parent.crossover(donor.program,
random_state)
genome = {'method': 'Crossover',
'parent_idx': parent_index,
'parent_nodes': removed,
'donor_idx': donor_index,
'donor_nodes': remains}
elif method < method_probs[1]:
# subtree_mutation
program, removed, _ = parent.subtree_mutation(random_state)
genome = {'method': 'Subtree Mutation',
'parent_idx': parent_index,
'parent_nodes': removed}
elif method < method_probs[2]:
# hoist_mutation
program, removed = parent.hoist_mutation(random_state)
genome = {'method': 'Hoist Mutation',
'parent_idx': parent_index,
'parent_nodes': removed}
elif method < method_probs[3]:
# point_mutation
program, mutated = parent.point_mutation(random_state)
genome = {'method': 'Point Mutation',
'parent_idx': parent_index,
'parent_nodes': mutated}
else:
# reproduction
program = parent.reproduce()
genome = {'method': 'Reproduction',
'parent_idx': parent_index,
'parent_nodes': []}
program = _Program(function_set=function_set,
arities=arities,
init_depth=init_depth,
init_method=init_method,
n_features=n_features,
metric=metric,
transformer=transformer,
const_range=const_range,
p_point_replace=p_point_replace,
parsimony_coefficient=parsimony_coefficient,
feature_names=feature_names,
random_state=random_state,
program=program)
program.parents = genome
# Draw samples, using sample weights, and then fit
if sample_weight is None:
curr_sample_weight = np.ones((n_samples,))
else:
curr_sample_weight = sample_weight.copy()
oob_sample_weight = curr_sample_weight.copy()
indices, not_indices = program.get_all_indices(n_samples,
max_samples,
random_state)
curr_sample_weight[not_indices] = 0
oob_sample_weight[indices] = 0
program.raw_fitness_ = program.raw_fitness(X, y, curr_sample_weight)
if max_samples < n_samples:
# Calculate OOB fitness
program.oob_fitness_ = program.raw_fitness(X, y, oob_sample_weight)
programs.append(program)
return programs
class BaseSymbolic(BaseEstimator, metaclass=ABCMeta):
"""Base class for symbolic regression / classification estimators.
Warning: This class should not be used directly.
Use derived classes instead.
"""
@abstractmethod
def __init__(self,
*,
population_size=1000,
hall_of_fame=None,
n_components=None,
generations=20,
tournament_size=20,
stopping_criteria=0.0,
const_range=(-1., 1.),
init_depth=(2, 6),
init_method='half and half',
function_set=('add', 'sub', 'mul', 'div'),
transformer=None,
metric='mean absolute error',
parsimony_coefficient=0.001,
p_crossover=0.9,
p_subtree_mutation=0.01,
p_hoist_mutation=0.01,
p_point_mutation=0.01,
p_point_replace=0.05,
max_samples=1.0,
class_weight=None,
feature_names=None,
warm_start=False,
low_memory=False,
n_jobs=1,
verbose=0,
random_state=None):
self.population_size = population_size
self.hall_of_fame = hall_of_fame
self.n_components = n_components
self.generations = generations
self.tournament_size = tournament_size
self.stopping_criteria = stopping_criteria
self.const_range = const_range
self.init_depth = init_depth
self.init_method = init_method
self.function_set = function_set
self.transformer = transformer
self.metric = metric
self.parsimony_coefficient = parsimony_coefficient
self.p_crossover = p_crossover
self.p_subtree_mutation = p_subtree_mutation
self.p_hoist_mutation = p_hoist_mutation
self.p_point_mutation = p_point_mutation
self.p_point_replace = p_point_replace
self.max_samples = max_samples
self.class_weight = class_weight
self.feature_names = feature_names
self.warm_start = warm_start
self.low_memory = low_memory
self.n_jobs = n_jobs
self.verbose = verbose
self.random_state = random_state
def _verbose_reporter(self, run_details=None):
"""A report of the progress of the evolution process.
Parameters
----------
run_details : dict
Information about the evolution.
"""
if run_details is None:
print(' |{:^25}|{:^42}|'.format('Population Average',
'Best Individual'))
print('-' * 4 + ' ' + '-' * 25 + ' ' + '-' * 42 + ' ' + '-' * 10)
line_format = '{:>4} {:>8} {:>16} {:>8} {:>16} {:>16} {:>10}'
print(line_format.format('Gen', 'Length', 'Fitness', 'Length',
'Fitness', 'OOB Fitness', 'Time Left'))
else:
# Estimate remaining time for run
gen = run_details['generation'][-1]
generation_time = run_details['generation_time'][-1]
remaining_time = (self.generations - gen - 1) * generation_time
if remaining_time > 60:
remaining_time = '{0:.2f}m'.format(remaining_time / 60.0)
else:
remaining_time = '{0:.2f}s'.format(remaining_time)
oob_fitness = 'N/A'
line_format = '{:4d} {:8.2f} {:16g} {:8d} {:16g} {:>16} {:>10}'
if self.max_samples < 1.0:
oob_fitness = run_details['best_oob_fitness'][-1]
line_format = '{:4d} {:8.2f} {:16g} {:8d} {:16g} {:16g} {:>10}'
print(line_format.format(run_details['generation'][-1],
run_details['average_length'][-1],
run_details['average_fitness'][-1],
run_details['best_length'][-1],
run_details['best_fitness'][-1],
oob_fitness,
remaining_time))
def _validate_data(self, *args, **kwargs):
try:
# scikit-learn >= 1.6
from sklearn.utils.validation import validate_data
return validate_data(self, *args, **kwargs)
except ImportError:
# scikit-learn < 1.6
return super()._validate_data(*args, **kwargs)
def fit(self, X, y, sample_weight=None):
"""Fit the Genetic Program according to X, y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
sample_weight : array-like, shape = [n_samples], optional
Weights applied to individual samples.
Returns
-------
self : object
Returns self.
"""
random_state = check_random_state(self.random_state)
# Check arrays
if sample_weight is not None:
sample_weight = _check_sample_weight(sample_weight, X)
if isinstance(self, ClassifierMixin):
X, y = self._validate_data(X, y, y_numeric=False)
check_classification_targets(y)
# Once we require scikit-learn >= 1.6, this should pass
# raise_unknown=True rather than checking for "unknown"
# manually.
y_type = type_of_target(y, input_name="y")
if y_type == "unknown":
raise ValueError("Unknown label type for y: %r" % y)
elif y_type != "binary":
raise ValueError(
"Only binary classification is supported. The type of the "
"target is %s."
% y_type
)
if self.class_weight:
if sample_weight is None:
sample_weight = 1.
# modify the sample weights with the corresponding class weight
sample_weight = (sample_weight *
compute_sample_weight(self.class_weight, y))
self.classes_, y = np.unique(y, return_inverse=True)
n_trim_classes = np.count_nonzero(np.bincount(y, sample_weight))
if n_trim_classes != 2:
raise ValueError("y contains %d class after sample_weight "
"trimmed classes with zero weights, while 2 "
"classes are required."
% n_trim_classes)
self.n_classes_ = len(self.classes_)
else:
X, y = self._validate_data(X, y, y_numeric=True)
hall_of_fame = self.hall_of_fame
if hall_of_fame is None:
hall_of_fame = self.population_size
if hall_of_fame > self.population_size or hall_of_fame < 1:
raise ValueError('hall_of_fame (%d) must be less than or equal to '
'population_size (%d).' % (self.hall_of_fame,
self.population_size))
n_components = self.n_components
if n_components is None:
n_components = hall_of_fame
if n_components > hall_of_fame or n_components < 1:
raise ValueError('n_components (%d) must be less than or equal to '
'hall_of_fame (%d).' % (self.n_components,
self.hall_of_fame))
self._function_set = []
for function in self.function_set:
if isinstance(function, str):
if function not in _function_map:
raise ValueError('invalid function name %s found in '
'`function_set`.' % function)
self._function_set.append(_function_map[function])
elif isinstance(function, _Function):
self._function_set.append(function)
else:
raise ValueError('invalid type %s found in `function_set`.'
% type(function))
if not self._function_set:
raise ValueError('No valid functions found in `function_set`.')
# For point-mutation to find a compatible replacement node
self._arities = {}
for function in self._function_set:
arity = function.arity
self._arities[arity] = self._arities.get(arity, [])
self._arities[arity].append(function)
if isinstance(self.metric, _Fitness):
self._metric = self.metric
elif isinstance(self, RegressorMixin):
if self.metric not in ('mean absolute error', 'mse', 'rmse',
'pearson', 'spearman'):
raise ValueError('Unsupported metric: %s' % self.metric)
self._metric = _fitness_map[self.metric]
elif isinstance(self, ClassifierMixin):
if self.metric != 'log loss':
raise ValueError('Unsupported metric: %s' % self.metric)
self._metric = _fitness_map[self.metric]
elif isinstance(self, TransformerMixin):
if self.metric not in ('pearson', 'spearman'):
raise ValueError('Unsupported metric: %s' % self.metric)
self._metric = _fitness_map[self.metric]
self._method_probs = np.array([self.p_crossover,
self.p_subtree_mutation,
self.p_hoist_mutation,
self.p_point_mutation])
self._method_probs = np.cumsum(self._method_probs)
if self._method_probs[-1] > 1:
raise ValueError('The sum of p_crossover, p_subtree_mutation, '
'p_hoist_mutation and p_point_mutation should '
'total to 1.0 or less.')
if self.init_method not in ('half and half', 'grow', 'full'):
raise ValueError('Valid program initializations methods include '
'"grow", "full" and "half and half". Given %s.'
% self.init_method)
if not((isinstance(self.const_range, tuple) and
len(self.const_range) == 2) or self.const_range is None):
raise ValueError('const_range should be a tuple with length two, '
'or None.')
if (not isinstance(self.init_depth, tuple) or
len(self.init_depth) != 2):
raise ValueError('init_depth should be a tuple with length two.')
if self.init_depth[0] > self.init_depth[1]:
raise ValueError('init_depth should be in increasing numerical '
'order: (min_depth, max_depth).')
if self.feature_names is not None:
if self.n_features_in_ != len(self.feature_names):
raise ValueError('The supplied `feature_names` has different '
'length to n_features. Expected %d, got %d.'
% (self.n_features_in_,
len(self.feature_names)))
for feature_name in self.feature_names:
if not isinstance(feature_name, str):
raise ValueError('invalid type %s found in '
'`feature_names`.' % type(feature_name))
if self.transformer is not None:
if isinstance(self.transformer, _Function):
self._transformer = self.transformer
elif self.transformer == 'sigmoid':
self._transformer = sigmoid
else:
raise ValueError('Invalid `transformer`. Expected either '
'"sigmoid" or _Function object, got %s' %
type(self.transformer))
if self._transformer.arity != 1:
raise ValueError('Invalid arity for `transformer`. Expected 1, '
'got %d.' % (self._transformer.arity))
params = self.get_params()
params['_metric'] = self._metric
if hasattr(self, '_transformer'):
params['_transformer'] = self._transformer
else:
params['_transformer'] = None
params['function_set'] = self._function_set
params['arities'] = self._arities
params['method_probs'] = self._method_probs
if not self.warm_start or not hasattr(self, '_programs'):
# Free allocated memory, if any
self._programs = []
self.run_details_ = {'generation': [],
'average_length': [],
'average_fitness': [],
'best_length': [],
'best_fitness': [],
'best_oob_fitness': [],
'generation_time': []}
prior_generations = len(self._programs)
n_more_generations = self.generations - prior_generations
if n_more_generations < 0:
raise ValueError('generations=%d must be larger or equal to '
'len(_programs)=%d when warm_start==True'
% (self.generations, len(self._programs)))
elif n_more_generations == 0:
fitness = [program.raw_fitness_ for program in self._programs[-1]]
warn('Warm-start fitting without increasing n_estimators does not '
'fit new programs.')
if self.warm_start:
# Generate and discard seeds that would have been produced on the
# initial fit call.
for i in range(len(self._programs)):
_ = random_state.randint(MAX_INT, size=self.population_size)
if self.verbose:
# Print header fields
self._verbose_reporter()
for gen in range(prior_generations, self.generations):
start_time = time()
if gen == 0:
parents = None
else:
parents = self._programs[gen - 1]
# Parallel loop
n_jobs, n_programs, starts = _partition_estimators(
self.population_size, self.n_jobs)
seeds = random_state.randint(MAX_INT, size=self.population_size)
population = Parallel(n_jobs=n_jobs,
verbose=int(self.verbose > 1))(
delayed(_parallel_evolve)(n_programs[i],
parents,
X,
y,
sample_weight,
seeds[starts[i]:starts[i + 1]],
params)
for i in range(n_jobs))
# Reduce, maintaining order across different n_jobs
population = list(itertools.chain.from_iterable(population))
fitness = [program.raw_fitness_ for program in population]
length = [program.length_ for program in population]
parsimony_coefficient = None
if self.parsimony_coefficient == 'auto':
parsimony_coefficient = (np.cov(length, fitness)[1, 0] /
np.var(length))
for program in population:
program.fitness_ = program.fitness(parsimony_coefficient)
self._programs.append(population)
# Remove old programs that didn't make it into the new population.
if not self.low_memory:
for old_gen in np.arange(gen, 0, -1):
indices = []
for program in self._programs[old_gen]:
if program is not None:
for idx in program.parents:
if 'idx' in idx:
indices.append(program.parents[idx])
indices = set(indices)
for idx in range(self.population_size):
if idx not in indices:
self._programs[old_gen - 1][idx] = None
elif gen > 0:
# Remove old generations
self._programs[gen - 1] = None
# Record run details
if self._metric.greater_is_better:
best_program = population[np.argmax(fitness)]
else:
best_program = population[np.argmin(fitness)]
self.run_details_['generation'].append(gen)
self.run_details_['average_length'].append(np.mean(length))
self.run_details_['average_fitness'].append(np.mean(fitness))
self.run_details_['best_length'].append(best_program.length_)
self.run_details_['best_fitness'].append(best_program.raw_fitness_)
oob_fitness = np.nan
if self.max_samples < 1.0:
oob_fitness = best_program.oob_fitness_
self.run_details_['best_oob_fitness'].append(oob_fitness)
generation_time = time() - start_time
self.run_details_['generation_time'].append(generation_time)
if self.verbose:
self._verbose_reporter(self.run_details_)
# Check for early stopping
if self._metric.greater_is_better:
best_fitness = fitness[np.argmax(fitness)]
if best_fitness >= self.stopping_criteria:
break
else:
best_fitness = fitness[np.argmin(fitness)]
if best_fitness <= self.stopping_criteria:
break
if isinstance(self, TransformerMixin):
# Find the best individuals in the final generation
fitness = np.array(fitness)
if self._metric.greater_is_better:
hall_of_fame = fitness.argsort()[::-1][:self.hall_of_fame]
else:
hall_of_fame = fitness.argsort()[:self.hall_of_fame]
evaluation = np.array([gp.execute(X) for gp in
[self._programs[-1][i] for
i in hall_of_fame]])
if self.metric == 'spearman':
evaluation = np.apply_along_axis(rankdata, 1, evaluation)
with np.errstate(divide='ignore', invalid='ignore'):
correlations = np.abs(np.corrcoef(evaluation))
np.fill_diagonal(correlations, 0.)
components = list(range(self.hall_of_fame))
indices = list(range(self.hall_of_fame))
# Iteratively remove least fit individual of most correlated pair
while len(components) > self.n_components:
most_correlated = np.unravel_index(np.argmax(correlations),
correlations.shape)
# The correlation matrix is sorted by fitness, so identifying
# the least fit of the pair is simply getting the higher index
worst = max(most_correlated)
components.pop(worst)
indices.remove(worst)
correlations = correlations[:, indices][indices, :]
indices = list(range(len(components)))
self._best_programs = [self._programs[-1][i] for i in
hall_of_fame[components]]
else:
# Find the best individual in the final generation
if self._metric.greater_is_better:
self._program = self._programs[-1][np.argmax(fitness)]
else:
self._program = self._programs[-1][np.argmin(fitness)]
return self
class SymbolicRegressor(RegressorMixin, BaseSymbolic):
"""A Genetic Programming symbolic regressor.
A symbolic regressor is an estimator that begins by building a population
of naive random formulas to represent a relationship. The formulas are
represented as tree-like structures with mathematical functions being
recursively applied to variables and constants. Each successive generation
of programs is then evolved from the one that came before it by selecting
the fittest individuals from the population to undergo genetic operations
such as crossover, mutation or reproduction.
Parameters
----------
population_size : integer, optional (default=1000)
The number of programs in each generation.
generations : integer, optional (default=20)
The number of generations to evolve.
tournament_size : integer, optional (default=20)
The number of programs that will compete to become part of the next
generation.
stopping_criteria : float, optional (default=0.0)
The required metric value required in order to stop evolution early.
const_range : tuple of two floats, or None, optional (default=(-1., 1.))
The range of constants to include in the formulas. If None then no
constants will be included in the candidate programs.
init_depth : tuple of two ints, optional (default=(2, 6))
The range of tree depths for the initial population of naive formulas.
Individual trees will randomly choose a maximum depth from this range.
When combined with `init_method='half and half'` this yields the well-
known 'ramped half and half' initialization method.
init_method : str, optional (default='half and half')
- 'grow' : Nodes are chosen at random from both functions and
terminals, allowing for smaller trees than `init_depth` allows. Tends
to grow asymmetrical trees.
- 'full' : Functions are chosen until the `init_depth` is reached, and
then terminals are selected. Tends to grow 'bushy' trees.
- 'half and half' : Trees are grown through a 50/50 mix of 'full' and
'grow', making for a mix of tree shapes in the initial population.
function_set : iterable, optional (default=('add', 'sub', 'mul', 'div'))
The functions to use when building and evolving programs. This iterable
can include strings to indicate either individual functions as outlined
below, or you can also include your own functions as built using the
``make_function`` factory from the ``functions`` module.
Available individual functions are:
- 'add' : addition, arity=2.
- 'sub' : subtraction, arity=2.
- 'mul' : multiplication, arity=2.
- 'div' : protected division where a denominator near-zero returns 1.,
arity=2.
- 'sqrt' : protected square root where the absolute value of the
argument is used, arity=1.
- 'log' : protected log where the absolute value of the argument is
used and a near-zero argument returns 0., arity=1.
- 'abs' : absolute value, arity=1.
- 'neg' : negative, arity=1.
- 'inv' : protected inverse where a near-zero argument returns 0.,
arity=1.
- 'max' : maximum, arity=2.
- 'min' : minimum, arity=2.
- 'sin' : sine (radians), arity=1.
- 'cos' : cosine (radians), arity=1.
- 'tan' : tangent (radians), arity=1.
metric : str, optional (default='mean absolute error')
The name of the raw fitness metric. Available options include:
- 'mean absolute error'.
- 'mse' for mean squared error.
- 'rmse' for root mean squared error.
- 'pearson', for Pearson's product-moment correlation coefficient.
- 'spearman' for Spearman's rank-order correlation coefficient.
Note that 'pearson' and 'spearman' will not directly predict the target
but could be useful as value-added features in a second-step estimator.
This would allow the user to generate one engineered feature at a time,
using the SymbolicTransformer would allow creation of multiple features
at once.
parsimony_coefficient : float or "auto", optional (default=0.001)
This constant penalizes large programs by adjusting their fitness to
be less favorable for selection. Larger values penalize the program
more which can control the phenomenon known as 'bloat'. Bloat is when
evolution is increasing the size of programs without a significant
increase in fitness, which is costly for computation time and makes for
a less understandable final result. This parameter may need to be tuned
over successive runs.
If "auto" the parsimony coefficient is recalculated for each generation
using c = Cov(l,f)/Var( l), where Cov(l,f) is the covariance between
program size l and program fitness f in the population, and Var(l) is
the variance of program sizes.
p_crossover : float, optional (default=0.9)
The probability of performing crossover on a tournament winner.
Crossover takes the winner of a tournament and selects a random subtree
from it to be replaced. A second tournament is performed to find a
donor. The donor also has a subtree selected at random and this is
inserted into the original parent to form an offspring in the next
generation.
p_subtree_mutation : float, optional (default=0.01)
The probability of performing subtree mutation on a tournament winner.
Subtree mutation takes the winner of a tournament and selects a random
subtree from it to be replaced. A donor subtree is generated at random
and this is inserted into the original parent to form an offspring in
the next generation.
p_hoist_mutation : float, optional (default=0.01)
The probability of performing hoist mutation on a tournament winner.
Hoist mutation takes the winner of a tournament and selects a random
subtree from it. A random subtree of that subtree is then selected
and this is 'hoisted' into the original subtrees location to form an
offspring in the next generation. This method helps to control bloat.
p_point_mutation : float, optional (default=0.01)
The probability of performing point mutation on a tournament winner.
Point mutation takes the winner of a tournament and selects random
nodes from it to be replaced. Terminals are replaced by other terminals
and functions are replaced by other functions that require the same
number of arguments as the original node. The resulting tree forms an
offspring in the next generation.
Note : The above genetic operation probabilities must sum to less than
one. The balance of probability is assigned to 'reproduction', where a
tournament winner is cloned and enters the next generation unmodified.
p_point_replace : float, optional (default=0.05)
For point mutation only, the probability that any given node will be
mutated.
max_samples : float, optional (default=1.0)
The fraction of samples to draw from X to evaluate each program on.
feature_names : list, optional (default=None)
Optional list of feature names, used purely for representations in
the `print` operation or `export_graphviz`. If None, then X0, X1, etc
will be used for representations.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more generations to the evolution, otherwise, just fit a new
evolution.
low_memory : bool, optional (default=False)
When set to ``True``, only the current generation is retained. Parent
information is discarded. For very large populations or runs with many
generations, this can result in substantial memory use reduction.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for `fit`. If -1, then the number
of jobs is set to the number of cores.
verbose : int, optional (default=0)
Controls the verbosity of the evolution building process.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Attributes
----------
run_details_ : dict
Details of the evolution process. Includes the following elements:
- 'generation' : The generation index.
- 'average_length' : The average program length of the generation.
- 'average_fitness' : The average program fitness of the generation.
- 'best_length' : The length of the best program in the generation.
- 'best_fitness' : The fitness of the best program in the generation.
- 'best_oob_fitness' : The out of bag fitness of the best program in
the generation (requires `max_samples` < 1.0).
- 'generation_time' : The time it took for the generation to evolve.
See Also
--------
SymbolicTransformer
References
----------
.. [1] J. Koza, "Genetic Programming", 1992.
.. [2] R. Poli, et al. "A Field Guide to Genetic Programming", 2008.
"""
def __init__(self,
*,
population_size=1000,
generations=20,
tournament_size=20,
stopping_criteria=0.0,
const_range=(-1., 1.),
init_depth=(2, 6),
init_method='half and half',
function_set=('add', 'sub', 'mul', 'div'),
metric='mean absolute error',
parsimony_coefficient=0.001,
p_crossover=0.9,
p_subtree_mutation=0.01,
p_hoist_mutation=0.01,
p_point_mutation=0.01,
p_point_replace=0.05,
max_samples=1.0,
feature_names=None,
warm_start=False,
low_memory=False,
n_jobs=1,
verbose=0,
random_state=None):
super(SymbolicRegressor, self).__init__(
population_size=population_size,
generations=generations,
tournament_size=tournament_size,
stopping_criteria=stopping_criteria,
const_range=const_range,
init_depth=init_depth,
init_method=init_method,
function_set=function_set,
metric=metric,
parsimony_coefficient=parsimony_coefficient,
p_crossover=p_crossover,
p_subtree_mutation=p_subtree_mutation,
p_hoist_mutation=p_hoist_mutation,
p_point_mutation=p_point_mutation,
p_point_replace=p_point_replace,
max_samples=max_samples,
feature_names=feature_names,
warm_start=warm_start,
low_memory=low_memory,
n_jobs=n_jobs,
verbose=verbose,
random_state=random_state)
def __str__(self):
"""Overloads `print` output of the object to resemble a LISP tree."""
if not hasattr(self, '_program'):
return self.__repr__()
return self._program.__str__()
def predict(self, X):
"""Perform regression on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
y : array, shape = [n_samples]
Predicted values for X.
"""
if not hasattr(self, '_program'):
raise NotFittedError('SymbolicRegressor not fitted.')
try:
# scikit-learn >= 1.6
from sklearn.utils.validation import validate_data
X = validate_data(self, X, reset=False)
except ImportError:
# scikit-learn < 1.6
X = check_array(X)
_, n_features = X.shape
if self.n_features_in_ != n_features:
raise ValueError('Number of features of the model must match the '
'input. Model n_features is %s and input '
'n_features is %s.'
% (self.n_features_in_, n_features))
y = self._program.execute(X)
return y
class SymbolicClassifier(ClassifierMixin, BaseSymbolic):
"""A Genetic Programming symbolic classifier.
A symbolic classifier is an estimator that begins by building a population
of naive random formulas to represent a relationship. The formulas are
represented as tree-like structures with mathematical functions being
recursively applied to variables and constants. Each successive generation
of programs is then evolved from the one that came before it by selecting
the fittest individuals from the population to undergo genetic operations
such as crossover, mutation or reproduction.
Parameters
----------
population_size : integer, optional (default=500)
The number of programs in each generation.
generations : integer, optional (default=10)
The number of generations to evolve.
tournament_size : integer, optional (default=20)
The number of programs that will compete to become part of the next
generation.
stopping_criteria : float, optional (default=0.0)
The required metric value required in order to stop evolution early.
const_range : tuple of two floats, or None, optional (default=(-1., 1.))
The range of constants to include in the formulas. If None then no
constants will be included in the candidate programs.
init_depth : tuple of two ints, optional (default=(2, 6))
The range of tree depths for the initial population of naive formulas.
Individual trees will randomly choose a maximum depth from this range.
When combined with `init_method='half and half'` this yields the well-
known 'ramped half and half' initialization method.
init_method : str, optional (default='half and half')
- 'grow' : Nodes are chosen at random from both functions and
terminals, allowing for smaller trees than `init_depth` allows. Tends
to grow asymmetrical trees.
- 'full' : Functions are chosen until the `init_depth` is reached, and
then terminals are selected. Tends to grow 'bushy' trees.
- 'half and half' : Trees are grown through a 50/50 mix of 'full' and
'grow', making for a mix of tree shapes in the initial population.
function_set : iterable, optional (default=('add', 'sub', 'mul', 'div'))
The functions to use when building and evolving programs. This iterable
can include strings to indicate either individual functions as outlined
below, or you can also include your own functions as built using the
``make_function`` factory from the ``functions`` module.
Available individual functions are:
- 'add' : addition, arity=2.
- 'sub' : subtraction, arity=2.
- 'mul' : multiplication, arity=2.
- 'div' : protected division where a denominator near-zero returns 1.,
arity=2.
- 'sqrt' : protected square root where the absolute value of the
argument is used, arity=1.
- 'log' : protected log where the absolute value of the argument is
used and a near-zero argument returns 0., arity=1.
- 'abs' : absolute value, arity=1.
- 'neg' : negative, arity=1.
- 'inv' : protected inverse where a near-zero argument returns 0.,
arity=1.
- 'max' : maximum, arity=2.
- 'min' : minimum, arity=2.
- 'sin' : sine (radians), arity=1.
- 'cos' : cosine (radians), arity=1.
- 'tan' : tangent (radians), arity=1.
transformer : str, optional (default='sigmoid')
The name of the function through which the raw decision function is
passed. This function will transform the raw decision function into
probabilities of each class.
This can also be replaced by your own functions as built using the
``make_function`` factory from the ``functions`` module.
metric : str, optional (default='log loss')
The name of the raw fitness metric. Available options include:
- 'log loss' aka binary cross-entropy loss.
parsimony_coefficient : float or "auto", optional (default=0.001)
This constant penalizes large programs by adjusting their fitness to
be less favorable for selection. Larger values penalize the program
more which can control the phenomenon known as 'bloat'. Bloat is when
evolution is increasing the size of programs without a significant
increase in fitness, which is costly for computation time and makes for
a less understandable final result. This parameter may need to be tuned
over successive runs.
If "auto" the parsimony coefficient is recalculated for each generation
using c = Cov(l,f)/Var( l), where Cov(l,f) is the covariance between
program size l and program fitness f in the population, and Var(l) is
the variance of program sizes.
p_crossover : float, optional (default=0.9)
The probability of performing crossover on a tournament winner.
Crossover takes the winner of a tournament and selects a random subtree
from it to be replaced. A second tournament is performed to find a
donor. The donor also has a subtree selected at random and this is
inserted into the original parent to form an offspring in the next
generation.
p_subtree_mutation : float, optional (default=0.01)
The probability of performing subtree mutation on a tournament winner.
Subtree mutation takes the winner of a tournament and selects a random
subtree from it to be replaced. A donor subtree is generated at random
and this is inserted into the original parent to form an offspring in
the next generation.
p_hoist_mutation : float, optional (default=0.01)
The probability of performing hoist mutation on a tournament winner.
Hoist mutation takes the winner of a tournament and selects a random
subtree from it. A random subtree of that subtree is then selected
and this is 'hoisted' into the original subtrees location to form an
offspring in the next generation. This method helps to control bloat.
p_point_mutation : float, optional (default=0.01)
The probability of performing point mutation on a tournament winner.
Point mutation takes the winner of a tournament and selects random
nodes from it to be replaced. Terminals are replaced by other terminals
and functions are replaced by other functions that require the same
number of arguments as the original node. The resulting tree forms an
offspring in the next generation.
Note : The above genetic operation probabilities must sum to less than
one. The balance of probability is assigned to 'reproduction', where a
tournament winner is cloned and enters the next generation unmodified.
p_point_replace : float, optional (default=0.05)
For point mutation only, the probability that any given node will be
mutated.
max_samples : float, optional (default=1.0)
The fraction of samples to draw from X to evaluate each program on.
class_weight : dict, 'balanced' or None, optional (default=None)
Weights associated with classes in the form ``{class_label: weight}``.
If not given, all classes are supposed to have weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
feature_names : list, optional (default=None)
Optional list of feature names, used purely for representations in
the `print` operation or `export_graphviz`. If None, then X0, X1, etc
will be used for representations.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more generations to the evolution, otherwise, just fit a new
evolution.
low_memory : bool, optional (default=False)
When set to ``True``, only the current generation is retained. Parent
information is discarded. For very large populations or runs with many
generations, this can result in substantial memory use reduction.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for `fit`. If -1, then the number
of jobs is set to the number of cores.
verbose : int, optional (default=0)
Controls the verbosity of the evolution building process.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Attributes
----------
run_details_ : dict
Details of the evolution process. Includes the following elements:
- 'generation' : The generation index.
- 'average_length' : The average program length of the generation.
- 'average_fitness' : The average program fitness of the generation.
- 'best_length' : The length of the best program in the generation.
- 'best_fitness' : The fitness of the best program in the generation.
- 'best_oob_fitness' : The out of bag fitness of the best program in
the generation (requires `max_samples` < 1.0).
- 'generation_time' : The time it took for the generation to evolve.
See Also
--------
SymbolicTransformer
References
----------
.. [1] J. Koza, "Genetic Programming", 1992.
.. [2] R. Poli, et al. "A Field Guide to Genetic Programming", 2008.
"""
def __init__(self,
*,
population_size=1000,
generations=20,
tournament_size=20,
stopping_criteria=0.0,
const_range=(-1., 1.),
init_depth=(2, 6),
init_method='half and half',
function_set=('add', 'sub', 'mul', 'div'),
transformer='sigmoid',
metric='log loss',
parsimony_coefficient=0.001,
p_crossover=0.9,
p_subtree_mutation=0.01,
p_hoist_mutation=0.01,
p_point_mutation=0.01,
p_point_replace=0.05,
max_samples=1.0,
class_weight=None,
feature_names=None,
warm_start=False,
low_memory=False,
n_jobs=1,
verbose=0,
random_state=None):
super(SymbolicClassifier, self).__init__(
population_size=population_size,
generations=generations,
tournament_size=tournament_size,
stopping_criteria=stopping_criteria,
const_range=const_range,
init_depth=init_depth,
init_method=init_method,
function_set=function_set,
transformer=transformer,
metric=metric,
parsimony_coefficient=parsimony_coefficient,
p_crossover=p_crossover,
p_subtree_mutation=p_subtree_mutation,
p_hoist_mutation=p_hoist_mutation,
p_point_mutation=p_point_mutation,
p_point_replace=p_point_replace,
max_samples=max_samples,
class_weight=class_weight,
feature_names=feature_names,
warm_start=warm_start,
low_memory=low_memory,
n_jobs=n_jobs,
verbose=verbose,
random_state=random_state)
def __str__(self):
"""Overloads `print` output of the object to resemble a LISP tree."""
if not hasattr(self, '_program'):
return self.__repr__()
return self._program.__str__()
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.classifier_tags.multi_class = False
return tags
def _more_tags(self):
return {'binary_only': True}
def predict_proba(self, X):
"""Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
proba : array, shape = [n_samples, n_classes]
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
if not hasattr(self, '_program'):
raise NotFittedError('SymbolicClassifier not fitted.')
try:
# scikit-learn >= 1.6
from sklearn.utils.validation import validate_data
X = validate_data(self, X, reset=False)
except ImportError:
# scikit-learn < 1.6
X = check_array(X)
_, n_features = X.shape
if self.n_features_in_ != n_features:
raise ValueError('Number of features of the model must match the '
'input. Model n_features is %s and input '
'n_features is %s.'
% (self.n_features_in_, n_features))
scores = self._program.execute(X)
proba = self._transformer(scores)
proba = np.vstack([1 - proba, proba]).T
return proba
def predict(self, X):
"""Predict classes on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
y : array, shape = [n_samples,]
The predicted classes of the input samples.
"""
proba = self.predict_proba(X)
return self.classes_.take(np.argmax(proba, axis=1), axis=0)
class SymbolicTransformer(TransformerMixin, BaseSymbolic):
"""A Genetic Programming symbolic transformer.
A symbolic transformer is a supervised transformer that begins by building
a population of naive random formulas to represent a relationship. The
formulas are represented as tree-like structures with mathematical
functions being recursively applied to variables and constants. Each
successive generation of programs is then evolved from the one that came
before it by selecting the fittest individuals from the population to
undergo genetic operations such as crossover, mutation or reproduction.
The final population is searched for the fittest individuals with the least
correlation to one another.
Parameters
----------
population_size : integer, optional (default=1000)
The number of programs in each generation.
hall_of_fame : integer, or None, optional (default=100)
The number of fittest programs to compare from when finding the
least-correlated individuals for the n_components. If `None`, the
entire final generation will be used.
n_components : integer, or None, optional (default=10)
The number of best programs to return after searching the hall_of_fame
for the least-correlated individuals. If `None`, the entire
hall_of_fame will be used.
generations : integer, optional (default=20)
The number of generations to evolve.
tournament_size : integer, optional (default=20)
The number of programs that will compete to become part of the next
generation.
stopping_criteria : float, optional (default=1.0)
The required metric value required in order to stop evolution early.
const_range : tuple of two floats, or None, optional (default=(-1., 1.))
The range of constants to include in the formulas. If None then no
constants will be included in the candidate programs.
init_depth : tuple of two ints, optional (default=(2, 6))
The range of tree depths for the initial population of naive formulas.
Individual trees will randomly choose a maximum depth from this range.
When combined with `init_method='half and half'` this yields the well-
known 'ramped half and half' initialization method.
init_method : str, optional (default='half and half')
- 'grow' : Nodes are chosen at random from both functions and
terminals, allowing for smaller trees than `init_depth` allows. Tends
to grow asymmetrical trees.
- 'full' : Functions are chosen until the `init_depth` is reached, and
then terminals are selected. Tends to grow 'bushy' trees.
- 'half and half' : Trees are grown through a 50/50 mix of 'full' and
'grow', making for a mix of tree shapes in the initial population.
function_set : iterable, optional (default=('add', 'sub', 'mul', 'div'))
The functions to use when building and evolving programs. This iterable
can include strings to indicate either individual functions as outlined
below, or you can also include your own functions as built using the
``make_function`` factory from the ``functions`` module.
Available individual functions are:
- 'add' : addition, arity=2.
- 'sub' : subtraction, arity=2.
- 'mul' : multiplication, arity=2.
- 'div' : protected division where a denominator near-zero returns 1.,
arity=2.
- 'sqrt' : protected square root where the absolute value of the
argument is used, arity=1.
- 'log' : protected log where the absolute value of the argument is
used and a near-zero argument returns 0., arity=1.
- 'abs' : absolute value, arity=1.
- 'neg' : negative, arity=1.
- 'inv' : protected inverse where a near-zero argument returns 0.,
arity=1.
- 'max' : maximum, arity=2.
- 'min' : minimum, arity=2.
- 'sin' : sine (radians), arity=1.
- 'cos' : cosine (radians), arity=1.
- 'tan' : tangent (radians), arity=1.
metric : str, optional (default='pearson')
The name of the raw fitness metric. Available options include:
- 'pearson', for Pearson's product-moment correlation coefficient.
- 'spearman' for Spearman's rank-order correlation coefficient.
parsimony_coefficient : float or "auto", optional (default=0.001)
This constant penalizes large programs by adjusting their fitness to
be less favorable for selection. Larger values penalize the program
more which can control the phenomenon known as 'bloat'. Bloat is when
evolution is increasing the size of programs without a significant
increase in fitness, which is costly for computation time and makes for
a less understandable final result. This parameter may need to be tuned
over successive runs.
If "auto" the parsimony coefficient is recalculated for each generation
using c = Cov(l,f)/Var( l), where Cov(l,f) is the covariance between
program size l and program fitness f in the population, and Var(l) is
the variance of program sizes.
p_crossover : float, optional (default=0.9)
The probability of performing crossover on a tournament winner.
Crossover takes the winner of a tournament and selects a random subtree
from it to be replaced. A second tournament is performed to find a
donor. The donor also has a subtree selected at random and this is
inserted into the original parent to form an offspring in the next
generation.
p_subtree_mutation : float, optional (default=0.01)
The probability of performing subtree mutation on a tournament winner.
Subtree mutation takes the winner of a tournament and selects a random
subtree from it to be replaced. A donor subtree is generated at random
and this is inserted into the original parent to form an offspring in
the next generation.
p_hoist_mutation : float, optional (default=0.01)
The probability of performing hoist mutation on a tournament winner.
Hoist mutation takes the winner of a tournament and selects a random
subtree from it. A random subtree of that subtree is then selected
and this is 'hoisted' into the original subtrees location to form an
offspring in the next generation. This method helps to control bloat.
p_point_mutation : float, optional (default=0.01)
The probability of performing point mutation on a tournament winner.
Point mutation takes the winner of a tournament and selects random
nodes from it to be replaced. Terminals are replaced by other terminals
and functions are replaced by other functions that require the same
number of arguments as the original node. The resulting tree forms an
offspring in the next generation.
Note : The above genetic operation probabilities must sum to less than
one. The balance of probability is assigned to 'reproduction', where a
tournament winner is cloned and enters the next generation unmodified.
p_point_replace : float, optional (default=0.05)
For point mutation only, the probability that any given node will be
mutated.
max_samples : float, optional (default=1.0)
The fraction of samples to draw from X to evaluate each program on.
feature_names : list, optional (default=None)
Optional list of feature names, used purely for representations in
the `print` operation or `export_graphviz`. If None, then X0, X1, etc
will be used for representations.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more generations to the evolution, otherwise, just fit a new
evolution.
low_memory : bool, optional (default=False)
When set to ``True``, only the current generation is retained. Parent
information is discarded. For very large populations or runs with many
generations, this can result in substantial memory use reduction.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for `fit`. If -1, then the number
of jobs is set to the number of cores.
verbose : int, optional (default=0)
Controls the verbosity of the evolution building process.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Attributes
----------
run_details_ : dict
Details of the evolution process. Includes the following elements:
- 'generation' : The generation index.
- 'average_length' : The average program length of the generation.
- 'average_fitness' : The average program fitness of the generation.
- 'best_length' : The length of the best program in the generation.
- 'best_fitness' : The fitness of the best program in the generation.
- 'best_oob_fitness' : The out of bag fitness of the best program in
the generation (requires `max_samples` < 1.0).
- 'generation_time' : The time it took for the generation to evolve.
See Also
--------
SymbolicRegressor
References
----------
.. [1] J. Koza, "Genetic Programming", 1992.
.. [2] R. Poli, et al. "A Field Guide to Genetic Programming", 2008.
"""
def __init__(self,
*,
population_size=1000,
hall_of_fame=100,
n_components=10,
generations=20,
tournament_size=20,
stopping_criteria=1.0,
const_range=(-1., 1.),
init_depth=(2, 6),
init_method='half and half',
function_set=('add', 'sub', 'mul', 'div'),
metric='pearson',
parsimony_coefficient=0.001,
p_crossover=0.9,
p_subtree_mutation=0.01,
p_hoist_mutation=0.01,
p_point_mutation=0.01,
p_point_replace=0.05,
max_samples=1.0,
feature_names=None,
warm_start=False,
low_memory=False,
n_jobs=1,
verbose=0,
random_state=None):
super(SymbolicTransformer, self).__init__(
population_size=population_size,
hall_of_fame=hall_of_fame,
n_components=n_components,
generations=generations,
tournament_size=tournament_size,
stopping_criteria=stopping_criteria,
const_range=const_range,
init_depth=init_depth,
init_method=init_method,
function_set=function_set,
metric=metric,
parsimony_coefficient=parsimony_coefficient,
p_crossover=p_crossover,
p_subtree_mutation=p_subtree_mutation,
p_hoist_mutation=p_hoist_mutation,
p_point_mutation=p_point_mutation,
p_point_replace=p_point_replace,
max_samples=max_samples,
feature_names=feature_names,
warm_start=warm_start,
low_memory=low_memory,
n_jobs=n_jobs,
verbose=verbose,
random_state=random_state)
def __len__(self):
"""Overloads `len` output to be the number of fitted components."""
if not hasattr(self, '_best_programs'):
return 0
return self.n_components
def __getitem__(self, item):
"""Return the ith item of the fitted components."""
if item >= len(self):
raise IndexError
return self._best_programs[item]
def __str__(self):
"""Overloads `print` output of the object to resemble LISP trees."""
if not hasattr(self, '_best_programs'):
return self.__repr__()
output = str([gp.__str__() for gp in self])
return output.replace("',", ",\n").replace("'", "")
if not _sklearn_version_ge("1.6"):
def _more_tags(self):
return {
"_xfail_checks": {
"check_sample_weights_invariance": (
"zero sample_weight is not equivalent to removing "
"samples"
),
}
}
def transform(self, X):
"""Transform X according to the fitted transformer.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
X_new : array-like, shape = [n_samples, n_components]
Transformed array.
"""
if not hasattr(self, '_best_programs'):
raise NotFittedError('SymbolicTransformer not fitted.')
try:
# scikit-learn >= 1.6
from sklearn.utils.validation import validate_data
X = validate_data(self, X, reset=False)
except ImportError:
# scikit-learn < 1.6
X = check_array(X)
_, n_features = X.shape
if self.n_features_in_ != n_features:
raise ValueError('Number of features of the model must match the '
'input. Model n_features is %s and input '
'n_features is %s.'
% (self.n_features_in_, n_features))
X_new = np.array([gp.execute(X) for gp in self._best_programs]).T
return X_new
def fit_transform(self, X, y, sample_weight=None):
"""Fit to data, then transform it.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
sample_weight : array-like, shape = [n_samples], optional
Weights applied to individual samples.
Returns
-------
X_new : array-like, shape = [n_samples, n_components]
Transformed array.
"""
return self.fit(X, y, sample_weight).transform(X)
|