File size: 29,207 Bytes
7718235 |
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 |
import argparse
import numpy as np
import torch
import yaml
class LoadFromFile(argparse.Action):
# parser.add_argument('--file', type=open, action=LoadFromFile)
def __call__(self, parser, namespace, values, option_string=None):
if values.name.endswith("yaml") or values.name.endswith("yml"):
with values as f:
config = yaml.load(f, Loader=yaml.FullLoader)
for key in config.keys():
if key not in namespace:
raise ValueError(f"Unknown argument in config file: {key}")
if (
"load_model" in config
and namespace.load_model is not None
and config["load_model"] != namespace.load_model
):
Warning(
f"The load model argument was specified as a command line argument "
f"({namespace.load_model}) and in the config file ({config['load_model']}). "
f"Ignoring 'load_model' from the config file and loading {namespace.load_model}."
)
del config["load_model"]
namespace.__dict__.update(config)
else:
raise ValueError("Configuration file must end with yaml or yml")
# TODO: for all functions, shuffle in a way that guarantee the same batch does not contain same protein.
def train_val_test_split(dset_len, train_size, val_size, test_size, seed, order=None):
assert (train_size is None) + (val_size is None) + (
test_size is None
) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
isinstance(test_size, float),
)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
test_size = round(dset_len * test_size) if is_float[2] else test_size
if train_size is None:
train_size = dset_len - val_size - test_size
elif val_size is None:
val_size = dset_len - train_size - test_size
elif test_size is None:
test_size = dset_len - train_size - val_size
if train_size + val_size + test_size > dset_len:
if is_float[2]:
test_size -= 1
elif is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0 and test_size >= 0, (
f"One of training ({train_size}), validation ({val_size}) or "
f"testing ({test_size}) splits ended up with a negative size."
)
total = train_size + val_size + test_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
idxs = np.arange(dset_len, dtype=np.int)
if order is None:
idxs = np.random.default_rng(seed).permutation(idxs)
idx_train = idxs[:train_size]
idx_val = idxs[train_size: train_size + val_size]
idx_test = idxs[train_size + val_size: total]
if order is not None:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
idx_test = [order[i] for i in idx_test]
return np.array(idx_train), np.array(idx_val), np.array(idx_test)
def make_splits_train_val_test(
dataset_len,
train_size,
val_size,
test_size,
seed,
filename=None,
splits=None,
order=None,
):
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
idx_test = splits["idx_test"]
else:
idx_train, idx_val, idx_test = train_val_test_split(
dataset_len, train_size, val_size, test_size, seed, order
)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val, idx_test=idx_test)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
torch.from_numpy(idx_test),
)
def train_val_split(dset_len, train_size, val_size, seed, order=None):
assert (train_size is None) + (
val_size is None) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
)
# dset_len: int = len(dset)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
if train_size is None:
train_size = dset_len - val_size
elif val_size is None:
val_size = dset_len - train_size
if train_size + val_size > dset_len:
if is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0, (
f"One of training ({train_size}), validation ({val_size})"
f" splits ended up with a negative size."
)
total = train_size + val_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
idxs = np.arange(dset_len, dtype=np.int)
if order is None:
idxs = np.random.default_rng(seed).permutation(idxs)
idx_train = idxs[:train_size]
idx_val = idxs[train_size: total]
if order is not None:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
return np.array(idx_train), np.array(idx_val)
def make_splits_train_val(
dset,
train_size,
val_size,
seed,
batch_size=48, # unused
filename=None,
splits=None,
order=None,
):
dset_len = len(dset)
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
else:
idx_train, idx_val = train_val_split(dset_len, train_size, val_size, seed, order)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
)
def make_splits_train_val_by_anno(
dset,
train_size,
val_size,
seed,
batch_size=48, # unused
filename=None,
splits=None,
order=None,
):
dset_len = len(dset)
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
else:
idx_train = np.where(dset.data['split'] == 'train')[0]
idx_val = np.where(dset.data['split'] == 'val')[0]
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
)
def train_val_split_by_uniprot_id(dset, train_size, val_size, seed, batch_size=48, order=None):
assert (train_size is None) + (
val_size is None) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
)
dset_len: int = len(dset)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
if train_size is None:
train_size = dset_len - val_size
elif val_size is None:
val_size = dset_len - train_size
if train_size + val_size > dset_len:
if is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0, (
f"One of training ({train_size}), validation ({val_size})"
f" splits ended up with a negative size."
)
total = train_size + val_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
uniprot_freq_table = dset.data.uniprotID.value_counts()
selected_val_uniprotIDs, _ = select_by_uniprot(uniprot_freq_table, val_size)
idxs = np.arange(dset_len, dtype=np.int)
idx_train = idxs[np.isin(dset.data.uniprotID, selected_val_uniprotIDs, invert=True)]
idx_val = idxs[np.isin(dset.data.uniprotID, selected_val_uniprotIDs)]
if order is None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
idx_val = np.random.default_rng(seed).permutation(idx_val)
idx_train = guarantee_no_same_protein_in_one_batch(
idx_train, batch_size, np.array(dset.data.uniprotID.iloc[idx_train] + dset.data.ENST.iloc[idx_train])
)
idx_val = guarantee_no_same_protein_in_one_batch(
idx_val, batch_size, np.array(dset.data.uniprotID.iloc[idx_val] + dset.data.ENST.iloc[idx_val])
)
else:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
return np.array(idx_train), np.array(idx_val)
def make_splits_train_val_by_uniprot_id(
dset,
train_size,
val_size,
seed,
batch_size=48,
filename=None,
splits=None,
order=None,
):
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
else:
idx_train, idx_val = train_val_split_by_uniprot_id(dset, train_size, val_size, seed, batch_size, order)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
)
def train_val_split_by_good_batch(dset, train_size, val_size, seed, batch_size=48, order=None):
assert (train_size is None) + (
val_size is None) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
)
dset_len: int = len(dset)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
if train_size is None:
train_size = dset_len - val_size
elif val_size is None:
val_size = dset_len - train_size
if train_size + val_size > dset_len:
if is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0, (
f"One of training ({train_size}), validation ({val_size})"
f" splits ended up with a negative size."
)
total = train_size + val_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
idxs = np.arange(dset_len, dtype=np.int)
if order is None:
idxs = np.random.default_rng(seed).permutation(idxs)
idx_train = idxs[:train_size]
idx_val = idxs[train_size: total]
if order is None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
idx_val = np.random.default_rng(seed).permutation(idx_val)
idx_train = guarantee_good_batch(idx_train, batch_size, dset)
else:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
return np.array(idx_train), np.array(idx_val)
def make_splits_train_val_by_good_batch(
dset,
train_size,
val_size,
seed,
batch_size=48,
filename=None,
splits=None,
order=None,
):
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
else:
idx_train, idx_val = train_val_split_by_good_batch(dset, train_size, val_size, seed, batch_size, order)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
)
def train_val_split_by_uniprot_id_good_batch(dset, train_size, val_size, seed, batch_size=48, order=None):
assert (train_size is None) + (
val_size is None) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
)
dset_len: int = len(dset)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
if train_size is None:
train_size = dset_len - val_size
elif val_size is None:
val_size = dset_len - train_size
if train_size + val_size > dset_len:
if is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0, (
f"One of training ({train_size}), validation ({val_size})"
f" splits ended up with a negative size."
)
total = train_size + val_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
uniprot_freq_table = dset.data.uniprotID.value_counts()
selected_val_uniprotIDs, _ = select_by_uniprot(uniprot_freq_table, val_size)
idxs = np.arange(dset_len, dtype=np.int)
idx_train = idxs[np.isin(dset.data.uniprotID, selected_val_uniprotIDs, invert=True)]
idx_val = idxs[np.isin(dset.data.uniprotID, selected_val_uniprotIDs)]
if order is None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
idx_val = np.random.default_rng(seed).permutation(idx_val)
idx_train = guarantee_good_batch(idx_train, batch_size, dset)
else:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
return np.array(idx_train), np.array(idx_val)
def make_splits_train_val_by_uniprot_id_good_batch(
dset,
train_size,
val_size,
seed,
batch_size=48,
filename=None,
splits=None,
order=None,
):
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
else:
idx_train, idx_val = train_val_split_by_uniprot_id_good_batch(dset, train_size, val_size, seed, batch_size, order)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
)
def train_val_test_split_by_uniprot_id(dset, train_size, val_size, test_size, seed, batch_size=48, order=None):
assert (train_size is None) + (val_size is None) + (
test_size is None
) <= 1, "Only one of train_size, val_size, test_size is allowed to be None."
is_float = (
isinstance(train_size, float),
isinstance(val_size, float),
isinstance(test_size, float),
)
dset_len: int = len(dset)
train_size = round(dset_len * train_size) if is_float[0] else train_size
val_size = round(dset_len * val_size) if is_float[1] else val_size
test_size = round(dset_len * test_size) if is_float[2] else test_size
if train_size is None:
train_size = dset_len - val_size - test_size
elif val_size is None:
val_size = dset_len - train_size - test_size
elif test_size is None:
test_size = dset_len - train_size - val_size
if train_size + val_size + test_size > dset_len:
if is_float[2]:
test_size -= 1
elif is_float[1]:
val_size -= 1
elif is_float[0]:
train_size -= 1
assert train_size >= 0 and val_size >= 0 and test_size >= 0, (
f"One of training ({train_size}), validation ({val_size}) or "
f"testing ({test_size}) splits ended up with a negative size."
)
total = train_size + val_size + test_size
assert dset_len >= total, (
f"The dataset ({dset_len}) is smaller than the "
f"combined split sizes ({total})."
)
if total < dset_len:
Warning(f"{dset_len - total} samples were excluded from the dataset")
uniprot_freq_table = dset.data.uniprotID.value_counts()
selected_test_uniprotIDs, uniprot_freq_table = select_by_uniprot(uniprot_freq_table, test_size)
selected_val_uniprotIDs, uniprot_freq_table = select_by_uniprot(uniprot_freq_table, val_size)
idxs = np.arange(dset_len, dtype=np.int)
idx_test = idxs[np.isin(dset.data.uniprotID, selected_test_uniprotIDs)]
idx_val = idxs[np.isin(dset.data.uniprotID, selected_val_uniprotIDs)]
idx_train = idxs[np.isin(dset.data.uniprotID, selected_test_uniprotIDs + selected_val_uniprotIDs, invert=True)]
if order is None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
idx_val = np.random.default_rng(seed).permutation(idx_val)
idx_test = np.random.default_rng(seed).permutation(idx_test)
idx_train = guarantee_no_same_protein_in_one_batch(
idx_train, batch_size, np.array(dset.data.uniprotID.iloc[idx_train] + dset.data.ENST.iloc[idx_train])
)
idx_val = guarantee_no_same_protein_in_one_batch(
idx_val, batch_size, np.array(dset.data.uniprotID.iloc[idx_val] + dset.data.ENST.iloc[idx_val])
)
idx_test = guarantee_no_same_protein_in_one_batch(
idx_test, batch_size, np.array(dset.data.uniprotID.iloc[idx_test] + dset.data.ENST.iloc[idx_test])
)
else:
idx_train = [order[i] for i in idx_train]
idx_val = [order[i] for i in idx_val]
idx_test = [order[i] for i in idx_test]
return np.array(idx_train), np.array(idx_val), np.array(idx_test)
def make_splits_train_val_test_by_uniprot_id(
dset,
train_size,
val_size,
test_size,
seed,
batch_size=48,
filename=None,
splits=None,
order=None,
):
if splits is not None:
splits = np.load(splits)
idx_train = splits["idx_train"]
idx_val = splits["idx_val"]
idx_test = splits["idx_test"]
else:
idx_train, idx_val, idx_test = train_val_test_split_by_uniprot_id(
dset, train_size, val_size, test_size, seed, batch_size, order
)
if filename is not None:
np.savez(filename, idx_train=idx_train, idx_val=idx_val, idx_test=idx_test)
return (
torch.from_numpy(idx_train),
torch.from_numpy(idx_val),
torch.from_numpy(idx_test),
)
def reshuffle_train_by_uniprot_id(idx_train, batch_size, dset, seed=None):
idx_train = guarantee_no_same_protein_in_one_batch(
idx_train, batch_size,
np.array(dset.data.uniprotID.iloc[idx_train] + dset.data.ENST.iloc[idx_train]),
seed=seed
)
return idx_train
def reshuffle_train_by_good_batch(idx_train, batch_size, dset, seed=None):
idx_train = guarantee_good_batch(
idx_train, batch_size, dset, seed=seed
)
return idx_train
def reshuffle_train_by_uniprot_id_good_batch(idx_train, batch_size, dset, seed=None):
return reshuffle_train_by_good_batch(idx_train, batch_size, dset, seed)
def reshuffle_train_by_anno(idx_train, batch_size, dset, seed=None):
if seed is not None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
else:
idx_train = np.random.permutation(idx_train)
return idx_train
def reshuffle_train(idx_train, batch_size, dset, seed=None):
if seed is not None:
idx_train = np.random.default_rng(seed).permutation(idx_train)
else:
idx_train = np.random.permutation(idx_train)
return idx_train
def select_by_uniprot(freq_table, number_to_select):
selected = 0
selected_uniprotIDs = []
candidates = freq_table[freq_table <= number_to_select - selected]
while selected < number_to_select and len(candidates) > 0:
selected_uniprotID = np.random.choice(candidates.index)
selected_uniprotIDs.append(selected_uniprotID)
selected += freq_table[selected_uniprotID]
# update freq_table and candidates
freq_table = freq_table.drop(selected_uniprotID)
candidates = freq_table[freq_table <= number_to_select - selected]
return selected_uniprotIDs, freq_table
def guarantee_no_same_protein_in_one_batch(idxs, batch_size, protein_identifiers, seed=0):
assert len(idxs) == len(protein_identifiers)
if seed is not None:
np.random.seed(seed)
# assume idxs and protein_identifiers are shuffled
result = []
while len(protein_identifiers) >= batch_size:
unique_protein_identifiers, first_idx, counts = np.unique(protein_identifiers,
return_index=True, return_counts=True)
if len(unique_protein_identifiers) < batch_size:
break
unique_random_selected = np.random.choice(unique_protein_identifiers,
size=batch_size, replace=False, p=counts / sum(counts))
unique_random_selected_idx = first_idx[[np.argwhere(unique_protein_identifiers == i)[0][0]
for i in unique_random_selected]]
result += list(idxs[unique_random_selected_idx])
# drop selected
idxs = np.delete(idxs, unique_random_selected_idx)
protein_identifiers = np.delete(protein_identifiers, unique_random_selected_idx)
# if idxs is not empty, append it to result
if len(idxs) > 0:
result += list(idxs)
return np.array(result)
def guarantee_good_batch_not_same_len(idxs, batch_size, dset, seed=0):
# guarantee generate good batches during training, which at least include:
# A positive example in gene A.
# A negative example in gene A.
# A positive example in gene !A.
# A negative example in gene !A.
# This only work for binary classification problem
assert batch_size >= 4
if seed is not None:
np.random.seed(seed)
# first get all positives and negatives
pos_idxs = idxs[dset.data[dset._y_columns[0]].iloc[idxs] == 1]
pos_ids = dset.data["uniprotID"].iloc[pos_idxs].to_numpy()
neg_idxs = idxs[dset.data[dset._y_columns[0]].iloc[idxs] != 1]
neg_ids = dset.data["uniprotID"].iloc[neg_idxs].to_numpy()
# assume idxs and protein_identifiers are shuffled
result = []
# loop through all positive idexes
for i in range(len(pos_idxs)):
id = pos_ids[i]
result.append(pos_idxs[i])
# get negative example in the same protein
neg_idx = neg_idxs[neg_ids == id]
if len(neg_idx) > 0:
result.append(np.random.choice(neg_idx))
else:
result.append(np.random.choice(neg_idxs))
# get positive example in different protein
pos_idx = pos_idxs[pos_ids != id]
if len(pos_idx) == 0:
pos_idx = pos_idxs[pos_idxs != pos_idxs[i]]
result.append(np.random.choice(pos_idx))
# get negative example in different protein
neg_idx = neg_idxs[neg_ids != id]
if len(neg_idx) == 0:
neg_idx = neg_idxs[neg_idxs != neg_idxs[i]]
result.append(np.random.choice(neg_idx))
# if batch_size is larger than 4, randomly select more
if batch_size > 4:
result += list(np.random.choice(idxs, size=batch_size - 4, replace=False))
# if some idxs are not used, randomly select them
unused_idxs = np.setdiff1d(idxs, result)
if len(unused_idxs) > 0:
result += list(unused_idxs)
return np.array(result)
def guarantee_good_batch(idxs, batch_size, dset, seed=0):
# guarantee generate good batches during training, which at least include:
# A positive example in gene A.
# A negative example in gene A.
# A positive example in gene !A.
# A negative example in gene !A.
# This only work for binary classification problem
assert batch_size >= 4
if seed is not None:
np.random.seed(seed)
if not isinstance(idxs, np.ndarray):
idxs = np.array(idxs)
# first get all positives and negatives
pos_label = 3
if sum(dset.data[dset._y_columns[0]].iloc[idxs] == 1) > 0:
pos_label = 1
pos_idxs = idxs[dset.data[dset._y_columns[0]].iloc[idxs] == pos_label]
pos_ids = dset.data["uniprotID"].iloc[pos_idxs].to_numpy()
neg_idxs = idxs[dset.data[dset._y_columns[0]].iloc[idxs] != pos_label]
neg_ids = dset.data["uniprotID"].iloc[neg_idxs].to_numpy()
# assume idxs and protein_identifiers are shuffled
result = []
# loop through all positive idexes
while len(pos_idxs) > 0:
this_batch_added = 0
# get a positive example
pos_idx = np.random.choice(pos_idxs)
id = pos_ids[pos_idxs == pos_idx][0]
result.append(pos_idx)
this_batch_added += 1
# drop selected
pos_ids = np.delete(pos_ids, np.argwhere(pos_idxs == pos_idx))
idxs = np.delete(idxs, np.argwhere(idxs == pos_idx))
pos_idxs = np.delete(pos_idxs, np.argwhere(pos_idxs == pos_idx))
# get negative example in the same protein
neg_idx = neg_idxs[neg_ids == id]
if len(neg_idx) > 0:
neg_idx = np.random.choice(neg_idx)
elif len(neg_idxs) > 0:
neg_idx = np.random.choice(neg_idxs)
else:
neg_idx = None
if neg_idx is not None:
result.append(neg_idx)
this_batch_added += 1
# drop selected
neg_ids = np.delete(neg_ids, np.argwhere(neg_idxs == neg_idx))
idxs = np.delete(idxs, np.argwhere(idxs == neg_idx))
neg_idxs = np.delete(neg_idxs, np.argwhere(neg_idxs == neg_idx))
# get positive example in different protein
pos_idx_candidate = pos_idxs[pos_ids != id]
if len(pos_idx_candidate) == 0:
pos_idx_candidate = pos_idxs[pos_idxs != pos_idx]
if len(pos_idx_candidate) > 0:
pos_idx = np.random.choice(pos_idx_candidate)
result.append(pos_idx)
this_batch_added += 1
# drop selected
pos_ids = np.delete(pos_ids, np.argwhere(pos_idxs == pos_idx))
idxs = np.delete(idxs, np.argwhere(idxs == pos_idx))
pos_idxs = np.delete(pos_idxs, np.argwhere(pos_idxs == pos_idx))
# get negative example in different protein
neg_idx_candidate = neg_idxs[neg_ids != id]
if len(neg_idx_candidate) == 0:
neg_idx_candidate = neg_idxs[neg_idxs != neg_idx]
if len(neg_idx_candidate) > 0:
neg_idx = np.random.choice(neg_idx_candidate)
result.append(neg_idx)
this_batch_added += 1
# drop selected
neg_ids = np.delete(neg_ids, np.argwhere(neg_idxs == neg_idx))
idxs = np.delete(idxs, np.argwhere(idxs == neg_idx))
neg_idxs = np.delete(neg_idxs, np.argwhere(neg_idxs == neg_idx))
# if batch_size is larger than this_batch_added, randomly select more
if batch_size > this_batch_added and len(idxs) >= batch_size - this_batch_added:
to_add = np.random.choice(idxs, size=batch_size - this_batch_added, replace=False)
result += list(to_add)
# drop selected
for idx in to_add:
pos_ids = np.delete(pos_ids, np.argwhere(pos_idxs == idx))
pos_idxs = np.delete(pos_idxs, np.argwhere(pos_idxs == idx))
neg_ids = np.delete(neg_ids, np.argwhere(neg_idxs == idx))
neg_idxs = np.delete(neg_idxs, np.argwhere(neg_idxs == idx))
idxs = np.delete(idxs, np.argwhere(idxs == idx))
# if some idxs are not used, randomly select them
unused_idxs = np.setdiff1d(idxs, result)
if len(unused_idxs) > 0:
result += list(unused_idxs)
return np.array(result)
def save_argparse(args, filename, exclude=None):
import json
if filename.endswith("yaml") or filename.endswith("yml"):
if isinstance(exclude, str):
exclude = [exclude]
args = args.__dict__.copy()
for exl in exclude:
del args[exl]
ds_arg = args.get("dataset_arg")
if ds_arg is not None and isinstance(ds_arg, str):
args["dataset_arg"] = json.loads(args["dataset_arg"])
yaml.dump(args, open(filename, "w"))
else:
raise ValueError("Configuration file should end with yaml or yml")
|