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

如何对独热编码标签张量执行resample_poly等效重采样?

处理独热编码标签的重采样问题

你已经用resample_poly完成了输入信号X的重采样,但独热编码的标签序列是离散类别标记,不能直接套用针对连续信号的重采样逻辑,需要适配离散序列的处理方式。目前没有内置的完全等效于resample_poly的独热标签重采样函数,但可以通过以下两种自定义方案实现需求,支持指定张量、up/down参数、mask_axis(序列长度轴)和class_axis(类别轴):

方案1:基于类别索引的硬标签重采样(推荐)

适用于标准独热编码(每个位置只有一个类别为1),先将独热编码转成类别索引,对索引序列重采样后再转回独热编码:

import numpy as np
from scipy.signal import resample_poly

def resample_onehot_labels(y_onehot, up, down, mask_axis=1, class_axis=-1):
    # 调整轴顺序,方便处理序列长度和类别维度
    y_reshaped = np.moveaxis(y_onehot, [mask_axis, class_axis], [1, -1])
    batch_size, seq_len, num_classes = y_reshaped.shape
    
    # 独热转类别索引
    y_idx = np.argmax(y_reshaped, axis=-1)
    
    # 用resample_poly处理索引序列,取整后限制类别范围
    y_idx_resampled = resample_poly(y_idx.astype(float), up=up, down=down, axis=1)
    y_idx_resampled = np.round(y_idx_resampled).astype(int)
    y_idx_resampled = np.clip(y_idx_resampled, 0, num_classes - 1)
    
    # 转回独热编码
    y_onehot_resampled = np.zeros((batch_size, y_idx_resampled.shape[1], num_classes), dtype=y_onehot.dtype)
    np.put_along_axis(y_onehot_resampled, y_idx_resampled[..., None], 1, axis=-1)
    
    # 恢复原轴顺序
    y_onehot_resampled = np.moveaxis(y_onehot_resampled, [1, -1], [mask_axis, class_axis])
    return y_onehot_resampled

# 调用示例
y_true_resampled = resample_onehot_labels(y_true, up=512, down=3208, mask_axis=1, class_axis=2)
# 输出形状:(1, 512, 4)

方案2:基于概率分布的软标签重采样

如果你的"独热编码"实际是带概率的软标签,可直接对每个类别维度用resample_poly做连续重采样,保留概率分布:

import numpy as np
from scipy.signal import resample_poly

def resample_onehot_soft(y_onehot, up, down, mask_axis=1, class_axis=-1):
    # 调整轴顺序
    y_reshaped = np.moveaxis(y_onehot, [mask_axis, class_axis], [1, -1])
    batch_size, seq_len, num_classes = y_reshaped.shape
    
    # 对每个类别维度单独重采样
    resampled_channels = []
    for c in range(num_classes):
        channel = y_reshaped[..., c]
        resampled_channel = resample_poly(channel, up=up, down=down, axis=1)
        resampled_channels.append(resampled_channel)
    
    y_resampled = np.stack(resampled_channels, axis=-1)
    # 可选:归一化,确保每个位置的类别概率和为1
    y_resampled = y_resampled / np.sum(y_resampled, axis=-1, keepdims=True)
    
    # 恢复原轴顺序
    y_resampled = np.moveaxis(y_resampled, [1, -1], [mask_axis, class_axis])
    return y_resampled

# 调用示例
y_true_resampled = resample_onehot_soft(y_true, up=512, down=3208, mask_axis=1, class_axis=2)

如果需要适配PyTorch/TensorFlow等张量框架,只需将上述numpy操作替换为对应框架的API(比如torch.argmax、tf.argmax,以及框架自带的重采样函数)即可。

内容的提问来源于stack exchange,提问作者Muhammad Ikhwan Perwira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:12:44