You need to enable JavaScript to run this app. 将PyTorch版TimesNet移植到Tensorflow.js的技术求助
优惠活动
大模型
产品
解决方案
定价
更多

将PyTorch版TimesNet移植到Tensorflow.js的技术求助

在TensorFlow.js中移植TimesNet模型的完整实现方案

一、核心移植逻辑

直接基于原PyTorch代码的模块划分,将每个组件映射为TensorFlow.js(TF.js)的等价实现,重点处理PyTorch与TF.js的层API、张量维度、权重格式差异,无需深入学习PyTorch特性即可完成移植。

二、逐模块代码实现

1. 时间序列分解组件(对应原SeriesDecomp类)

class SeriesDecomp extends tf.layers.Layer {
  constructor(config) {
    super(config);
    this.kernelSize = config.kernelSize;
    this.movingAvg = tf.layers.averagePooling1d({
      poolSize: this.kernelSize,
      strides: 1,
      padding: 'same'
    });
  }

  call(inputs) {
    return tf.tidy(() => {
      const movingAvg = this.movingAvg.apply(inputs);
      const res = tf.sub(inputs, movingAvg);
      return [movingAvg, res];
    });
  }

  static get className() {
    return 'SeriesDecomp';
  }
}
tf.serialization.registerClass(SeriesDecomp);

2. 核心时序注意力块(对应原TimesBlock类)

class TimesBlock extends tf.layers.Layer {
  constructor(config) {
    super(config);
    this.outChannels = config.outChannels;
    this.numHeads = config.numHeads;
    
    // 频率注意力分支
    this.freqConv = tf.layers.conv1d({
      filters: this.outChannels,
      kernelSize: config.kernelSize,
      padding: 'same',
      activation: 'relu'
    });
    this.freqAttn = tf.layers.multiHeadAttention({
      numHeads: this.numHeads,
      keyDim: this.outChannels / this.numHeads
    });
    
    // 时间注意力分支
    this.timeConv = tf.layers.conv1d({
      filters: this.outChannels,
      kernelSize: config.kernelSize,
      padding: 'same',
      activation: 'relu'
    });
    this.timeAttn = tf.layers.multiHeadAttention({
      numHeads: this.numHeads,
      keyDim: this.outChannels / this.numHeads
    });
    
    this.decomp = new SeriesDecomp({kernelSize: config.decompKernelSize});
    this.norm = tf.layers.layerNormalization();
    this.proj = tf.layers.conv1d({
      filters: this.outChannels,
      kernelSize: 1,
      padding: 'same'
    });
  }

  call(inputs) {
    return tf.tidy(() => {
      const [x, xMark] = inputs;
      // 频率分支计算
      let freqX = this.freqConv.apply(x);
      freqX = tf.concat([freqX, xMark], -1);
      freqX = this.freqAttn.apply({query: freqX, value: freqX});
      
      // 时间分支计算
      let timeX = this.timeConv.apply(x);
      timeX = tf.concat([timeX, xMark], -1);
      timeX = this.timeAttn.apply({query: timeX, value: timeX});
      
      // 融合与残差连接
      let res = tf.add(freqX, timeX);
      res = this.proj.apply(res);
      const [trend, seasonal] = this.decomp.apply(res);
      res = tf.add(trend, seasonal);
      return this.norm.apply(tf.add(res, x));
    });
  }

  static get className() {
    return 'TimesBlock';
  }
}
tf.serialization.registerClass(TimesBlock);

3. 完整TimesNet模型组装

class TimesNet extends tf.layers.Layer {
  constructor(config) {
    super(config);
    this.seqLen = config.seqLen;
    this.predLen = config.predLen;
    this.outChannels = config.outChannels;
    this.numBlocks = config.numBlocks;
    
    // 输入嵌入层
    this.embedding = tf.layers.conv1d({
      filters: this.outChannels,
      kernelSize: 1,
      padding: 'same'
    });
    
    // 堆叠TimesBlock
    this.blocks = [];
    for (let i = 0; i < this.numBlocks; i++) {
      this.blocks.push(new TimesBlock({
        outChannels: this.outChannels,
        kernelSize: config.kernelSize,
        numHeads: config.numHeads,
        decompKernelSize: config.decompKernelSize
      }));
    }
    
    // 输出投影层
    this.projection = tf.layers.conv1d({
      filters: this.predLen,
      kernelSize: 1,
      padding: 'same'
    });
  }

  call(inputs) {
    return tf.tidy(() => {
      const [x, xMark] = inputs;
      // 输入维度转换:适配TF.js的[N, L, C]格式(原PyTorch为[N, C, L])
      x = tf.transpose(x, [0, 2, 1]);
      xMark = tf.transpose(xMark, [0, 2, 1]);
      
      // 输入嵌入
      let xEmbed = this.embedding.apply(x);
      // 遍历执行所有TimesBlock
      this.blocks.forEach(block => {
        xEmbed = block.apply([xEmbed, xMark]);
      });
      // 输出投影并转置为预测格式
      let output = this.projection.apply(xEmbed);
      return tf.transpose(output, [0, 2, 1]);
    });
  }

  static get className() {
    return 'TimesNet';
  }
}
tf.serialization.registerClass(TimesNet);

三、权重转换与验证

  1. 预训练权重迁移

    • 在Python中加载原PyTorch模型,提取各层权重(如Conv1d的权重形状为[out, in, kernel])
    • 将卷积权重转置为TF.js格式:[kernel, in, out],其他层权重直接对应复制
    • 将转换后的权重保存为JSON格式,通过tf.loadLayersModel导入TF.js
  2. 功能一致性验证

    • 用相同的时间序列输入,分别在PyTorch和TF.js模型中运行
    • 对比输出结果的MAE误差,控制在1e-5以内即可确认移植正确性

四、关键注意事项

  • 处理PyTorch与TF.js的张量维度差异:原PyTorch用[N, C, L],TF.js默认[N, L, C],需通过tf.transpose转换
  • 多头注意力层的keyDim需设置为outChannels / numHeads,保证与原模型维度一致
  • 平均池化层的padding必须设置为same,确保输出序列长度与输入一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:25:16