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

使用tidyclust调优K-prototypes模型遇数据类型兼容错误求助

解决tidyclust调优K-prototypes时sse_within_total类型不兼容错误

问题重现

使用tidyclust框架调优基于clustMixType引擎的K-prototypes聚类模型时,执行tune_cluster()出现如下错误:

Error in value[[3L]]():
! In metric: sse_within_total
Not compatible with requested type: [type=character; target=double].

非调优的Workflow或聚类拟合对象上,通过sse_within_total(..., dist_fun = cluster::daisy)可以正常计算指标,但不清楚如何在tune_cluster()中指定该距离函数。

原因分析

默认的sse_within_total()使用欧氏距离,仅支持纯数值型数据;而K-prototypes用于处理数值+分类混合数据,需要能兼容混合类型的距离函数(如cluster::daisy)。tune_cluster()无法直接给sse_within_total()传递额外参数,必须通过自定义度量函数的方式固化参数。

解决方案

将sse_within_total()包装成带固定dist_fun参数的自定义度量函数,再传入cluster_metric_set()供tune_cluster()使用。可以用两种方式实现:

方式1:手动定义自定义度量函数

custom_sse_within <- function(data, truth, estimate, ...) {
  sse_within_total(data, truth, estimate, ..., dist_fun = cluster::daisy)
}

方式2:用purrr::partial固化参数

custom_sse_within <- purrr::partial(sse_within_total, dist_fun = cluster::daisy)

完整可运行代码

library(tidyclust)
library(tidyverse)
library(tidymodels)
library(cluster) # 确保加载cluster包

data("penguins", package = "modeldata")

penguins <- penguins %>% drop_na()
penguins_cv <- vfold_cv(penguins, v = 5)

# 可调优的K-prototypes模型规格
kproto_spec <- k_means(engine = 'clustMixType', num_clusters = tune())

penguins_rec <- recipe(~ ., data = penguins)

kproto_wflow <- workflow(penguins_rec, kproto_spec)

clust_num_grid <- grid_regular(num_clusters(), levels = 10)

# 定义带daisy距离的自定义度量
custom_sse_within <- purrr::partial(sse_within_total, dist_fun = cluster::daisy)

# 执行调优
res <- tune_cluster(
  kproto_wflow,
  resamples = penguins_cv,
  grid = clust_num_grid,
  control = control_grid(save_pred = TRUE, extract = identity),
  metrics = cluster_metric_set(custom_sse_within)
)

# 查看结果
show_notes(res)
collect_metrics(res)

说明

  • 自定义度量函数固化了dist_fun = cluster::daisy参数,确保tune_cluster()在每个交叉验证折上计算指标时,都使用能处理混合数据的距离函数。
  • 需确保加载cluster包,否则daisy函数会找不到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:18:17