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

如何提取PyTorch自编码器的编码器部分实现测试阶段特征降维

PyTorch自编码器提取编码器模块操作说明

先修正你代码里的语法错误

你给出的类定义存在变量未定义的问题:__init__方法接收的参数是n_features,但内部错误写了self.n_sensors = n_sensors,这里n_sensors没有被定义,会直接报错,修正后的类代码如下:

import torch.nn as nn
class Autoencoder(nn.Module):
    def __init__(self, n_features):
        super(Autoencoder, self).__init__()
        self.n_features = n_features
        
        self.encoder = nn.Sequential(
            nn.Linear(self.n_features, 1),
            nn.ReLU(True))
        
        self.decoder = nn.Sequential(
            nn.Linear(1, self.n_features),
            nn.ReLU(True))

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

提取编码器的正确操作

你的思路是对的,但调用方式要调整:encoder是自编码器实例的属性,不是类本身的属性,也不需要加括号调用,具体操作步骤如下:

  • 首先完成自编码器的实例化、训练流程,得到训练完成的模型实例
# 示例:假设输入特征维度为10,实例化模型
autoencoder = Autoencoder(n_features=10)
# 此处省略模型训练代码,训练完成后得到可用的autoencoder实例
  • 直接调用实例的encoder属性处理测试数据即可得到压缩后的潜空间特征,测试阶段建议搭配torch.no_grad()关闭梯度计算,提升运行效率、节省显存:
import torch
# 假设test_data为预处理后的测试数据张量,形状匹配编码器输入要求
with torch.no_grad():
    latent_code = autoencoder.encoder(test_data)
  • 如果你需要单独把编码器作为独立模块复用,也可以单独赋值给新变量:
encoder_model = autoencoder.encoder
with torch.no_grad():
    latent_code = encoder_model(test_data)

注意:你提到的model = Autoencoder.encoder()写法是错误的,encoder是绑定在实例上的模块,不是类的静态方法,不需要加括号调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:57:01