跳到主要内容

自定义算子示例

下面三个示例都是完整可发布的:给出契约内容与 Python 源码,说明调试时应当看到的结果,并列出最容易踩的坑。把它们当作模板改造成你自己的算法即可。

怎么使用这些示例

在算子工作台里先按「契约」部分填写参数与端口,再把「代码」部分粘进代码编辑器(文件名为 main.py 时,入口填 main:类名),然后选一个数据集版本调试。字段与 API 的规则说明见 算子契约与错误码参考,开发流程见 自定义算子开发。

三个示例覆盖三类最常见的需求:

示例输入输出用到的能力
① 样本队列统计样本集合特征表 + 指标pandas 分组统计
② 二分类 Brier 分数预测表指标纯标准库数值计算
③ 影像缩略图集样本集合图片集 + 指标PIL 读图与绘图

1. 示例一:样本队列统计​

统计一个队列有多少样本、多少患者、标签分布如何,并把每个样本的元数据整理成特征表,方便下游直接做分组分析。

契约​

{
"type": "SampleCohortSummary",
"version": "1.0.0",
"name": "样本队列统计",
"category": "features",
"description": "统计样本数、患者数与标签分布,并输出逐样本元数据特征表。",
"parametersSchema": {
"type": "object",
"title": "参数",
"properties": {
"requireLabel": { "type": "boolean", "title": "丢弃无标签样本", "default": false },
"valueKey": { "type": "string", "title": "数值标签字段名", "default": "labelValue" }
},
"additionalProperties": false
},
"defaults": { "requireLabel": false, "valueKey": "labelValue" },
"inputs": [
{ "name": "samples", "type": "sample_collection", "required": true }
],
"outputs": [
{ "name": "features", "type": "feature_table", "required": true },
{ "name": "metrics", "type": "metrics", "required": true }
],
"entrypoint": "main:CohortSummary",
"dependencies": ["pandas"]
}

代码 main.py​

"""样本队列统计:逐样本元数据表 + 队列级指标。"""
import statistics

import pandas as pd

from radstudio.operator import Operator, operator


@operator("SampleCohortSummary", version="1.0.0")
class CohortSummary(Operator):
def run(self, ctx):
rows = ctx.input_json("samples") # 样本集合的根节点是列表
if not isinstance(rows, list) or not rows:
raise ValueError("样本集合为空,无法统计")
keep = ctx.parameters["requireLabel"]
value_key = ctx.parameters["valueKey"]

kept, dropped = [], 0
for row in rows:
if keep and row.get("label") is None:
dropped += 1
continue
numeric = row.get(value_key)
kept.append(
{
"imageId": row["imageId"],
"patientId": row["patientId"],
"label": row.get("label"),
"hasRoi": 1 if str(row.get("roiPath") or "").strip() else 0,
"numeric": float(numeric) if isinstance(numeric, (int, float)) else 0.0,
}
)
ctx.progress(60, f"保留 {len(kept)} / {len(rows)} 个样本")

frame = pd.DataFrame(kept)
grouped = frame.groupby(["label"], dropna=False)["imageId"].count()
numbers = frame["numeric"].tolist()

features = {
"featureNames": ["hasRoi", "numeric"],
"records": [
{
"imageId": item["imageId"],
"patientId": item["patientId"],
"label": item["label"],
"values": [item["hasRoi"], item["numeric"]],
}
for item in kept
],
}
metrics = {
"samples": len(kept),
"dropped": dropped,
"patients": frame["patientId"].nunique(),
"roiCoverage": round(float(frame["hasRoi"].mean()), 4) if len(frame) else 0.0,
"labelCounts": {str(key): int(value) for key, value in grouped.items()},
"numericMean": round(statistics.fmean(numbers), 6) if numbers else 0.0,
"numericStd": round(statistics.pstdev(numbers), 6) if len(numbers) > 1 else 0.0,
}
return {
"features": ctx.output_json("features.json", features, "feature_table"),
"metrics": ctx.output_json("metrics.json", metrics, "metrics"),
}

预期调试结果​

选一个数据集版本点调试后,日志里能看到 保留 120 / 128 个样本 之类的进度信息,产物区出现 metrics.json:

字段,示例值,说明
samples,120,进入特征表的样本数
patients,42,去重后的患者数
roiCoverage,0.9333,带 ROI 掩膜的样本占比
labelCounts,"{'0': 66, '1': 54}",按标签分组的样本数
numericMean,0.418752,数值标签字段的均值

features.json 是标准特征表结构:featureNames 与每条记录的 values 长度必须一致,records 每行必须带 imageId、patientId。

常见坑​

现象原因
输出缺少必需端口:featuresrun() 返回的字典少写了端口,或键名与契约里的 name 不一致
特征值数量与featureNames不一致values 数组长度和 featureNames 不同,逐字段核对顺序
样本键imageId重复,禁止按行号合并上游数据里同一 imageId 出现两次;先在上游去重,或在算子里主动合并
同一患者标签不一致同一 patientId 带了不同的 label,这是平台的数据一致性约束
参数面板上没有控件parametersSchema 顶层没写 "type": "object",或属性名与 defaults 不对应

2. 示例二:二分类 Brier 分数​

对上游预测结果计算 Brier 分数 mean((p - y)^2),越低越好。特点是只用 Python 标准库,适合作为评价指标类算子的模板。

契约​

{
"type": "ResearchBrierScore",
"version": "1.0.0",
"name": "科研示例:二分类 Brier 分数",
"category": "results",
"description": "按图像等权计算 mean((p-y)^2),越低越好;不验证独立性,不替代患者级统计分析。",
"parametersSchema": { "type": "object", "properties": {}, "additionalProperties": false },
"defaults": {},
"inputs": [
{ "name": "predictions", "type": "prediction_table", "required": true }
],
"outputs": [
{ "name": "metrics", "type": "metrics" }
],
"entrypoint": "main:BrierScore",
"dependencies": []
}

代码 main.py​

"""二分类 Brier 分数:mean((p - y)**2),不做拟合也不选择阈值。"""
import math

from radstudio.operator import Operator, operator


@operator("ResearchBrierScore", version="1.0.0")
class BrierScore(Operator):
def run(self, ctx):
if ctx.parameters:
raise ValueError("ResearchBrierScore does not accept parameters")
table = ctx.input_json("predictions")
rows = table.get("records")
if not isinstance(rows, list) or not rows:
raise ValueError("predictions.records must be a nonempty list")

seen, errors = set(), []
for row in rows:
identity = row.get("imageId")
if not isinstance(identity, str) or not identity or identity in seen:
raise ValueError("imageId must be nonempty and unique")
seen.add(identity)
y, p = row.get("label"), row.get("probability")
if type(y) not in (int, float) or y not in (0, 1):
raise ValueError("label must be numeric 0 or 1")
if type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1:
raise ValueError("probability must be finite and in [0, 1]")
errors.append((p - y) ** 2)

return {
"metrics": ctx.output_json(
"brier.json",
{
"brier": math.fsum(errors) / len(errors),
"sampleCount": len(rows),
"weighting": "per_image",
"positiveLabel": 1,
"evaluation": table.get("evaluation", "unspecified"),
"independenceVerified": False,
},
"metrics",
)
}

预期调试结果​

用 4 行预测数据((label, probability) 分别为 (1, 0.9)、(1, 0.6)、(0, 0.2)、(0, 0.4))调试,brier.json 内容应为:

字段,值
brier,0.0925
sampleCount,4
weighting,per_image
positiveLabel,1
independenceVerified,false

0.0925 与 scikit-learn 的 brier_score_loss 在同一组数据上的结果一致,可以拿它验证自己的实现有没有写错。

常见坑​

现象原因
调试面板选不到数据集本算子的必需输入是预测表而不是样本集合;请先用工作流跑通上游预测节点,把结果作为数据集版本后再来调试(见 自定义算子开发 第 6 节说明)
label must be numeric 0 or 1上游标签为空或多分类;Brier 只适用于二分类
probability must be finite and in [0, 1]概率缺失、为 NaN 或超出 0–1
参数面板被隐藏契约里 properties 为空,属于预期行为;如果确实需要参数,请另存新版本补上
想用 sklearn.metrics.brier_score_loss可以,scikit-learn 在依赖白名单内;示例特意只用标准库,是为了少一个不确定因素

3. 示例三:影像缩略图集​

从输入的影像真实地生成新的图片产物:逐张读图、等比缩放、拼成一张总览图,并把所有图片打包成可下载的图集。适合做可视化、质控预览、结果归档类算子。

契约​

{
"type": "ImageThumbAtlas",
"version": "1.0.0",
"name": "影像缩略图集",
"category": "results",
"description": "按标签分组抽样生成缩略图与总览图,打包为可下载图集。",
"parametersSchema": {
"type": "object",
"title": "参数",
"properties": {
"tile": { "type": "integer", "title": "缩略图边长(像素)", "minimum": 32, "maximum": 512, "default": 256 },
"maxImages": { "type": "integer", "title": "最多处理张数", "minimum": 1, "maximum": 60, "default": 12 },
"perLabel": { "type": "integer", "title": "每个标签最多张数", "minimum": 1, "maximum": 30, "default": 6 }
},
"required": ["tile", "maxImages"],
"additionalProperties": false
},
"defaults": { "tile": 256, "maxImages": 12, "perLabel": 6 },
"inputs": [
{ "name": "samples", "type": "sample_collection", "required": true }
],
"outputs": [
{ "name": "figures", "type": "figure_bundle", "required": true },
{ "name": "metrics", "type": "metrics", "required": true }
],
"entrypoint": "main:ThumbAtlas",
"dependencies": ["pillow", "numpy"]
}

代码 main.py​

"""影像缩略图集:读原图 → 灰度归一化 → 缩放 → 拼总览图 → 打包 zip。"""
import io
import zipfile

import numpy as np
from PIL import Image

from radstudio.operator import Operator, operator


@operator("ImageThumbAtlas", version="1.0.0")
class ThumbAtlas(Operator):
def run(self, ctx):
tile = int(ctx.parameters["tile"])
budget = int(ctx.parameters["maxImages"])
per_label = int(ctx.parameters["perLabel"])
rows = ctx.input_json("samples")
if not isinstance(rows, list) or not rows:
raise ValueError("样本集合为空,无法生成图集")

used, counts, tiles, failures = 0, {}, [], []
for row in rows:
if used >= budget:
break
label = str(row.get("label"))
if counts.get(label, 0) >= per_label:
continue
try:
source = ctx.store.resolve_path(row["imagePath"])
array = np.asarray(Image.open(source).convert("L"), dtype=float)
if array.ndim != 2:
raise ValueError("仅支持二维灰度图像")
low, high = float(array.min()), float(array.max())
span = high - low if high > low else 1.0
normalized = ((array - low) / span * 255.0).astype(np.uint8)
image = Image.fromarray(normalized).resize((tile, tile), Image.NEAREST)
except (OSError, ValueError, KeyError) as error:
failures.append({"imageId": row["imageId"], "reason": str(error)})
continue

buffer = io.BytesIO()
image.save(buffer, format="PNG")
name = f"{used:03d}_{label}.png"
tiles.append((name, buffer.getvalue()))
counts[label] = counts.get(label, 0) + 1
used += 1
ctx.progress(round(used / budget * 80), f"已处理 {used} 张")

if not tiles:
raise ValueError("没有任何影像处理成功,请检查影像路径与格式")

columns = min(4, len(tiles))
lines = (len(tiles) + columns - 1) // columns
montage = Image.new("L", (columns * tile, lines * tile), color=255)
for index, (name, raw) in enumerate(tiles):
montage.paste(Image.open(io.BytesIO(raw)), ((index % columns) * tile, (index // columns) * tile))
overview = io.BytesIO()
montage.save(overview, format="PNG")

archive = io.BytesIO()
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle:
for name, raw in tiles:
bundle.writestr(f"thumbs/{name}", raw)
bundle.writestr("montage.png", overview.getvalue())
bundle.writestr(
"index.csv",
"file,label\n" + "\n".join(f"{name},{name.rsplit('_', 1)[-1]}" for name, _ in tiles),
)

return {
"figures": ctx.output_bytes("figures.zip", archive.getvalue(), "figure_bundle"),
"metrics": ctx.output_json(
"atlas.json",
{
"images": len(tiles),
"byLabel": counts,
"skipped": len(rows) - used,
"failed": failures,
"tile": tile,
"montage": {"width": columns * tile, "height": lines * tile},
},
"metrics",
),
}

预期调试结果​

  • 产物区出现 figures.zip(图集)与 atlas.json(指标)。
  • 打开 figures.zip 可见 thumbs/000_1.png 等缩略图、一张 montage.png 总览图、以及 index.csv 清单——这些文件是算子新产生的,不是原始影像的拷贝。
  • atlas.json 示例:
字段,值
images,12
byLabel,"{'0': 6, '1': 6}"
skipped,108
failed,[]
tile,256
montage,"{'width': 1024, 'height': 768}"

在运行详情页可以直接下载 figures.zip 查看。

常见坑​

现象原因
仅支持二维灰度图像输入的 .npy 是三维体数据;逐层处理或改用二维切片
只成功几张、failed 里成批报错imagePath 指向的是掩膜或不存在的路径;先核对字段
图集打不开 / 下游识别不了figure_bundle 必须是一个 zip 归档,用 ctx.output_bytes(..., "figure_bundle") 一次性写出,不要输出多张散图
运行很慢或超时用 maxImages / perLabel 控制张数,调试时再勾选「只取前 N 条样本」
实现包超过 16MB 上限把生成的图片或测试数据留在了代码包里;代码包只放 .py 源文件
用了 matplotlib 绘图该库不在依赖白名单内,会报 依赖 matplotlib 不在平台预置白名单内;改用 PIL 绘制

4. 下一步​