You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Wandb中绘制数组首个元素折线图?Vega配置及替代方案咨询

解决方案:Wandb数组指标折线图实现

一、调整Vega配置实现(可行)

你之前的问题出在Vega transform的层级错误——Wandb自定义图表中,数组处理的transform必须放在数据源(data)的transform数组里,而非顶层的transform块。另外,如果只需要数组的首个元素,无需用flatten,直接用calculate提取更高效。

正确配置步骤:

  1. 查询语句保持不变:
query {
    runSets
         (runSets: "${runSets}" ) {
            id
            name
            history
                (keys: ["metric" ] )
        }
}
  1. Vega Spec 调整:
    在data的transform中添加calculate提取数组第一个元素,同时保留step作为X轴:
{
  "data": {
    "name": "table",
    "transform": [
      // 提取metric数组第一个元素,命名为metric_first
      {"type": "calculate", "as": "metric_first", "expr": "datum.metric[0]"},
      // 过滤无效的step或metric数据
      {"type": "filter", "expr": "datum.step != null && datum.metric_first != null"}
    ]
  },
  "mark": "line",
  "encoding": {
    "x": {"field": "step", "type": "quantitative", "title": "Step"},
    "y": {"field": "metric_first", "type": "quantitative", "title": "Metric (First Element)"},
    "color": {"field": "name", "type": "nominal", "title": "Run Name"}
  }
}

如果后续需要用到数组所有元素,可将calculate替换为flatten(同样放在data的transform数组内):

"data": {
  "name": "table",
  "transform": [
    {"type": "flatten", "fields": ["metric"], "as": "metric_element"},
    {"type": "filter", "expr": "datum.step != null"}
  ]
}

二、Notebook脚本处理方案

如果Vega配置过于繁琐,直接在Notebook中拉取数据转换更灵活:

步骤1:拉取指定Run的历史数据

import wandb

# 初始化API
api = wandb.Api()

# 替换为你的Run路径(格式:用户名/项目名/run_id)
run = api.run("your_username/your_project/your_run_id")

# 拉取包含metric和step的历史数据
history = run.history(keys=["metric", "step"])

步骤2:提取数组首个元素并可视化

import matplotlib.pyplot as plt

# 提取每个step对应的metric第一个元素
history["metric_first"] = history["metric"].apply(lambda x: x[0] if isinstance(x, list) else None)

# 过滤无效数据
valid_data = history.dropna(subset=["step", "metric_first"])

# 绘制折线图
plt.plot(valid_data["step"], valid_data["metric_first"])
plt.xlabel("Step")
plt.ylabel("Metric (First Element)")
plt.title("Metric First Element vs Step")
plt.show()

步骤3(可选):重新回传处理后的数据到Wandb

如果想让处理后的数据在Wandb平台长期查看,可重新log:

# 初始化并关联目标Run
run = wandb.init(project="your_project", resume="your_run_id")

# 按step重新log处理后的数据
for idx, row in valid_data.iterrows():
    run.log({"metric_first": row["metric_first"], "step": row["step"]})

run.finish()

内容的提问来源于stack exchange,提问作者Danial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:02:55