File size: 2,241 Bytes
76eb7b3 | 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 | """Score lung nodule or liver lesion localization on CT-FM v12 regional features.
python -m proj2rep lesion --task nodule --input embeddings/scan.npz --out scan_nodule.npz
"""
import argparse
from pathlib import Path
import numpy as np
from scipy.special import expit
def local_scores(regions, weights):
"""Apply the training standardization and logistic head; output rows and columns follow the encoder grid."""
grid = int(weights["grid"])
if regions.ndim != 3 or regions.shape[1:] != (grid**2, len(weights["coef"])):
raise ValueError(f"Expected (slabs, {grid**2}, {len(weights['coef'])}) CT-FM features; encode with --grid {grid}")
if not np.isfinite(regions).all():
raise ValueError("The scan contains missing or non-finite regional embeddings")
x = regions.astype(np.float32, copy=True)
x -= weights["mean"]
x /= weights["scale"]
logits = x.reshape(-1, x.shape[-1]) @ weights["coef"] + weights["intercept"]
return expit(logits).reshape(len(x), grid, grid)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--task", choices=("nodule", "liver"), required=True)
parser.add_argument("--input", type=Path, required=True, help="one scan produced by proj2rep encode --grid 8")
parser.add_argument("--out", type=Path, required=True, help="output NPZ with slab positions and regional scores")
args = parser.parse_args(argv)
path = Path(__file__).parent / "weights" / f"{args.task}_grid8.npz"
with np.load(path) as weights, np.load(args.input) as scan:
scores = local_scores(scan["regions"], weights)
z0 = scan["z0"]
if z0.shape != (len(scores),) or not np.isfinite(z0).all():
raise ValueError("Expected one finite z0 coordinate per slab")
if args.out.resolve() == args.input.resolve():
raise ValueError("Use a separate file for the output scores")
with args.out.open("wb") as file:
np.savez_compressed(file, z0=z0, scores=scores, task=args.task, grid=int(weights["grid"]))
print(f"Scored {len(scores)} slabs for {args.task} localization")
if __name__ == "__main__":
main()
|