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
|
# Author: Leland McInnes <leland.mcinnes@gmail.com>
#
# License: BSD 2 clause
from warnings import warn
import locale
import numpy as np
import numba
import scipy.sparse
from pynndescent.sparse import (
sparse_mul,
sparse_diff,
sparse_sum,
arr_intersect,
sparse_dot_product,
)
from pynndescent.utils import tau_rand_int, norm
import joblib
from collections import namedtuple
locale.setlocale(locale.LC_NUMERIC, "C")
# Used for a floating point "nearly zero" comparison
EPS = 1e-8
INT32_MIN = np.iinfo(np.int32).min + 1
INT32_MAX = np.iinfo(np.int32).max - 1
FlatTree = namedtuple(
"FlatTree", ["hyperplanes", "offsets", "children", "indices", "leaf_size"]
)
dense_hyperplane_type = numba.float32[::1]
sparse_hyperplane_type = numba.float64[:, ::1]
offset_type = numba.float64
children_type = numba.typeof((np.int32(-1), np.int32(-1)))
point_indices_type = numba.int32[::1]
@numba.njit(
numba.types.Tuple(
(numba.int32[::1], numba.int32[::1], dense_hyperplane_type, offset_type)
)(numba.float32[:, ::1], numba.int32[::1], numba.int64[::1]),
locals={
"n_left": numba.uint32,
"n_right": numba.uint32,
"hyperplane_vector": numba.float32[::1],
"hyperplane_offset": numba.float32,
"margin": numba.float32,
"d": numba.uint32,
"i": numba.uint32,
"left_index": numba.uint32,
"right_index": numba.uint32,
},
fastmath=True,
nogil=True,
cache=True,
)
def angular_random_projection_split(data, indices, rng_state):
"""Given a set of ``graph_indices`` for graph_data points from ``graph_data``, create
a random hyperplane to split the graph_data, returning two arrays graph_indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simply uses this splitting recursively.
This particular split uses cosine distance to determine the hyperplane
and which side each graph_data sample falls on.
Parameters
----------
data: array of shape (n_samples, n_features)
The original graph_data to be split
indices: array of shape (tree_node_size,)
The graph_indices of the elements in the ``graph_data`` array that are to
be split in the current operation.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
indices_left: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
indices_right: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
"""
dim = data.shape[1]
# Select two random points, set the hyperplane between them
left_index = tau_rand_int(rng_state) % indices.shape[0]
right_index = tau_rand_int(rng_state) % indices.shape[0]
right_index += left_index == right_index
right_index = right_index % indices.shape[0]
left = indices[left_index]
right = indices[right_index]
left_norm = norm(data[left])
right_norm = norm(data[right])
if abs(left_norm) < EPS:
left_norm = 1.0
if abs(right_norm) < EPS:
right_norm = 1.0
# Compute the normal vector to the hyperplane (the vector between
# the two points)
hyperplane_vector = np.empty(dim, dtype=np.float32)
for d in range(dim):
hyperplane_vector[d] = (data[left, d] / left_norm) - (
data[right, d] / right_norm
)
hyperplane_norm = norm(hyperplane_vector)
if abs(hyperplane_norm) < EPS:
hyperplane_norm = 1.0
for d in range(dim):
hyperplane_vector[d] = hyperplane_vector[d] / hyperplane_norm
# For each point compute the margin (project into normal vector)
# If we are on lower side of the hyperplane put in one pile, otherwise
# put it in the other pile (if we hit hyperplane on the nose, flip a coin)
n_left = 0
n_right = 0
side = np.empty(indices.shape[0], np.int8)
for i in range(indices.shape[0]):
margin = 0.0
for d in range(dim):
margin += hyperplane_vector[d] * data[indices[i], d]
if abs(margin) < EPS:
side[i] = tau_rand_int(rng_state) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
elif margin > 0:
side[i] = 0
n_left += 1
else:
side[i] = 1
n_right += 1
# If all points end up on one side, something went wrong numerically
# In this case, assign points randomly; they are likely very close anyway
if n_left == 0 or n_right == 0:
n_left = 0
n_right = 0
for i in range(indices.shape[0]):
side[i] = tau_rand_int(rng_state) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
# Now that we have the counts allocate arrays
indices_left = np.empty(n_left, dtype=np.int32)
indices_right = np.empty(n_right, dtype=np.int32)
# Populate the arrays with graph_indices according to which side they fell on
n_left = 0
n_right = 0
for i in range(side.shape[0]):
if side[i] == 0:
indices_left[n_left] = indices[i]
n_left += 1
else:
indices_right[n_right] = indices[i]
n_right += 1
return indices_left, indices_right, hyperplane_vector, 0.0
@numba.njit(
numba.types.Tuple(
(numba.int32[::1], numba.int32[::1], dense_hyperplane_type, offset_type)
)(numba.float32[:, ::1], numba.int32[::1], numba.int64[::1]),
locals={
"n_left": numba.uint32,
"n_right": numba.uint32,
"hyperplane_vector": numba.float32[::1],
"hyperplane_offset": numba.float32,
"margin": numba.float32,
"d": numba.uint32,
"i": numba.uint32,
"left_index": numba.uint32,
"right_index": numba.uint32,
},
fastmath=True,
nogil=True,
cache=True,
)
def euclidean_random_projection_split(data, indices, rng_state):
"""Given a set of ``graph_indices`` for graph_data points from ``graph_data``, create
a random hyperplane to split the graph_data, returning two arrays graph_indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simply uses this splitting recursively.
This particular split uses euclidean distance to determine the hyperplane
and which side each graph_data sample falls on.
Parameters
----------
data: array of shape (n_samples, n_features)
The original graph_data to be split
indices: array of shape (tree_node_size,)
The graph_indices of the elements in the ``graph_data`` array that are to
be split in the current operation.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
indices_left: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
indices_right: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
"""
dim = data.shape[1]
# Select two random points, set the hyperplane between them
left_index = tau_rand_int(rng_state) % indices.shape[0]
right_index = tau_rand_int(rng_state) % indices.shape[0]
right_index += left_index == right_index
right_index = right_index % indices.shape[0]
left = indices[left_index]
right = indices[right_index]
# Compute the normal vector to the hyperplane (the vector between
# the two points) and the offset from the origin
hyperplane_offset = 0.0
hyperplane_vector = np.empty(dim, dtype=np.float32)
for d in range(dim):
hyperplane_vector[d] = data[left, d] - data[right, d]
hyperplane_offset -= (
hyperplane_vector[d] * (data[left, d] + data[right, d]) / 2.0
)
# For each point compute the margin (project into normal vector, add offset)
# If we are on lower side of the hyperplane put in one pile, otherwise
# put it in the other pile (if we hit hyperplane on the nose, flip a coin)
n_left = 0
n_right = 0
side = np.empty(indices.shape[0], np.int8)
for i in range(indices.shape[0]):
margin = hyperplane_offset
for d in range(dim):
margin += hyperplane_vector[d] * data[indices[i], d]
if abs(margin) < EPS:
side[i] = abs(tau_rand_int(rng_state)) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
elif margin > 0:
side[i] = 0
n_left += 1
else:
side[i] = 1
n_right += 1
# If all points end up on one side, something went wrong numerically
# In this case, assign points randomly; they are likely very close anyway
if n_left == 0 or n_right == 0:
n_left = 0
n_right = 0
for i in range(indices.shape[0]):
side[i] = tau_rand_int(rng_state) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
# Now that we have the counts allocate arrays
indices_left = np.empty(n_left, dtype=np.int32)
indices_right = np.empty(n_right, dtype=np.int32)
# Populate the arrays with graph_indices according to which side they fell on
n_left = 0
n_right = 0
for i in range(side.shape[0]):
if side[i] == 0:
indices_left[n_left] = indices[i]
n_left += 1
else:
indices_right[n_right] = indices[i]
n_right += 1
return indices_left, indices_right, hyperplane_vector, hyperplane_offset
@numba.njit(
fastmath=True,
nogil=True,
cache=True,
locals={
"normalized_left_data": numba.types.float32[::1],
"normalized_right_data": numba.types.float32[::1],
"hyperplane_norm": numba.types.float32,
"i": numba.types.uint32,
},
)
def sparse_angular_random_projection_split(inds, indptr, data, indices, rng_state):
"""Given a set of ``graph_indices`` for graph_data points from a sparse graph_data set
presented in csr sparse format as inds, graph_indptr and graph_data, create
a random hyperplane to split the graph_data, returning two arrays graph_indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simply uses this splitting recursively.
This particular split uses cosine distance to determine the hyperplane
and which side each graph_data sample falls on.
Parameters
----------
inds: array
CSR format index array of the matrix
indptr: array
CSR format index pointer array of the matrix
data: array
CSR format graph_data array of the matrix
indices: array of shape (tree_node_size,)
The graph_indices of the elements in the ``graph_data`` array that are to
be split in the current operation.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
indices_left: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
indices_right: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
"""
# Select two random points, set the hyperplane between them
left_index = tau_rand_int(rng_state) % indices.shape[0]
right_index = tau_rand_int(rng_state) % indices.shape[0]
right_index += left_index == right_index
right_index = right_index % indices.shape[0]
left = indices[left_index]
right = indices[right_index]
left_inds = inds[indptr[left] : indptr[left + 1]]
left_data = data[indptr[left] : indptr[left + 1]]
right_inds = inds[indptr[right] : indptr[right + 1]]
right_data = data[indptr[right] : indptr[right + 1]]
left_norm = norm(left_data)
right_norm = norm(right_data)
if abs(left_norm) < EPS:
left_norm = 1.0
if abs(right_norm) < EPS:
right_norm = 1.0
# Compute the normal vector to the hyperplane (the vector between
# the two points)
normalized_left_data = (left_data / left_norm).astype(np.float32)
normalized_right_data = (right_data / right_norm).astype(np.float32)
hyperplane_inds, hyperplane_data = sparse_diff(
left_inds, normalized_left_data, right_inds, normalized_right_data
)
hyperplane_norm = norm(hyperplane_data)
if abs(hyperplane_norm) < EPS:
hyperplane_norm = 1.0
for d in range(hyperplane_data.shape[0]):
hyperplane_data[d] = hyperplane_data[d] / hyperplane_norm
# For each point compute the margin (project into normal vector)
# If we are on lower side of the hyperplane put in one pile, otherwise
# put it in the other pile (if we hit hyperplane on the nose, flip a coin)
n_left = 0
n_right = 0
side = np.empty(indices.shape[0], np.int8)
for i in range(indices.shape[0]):
margin = 0.0
i_inds = inds[indptr[indices[i]] : indptr[indices[i] + 1]]
i_data = data[indptr[indices[i]] : indptr[indices[i] + 1]]
_, mul_data = sparse_mul(hyperplane_inds, hyperplane_data, i_inds, i_data)
for val in mul_data:
margin += val
if abs(margin) < EPS:
side[i] = tau_rand_int(rng_state) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
elif margin > 0:
side[i] = 0
n_left += 1
else:
side[i] = 1
n_right += 1
# If all points end up on one side, something went wrong numerically
# In this case, assign points randomly; they are likely very close anyway
if n_left == 0 or n_right == 0:
n_left = 0
n_right = 0
for i in range(indices.shape[0]):
side[i] = tau_rand_int(rng_state) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
# Now that we have the counts allocate arrays
indices_left = np.empty(n_left, dtype=np.int32)
indices_right = np.empty(n_right, dtype=np.int32)
# Populate the arrays with graph_indices according to which side they fell on
n_left = 0
n_right = 0
for i in range(side.shape[0]):
if side[i] == 0:
indices_left[n_left] = indices[i]
n_left += 1
else:
indices_right[n_right] = indices[i]
n_right += 1
hyperplane = np.vstack((hyperplane_inds, hyperplane_data))
return indices_left, indices_right, hyperplane, 0.0
@numba.njit(fastmath=True, nogil=True, cache=True)
def sparse_euclidean_random_projection_split(inds, indptr, data, indices, rng_state):
"""Given a set of ``graph_indices`` for graph_data points from a sparse graph_data set
presented in csr sparse format as inds, graph_indptr and graph_data, create
a random hyperplane to split the graph_data, returning two arrays graph_indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simply uses this splitting recursively.
This particular split uses cosine distance to determine the hyperplane
and which side each graph_data sample falls on.
Parameters
----------
inds: array
CSR format index array of the matrix
indptr: array
CSR format index pointer array of the matrix
data: array
CSR format graph_data array of the matrix
indices: array of shape (tree_node_size,)
The graph_indices of the elements in the ``graph_data`` array that are to
be split in the current operation.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
indices_left: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
indices_right: array
The elements of ``graph_indices`` that fall on the "left" side of the
random hyperplane.
"""
# Select two random points, set the hyperplane between them
left_index = np.abs(tau_rand_int(rng_state)) % indices.shape[0]
right_index = np.abs(tau_rand_int(rng_state)) % indices.shape[0]
right_index += left_index == right_index
right_index = right_index % indices.shape[0]
left = indices[left_index]
right = indices[right_index]
left_inds = inds[indptr[left] : indptr[left + 1]]
left_data = data[indptr[left] : indptr[left + 1]]
right_inds = inds[indptr[right] : indptr[right + 1]]
right_data = data[indptr[right] : indptr[right + 1]]
# Compute the normal vector to the hyperplane (the vector between
# the two points) and the offset from the origin
hyperplane_offset = 0.0
hyperplane_inds, hyperplane_data = sparse_diff(
left_inds, left_data, right_inds, right_data
)
offset_inds, offset_data = sparse_sum(left_inds, left_data, right_inds, right_data)
offset_data = offset_data / 2.0
offset_inds, offset_data = sparse_mul(
hyperplane_inds, hyperplane_data, offset_inds, offset_data.astype(np.float32)
)
for val in offset_data:
hyperplane_offset -= val
# For each point compute the margin (project into normal vector, add offset)
# If we are on lower side of the hyperplane put in one pile, otherwise
# put it in the other pile (if we hit hyperplane on the nose, flip a coin)
n_left = 0
n_right = 0
side = np.empty(indices.shape[0], np.int8)
for i in range(indices.shape[0]):
margin = hyperplane_offset
i_inds = inds[indptr[indices[i]] : indptr[indices[i] + 1]]
i_data = data[indptr[indices[i]] : indptr[indices[i] + 1]]
_, mul_data = sparse_mul(hyperplane_inds, hyperplane_data, i_inds, i_data)
for val in mul_data:
margin += val
if abs(margin) < EPS:
side[i] = abs(tau_rand_int(rng_state)) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
elif margin > 0:
side[i] = 0
n_left += 1
else:
side[i] = 1
n_right += 1
# If all points end up on one side, something went wrong numerically
# In this case, assign points randomly; they are likely very close anyway
if n_left == 0 or n_right == 0:
n_left = 0
n_right = 0
for i in range(indices.shape[0]):
side[i] = abs(tau_rand_int(rng_state)) % 2
if side[i] == 0:
n_left += 1
else:
n_right += 1
# Now that we have the counts allocate arrays
indices_left = np.empty(n_left, dtype=np.int32)
indices_right = np.empty(n_right, dtype=np.int32)
# Populate the arrays with graph_indices according to which side they fell on
n_left = 0
n_right = 0
for i in range(side.shape[0]):
if side[i] == 0:
indices_left[n_left] = indices[i]
n_left += 1
else:
indices_right[n_right] = indices[i]
n_right += 1
hyperplane = np.vstack((hyperplane_inds, hyperplane_data))
return indices_left, indices_right, hyperplane, hyperplane_offset
@numba.njit(
nogil=True,
locals={"left_node_num": numba.types.int32, "right_node_num": numba.types.int32},
)
def make_euclidean_tree(
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size=30,
max_depth=200,
):
if indices.shape[0] > leaf_size and max_depth > 0:
(
left_indices,
right_indices,
hyperplane,
offset,
) = euclidean_random_projection_split(data, indices, rng_state)
make_euclidean_tree(
data,
left_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
left_node_num = len(point_indices) - 1
make_euclidean_tree(
data,
right_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
right_node_num = len(point_indices) - 1
hyperplanes.append(hyperplane)
offsets.append(offset)
children.append((np.int32(left_node_num), np.int32(right_node_num)))
point_indices.append(np.array([-1], dtype=np.int32))
else:
hyperplanes.append(np.array([-1.0], dtype=np.float32))
offsets.append(-np.inf)
children.append((np.int32(-1), np.int32(-1)))
point_indices.append(indices)
return
@numba.njit(
nogil=True,
locals={
"children": numba.types.ListType(children_type),
"left_node_num": numba.types.int32,
"right_node_num": numba.types.int32,
},
)
def make_angular_tree(
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size=30,
max_depth=200,
):
if indices.shape[0] > leaf_size and max_depth > 0:
(
left_indices,
right_indices,
hyperplane,
offset,
) = angular_random_projection_split(data, indices, rng_state)
make_angular_tree(
data,
left_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
left_node_num = len(point_indices) - 1
make_angular_tree(
data,
right_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
right_node_num = len(point_indices) - 1
hyperplanes.append(hyperplane)
offsets.append(offset)
children.append((np.int32(left_node_num), np.int32(right_node_num)))
point_indices.append(np.array([-1], dtype=np.int32))
else:
hyperplanes.append(np.array([-1.0], dtype=np.float32))
offsets.append(-np.inf)
children.append((np.int32(-1), np.int32(-1)))
point_indices.append(indices)
return
@numba.njit(
nogil=True,
locals={"left_node_num": numba.types.int32, "right_node_num": numba.types.int32},
)
def make_sparse_euclidean_tree(
inds,
indptr,
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size=30,
max_depth=200,
):
if indices.shape[0] > leaf_size and max_depth > 0:
(
left_indices,
right_indices,
hyperplane,
offset,
) = sparse_euclidean_random_projection_split(
inds, indptr, data, indices, rng_state
)
make_sparse_euclidean_tree(
inds,
indptr,
data,
left_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
left_node_num = len(point_indices) - 1
make_sparse_euclidean_tree(
inds,
indptr,
data,
right_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
right_node_num = len(point_indices) - 1
hyperplanes.append(hyperplane)
offsets.append(offset)
children.append((np.int32(left_node_num), np.int32(right_node_num)))
point_indices.append(np.array([-1], dtype=np.int32))
else:
hyperplanes.append(np.array([[-1.0], [-1.0]], dtype=np.float64))
offsets.append(-np.inf)
children.append((np.int32(-1), np.int32(-1)))
point_indices.append(indices)
return
@numba.njit(
nogil=True,
locals={"left_node_num": numba.types.int32, "right_node_num": numba.types.int32},
)
def make_sparse_angular_tree(
inds,
indptr,
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size=30,
max_depth=200,
):
if indices.shape[0] > leaf_size and max_depth > 0:
(
left_indices,
right_indices,
hyperplane,
offset,
) = sparse_angular_random_projection_split(
inds, indptr, data, indices, rng_state
)
make_sparse_angular_tree(
inds,
indptr,
data,
left_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
left_node_num = len(point_indices) - 1
make_sparse_angular_tree(
inds,
indptr,
data,
right_indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth - 1,
)
right_node_num = len(point_indices) - 1
hyperplanes.append(hyperplane)
offsets.append(offset)
children.append((np.int32(left_node_num), np.int32(right_node_num)))
point_indices.append(np.array([-1], dtype=np.int32))
else:
hyperplanes.append(np.array([[-1.0], [-1.0]], dtype=np.float64))
offsets.append(-np.inf)
children.append((np.int32(-1), np.int32(-1)))
point_indices.append(indices)
@numba.njit(nogil=True)
def make_dense_tree(data, rng_state, leaf_size=30, angular=False, max_depth=200):
indices = np.arange(data.shape[0]).astype(np.int32)
hyperplanes = numba.typed.List.empty_list(dense_hyperplane_type)
offsets = numba.typed.List.empty_list(offset_type)
children = numba.typed.List.empty_list(children_type)
point_indices = numba.typed.List.empty_list(point_indices_type)
if angular:
make_angular_tree(
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth=max_depth,
)
else:
make_euclidean_tree(
data,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth=max_depth,
)
max_leaf_size = leaf_size
for points in point_indices:
if len(points) > max_leaf_size:
max_leaf_size = numba.int32(len(points))
result = FlatTree(hyperplanes, offsets, children, point_indices, max_leaf_size)
return result
@numba.njit(nogil=True)
def make_sparse_tree(
inds,
indptr,
spdata,
rng_state,
leaf_size=30,
angular=False,
max_depth=200,
):
indices = np.arange(indptr.shape[0] - 1).astype(np.int32)
hyperplanes = numba.typed.List.empty_list(sparse_hyperplane_type)
offsets = numba.typed.List.empty_list(offset_type)
children = numba.typed.List.empty_list(children_type)
point_indices = numba.typed.List.empty_list(point_indices_type)
if angular:
make_sparse_angular_tree(
inds,
indptr,
spdata,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth=max_depth,
)
else:
make_sparse_euclidean_tree(
inds,
indptr,
spdata,
indices,
hyperplanes,
offsets,
children,
point_indices,
rng_state,
leaf_size,
max_depth=max_depth,
)
max_leaf_size = leaf_size
for points in point_indices:
if len(points) > max_leaf_size:
max_leaf_size = numba.int32(len(points))
return FlatTree(hyperplanes, offsets, children, point_indices, max_leaf_size)
@numba.njit(
[
"b1(f4[::1],f4,f4[::1],i8[::1])",
numba.types.boolean(
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
numba.types.float32,
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
numba.types.Array(numba.types.int64, 1, "C", readonly=False),
),
],
fastmath=True,
locals={
"margin": numba.types.float32,
"dim": numba.types.intp,
"d": numba.types.uint16,
},
cache=True,
)
def select_side(hyperplane, offset, point, rng_state):
margin = offset
dim = point.shape[0]
for d in range(dim):
margin += hyperplane[d] * point[d]
if abs(margin) < EPS:
side = np.abs(tau_rand_int(rng_state)) % 2
if side == 0:
return 0
else:
return 1
elif margin > 0:
return 0
else:
return 1
@numba.njit(
[
"i4[::1](f4[::1],f4[:,::1],f4[::1],i4[:,::1],i4[::1],i8[::1])",
numba.types.Array(numba.types.int32, 1, "C", readonly=True)(
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
numba.types.Array(numba.types.float32, 2, "C", readonly=True),
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
numba.types.Array(numba.types.int32, 2, "C", readonly=True),
numba.types.Array(numba.types.int32, 1, "C", readonly=True),
numba.types.Array(numba.types.int64, 1, "C", readonly=False),
),
],
locals={"node": numba.types.uint32, "side": numba.types.boolean},
cache=True,
)
def search_flat_tree(point, hyperplanes, offsets, children, indices, rng_state):
node = 0
while children[node, 0] > 0:
side = select_side(hyperplanes[node], offsets[node], point, rng_state)
if side == 0:
node = children[node, 0]
else:
node = children[node, 1]
return indices[-children[node, 0] : -children[node, 1]]
@numba.njit(fastmath=True, cache=True)
def sparse_select_side(hyperplane, offset, point_inds, point_data, rng_state):
margin = offset
hyperplane_size = hyperplane.shape[1]
while hyperplane[0, hyperplane_size - 1] < 0.0:
hyperplane_size -= 1
hyperplane_inds = hyperplane[0, :hyperplane_size].astype(np.int32)
hyperplane_data = hyperplane[1, :hyperplane_size]
margin += sparse_dot_product(
hyperplane_inds, hyperplane_data, point_inds, point_data
)
if abs(margin) < EPS:
side = tau_rand_int(rng_state) % 2
if side == 0:
return 0
else:
return 1
elif margin > 0:
return 0
else:
return 1
@numba.njit(locals={"node": numba.types.uint32}, cache=True)
def search_sparse_flat_tree(
point_inds, point_data, hyperplanes, offsets, children, indices, rng_state
):
node = 0
while children[node, 0] > 0:
side = sparse_select_side(
hyperplanes[node], offsets[node], point_inds, point_data, rng_state
)
if side == 0:
node = children[node, 0]
else:
node = children[node, 1]
return indices[-children[node, 0] : -children[node, 1]]
def make_forest(
data,
n_neighbors,
n_trees,
leaf_size,
rng_state,
random_state,
n_jobs=None,
angular=False,
max_depth=200,
):
"""Build a random projection forest with ``n_trees``.
Parameters
----------
data
n_neighbors
n_trees
leaf_size
rng_state
angular
Returns
-------
forest: list
A list of random projection trees.
"""
# print(ts(), "Started forest construction")
result = []
if leaf_size is None:
leaf_size = max(10, np.int32(n_neighbors))
if n_jobs is None:
n_jobs = -1
rng_states = random_state.randint(INT32_MIN, INT32_MAX, size=(n_trees, 3)).astype(
np.int64
)
try:
if scipy.sparse.isspmatrix_csr(data):
result = joblib.Parallel(n_jobs=n_jobs, require="sharedmem")(
joblib.delayed(make_sparse_tree)(
data.indices,
data.indptr,
data.data,
rng_states[i],
leaf_size,
angular,
max_depth=max_depth,
)
for i in range(n_trees)
)
else:
result = joblib.Parallel(n_jobs=n_jobs, require="sharedmem")(
joblib.delayed(make_dense_tree)(
data,
rng_states[i],
leaf_size,
angular,
max_depth=max_depth
)
for i in range(n_trees)
)
except (RuntimeError, RecursionError, SystemError):
warn(
"Random Projection forest initialisation failed due to recursion"
"limit being reached. Something is a little strange with your "
"graph_data, and this may take longer than normal to compute."
)
return tuple(result)
@numba.njit(nogil=True)
def get_leaves_from_tree(tree, max_leaf_size):
n_leaves = 0
for i in range(len(tree.children)):
if tree.children[i][0] == -1 and tree.children[i][1] == -1:
n_leaves += 1
result = np.full((n_leaves, max_leaf_size), -1, dtype=np.int32)
leaf_index = 0
for i in range(len(tree.indices)):
if tree.children[i][0] == -1 or tree.children[i][1] == -1:
leaf_size = tree.indices[i].shape[0]
result[leaf_index, :leaf_size] = tree.indices[i]
leaf_index += 1
return result
def rptree_leaf_array_parallel(rp_forest):
max_leaf_size = np.max([rp_tree.leaf_size for rp_tree in rp_forest])
result = joblib.Parallel(n_jobs=-1, require="sharedmem")(
joblib.delayed(get_leaves_from_tree)(rp_tree, max_leaf_size) for rp_tree in rp_forest
)
return result
def rptree_leaf_array(rp_forest):
if len(rp_forest) > 0:
return np.vstack(rptree_leaf_array_parallel(rp_forest))
else:
return np.array([[-1]])
@numba.njit()
def recursive_convert(
tree, hyperplanes, offsets, children, indices, node_num, leaf_start, tree_node
):
if tree.children[tree_node][0] < 0:
leaf_end = leaf_start + len(tree.indices[tree_node])
children[node_num, 0] = -leaf_start
children[node_num, 1] = -leaf_end
indices[leaf_start:leaf_end] = tree.indices[tree_node]
return node_num, leaf_end
else:
hyperplanes[node_num] = tree.hyperplanes[tree_node]
offsets[node_num] = tree.offsets[tree_node]
children[node_num, 0] = node_num + 1
old_node_num = node_num
node_num, leaf_start = recursive_convert(
tree,
hyperplanes,
offsets,
children,
indices,
node_num + 1,
leaf_start,
tree.children[tree_node][0],
)
children[old_node_num, 1] = node_num + 1
node_num, leaf_start = recursive_convert(
tree,
hyperplanes,
offsets,
children,
indices,
node_num + 1,
leaf_start,
tree.children[tree_node][1],
)
return node_num, leaf_start
@numba.njit()
def recursive_convert_sparse(
tree, hyperplanes, offsets, children, indices, node_num, leaf_start, tree_node
):
if tree.children[tree_node][0] < 0:
leaf_end = leaf_start + len(tree.indices[tree_node])
children[node_num, 0] = -leaf_start
children[node_num, 1] = -leaf_end
indices[leaf_start:leaf_end] = tree.indices[tree_node]
return node_num, leaf_end
else:
hyperplanes[
node_num, :, : tree.hyperplanes[tree_node].shape[1]
] = tree.hyperplanes[tree_node]
offsets[node_num] = tree.offsets[tree_node]
children[node_num, 0] = node_num + 1
old_node_num = node_num
node_num, leaf_start = recursive_convert_sparse(
tree,
hyperplanes,
offsets,
children,
indices,
node_num + 1,
leaf_start,
tree.children[tree_node][0],
)
children[old_node_num, 1] = node_num + 1
node_num, leaf_start = recursive_convert_sparse(
tree,
hyperplanes,
offsets,
children,
indices,
node_num + 1,
leaf_start,
tree.children[tree_node][1],
)
return node_num, leaf_start
@numba.njit(cache=True)
def num_nodes_and_leaves(tree):
n_nodes = 0
n_leaves = 0
for i in range(len(tree.children)):
if tree.children[i][0] < 0:
n_leaves += 1
n_nodes += 1
else:
n_nodes += 1
return n_nodes, n_leaves
def convert_tree_format(tree, data_size, data_dim):
n_nodes, n_leaves = num_nodes_and_leaves(tree)
is_sparse = False
if tree.hyperplanes[0].ndim == 1:
# dense hyperplanes
hyperplane_dim = data_dim
hyperplanes = np.zeros((n_nodes, hyperplane_dim), dtype=np.float32)
else:
# sparse hyperplanes
is_sparse = True
hyperplane_dim = data_dim
hyperplanes = np.zeros((n_nodes, 2, hyperplane_dim), dtype=np.float32)
hyperplanes[:, 0, :] = -1
offsets = np.zeros(n_nodes, dtype=np.float32)
children = np.int32(-1) * np.ones((n_nodes, 2), dtype=np.int32)
indices = np.int32(-1) * np.ones(data_size, dtype=np.int32)
if is_sparse:
recursive_convert_sparse(
tree, hyperplanes, offsets, children, indices, 0, 0, len(tree.children) - 1
)
else:
recursive_convert(
tree, hyperplanes, offsets, children, indices, 0, 0, len(tree.children) - 1
)
return FlatTree(hyperplanes, offsets, children, indices, tree.leaf_size)
# Indices for tuple version of flat tree for pickle serialization
FLAT_TREE_HYPERPLANES = 0
FLAT_TREE_OFFSETS = 1
FLAT_TREE_CHILDREN = 2
FLAT_TREE_INDICES = 3
FLAT_TREE_LEAF_SIZE = 4
def denumbaify_tree(tree):
result = (
tree.hyperplanes,
tree.offsets,
tree.children,
tree.indices,
tree.leaf_size,
)
return result
def renumbaify_tree(tree):
result = FlatTree(
tree[FLAT_TREE_HYPERPLANES],
tree[FLAT_TREE_OFFSETS],
tree[FLAT_TREE_CHILDREN],
tree[FLAT_TREE_INDICES],
tree[FLAT_TREE_LEAF_SIZE],
)
return result
@numba.njit(
parallel=True,
locals={
"intersection": numba.int64[::1],
"result": numba.float32,
"i": numba.uint32,
},
cache=False,
)
def score_tree(tree, neighbor_indices, data, rng_state):
result = 0.0
for i in numba.prange(neighbor_indices.shape[0]):
leaf_indices = search_flat_tree(
data[i],
tree.hyperplanes,
tree.offsets,
tree.children,
tree.indices,
rng_state,
)
intersection = arr_intersect(neighbor_indices[i], leaf_indices)
result += numba.float32(intersection.shape[0] > 1)
return result / numba.float32(neighbor_indices.shape[0])
@numba.njit(nogil=True, locals={"node": numba.int32}, cache=False)
def score_linked_tree(tree, neighbor_indices):
result = 0.0
n_nodes = len(tree.children)
for i in range(n_nodes):
node = numba.int32(i)
left_child = tree.children[node][0]
right_child = tree.children[node][1]
if left_child == -1 and right_child == -1:
for j in range(tree.indices[node].shape[0]):
idx = tree.indices[node][j]
intersection = arr_intersect(neighbor_indices[idx], tree.indices[node])
result += numba.float32(intersection.shape[0] > 1)
return result / numba.float32(neighbor_indices.shape[0])
|