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

使用SelectKBest特征选择后出现dropout输入类型不匹配错误求助

问题描述

直接使用x = data.features时代码运行正常,但通过SelectKBest进行特征选择后,执行到F.dropout时报错:dropout(): argument 'input' (position 1) must be Tensor, not tensorflow.python.framework.ops.EagerTensor。

出错代码
def forward(self, data):
    x = data.features
    
    yyy=pd.read_csv("ycornell.csv",header=None)
    vectorr=pd.read_csv("vectorcornell.csv",header=None)
    centralityy=pd.read_csv("cornellcentrality.csv",header=None)
    selectedfeaturess= SelectKBest(chi2, k=100).fit_transform(x,yyy)
    x = np.c_[centralityy, selectedfeaturess]
    x= tf.convert_to_tensor(x)
    adj = data.adj
    x = F.dropout(x, p=self.dropout, training=self.training)
    x = F.relu(self.gc1(x, adj), return_dict=False)
    x = F.dropout(x, p=self.dropout, training=self.training)
    x = self.gc2(x, adj)
    return F.log_softmax(x, dim=1)
问题原因与解决方法
  • 核心问题:你用tf.convert_to_tensor()把数组转成了TensorFlow的EagerTensor,但F.dropout是PyTorch的函数,仅支持PyTorch原生Tensor类型。
  • 解决方法:
    1. 将TensorFlow的张量转换替换为PyTorch的张量转换函数,比如torch.tensor()或torch.from_numpy()。
    2. 确保转换后的张量与原data.features处于同一设备(CPU/GPU),避免设备不匹配报错。

修改后的关键代码片段:

# 替换原有的x=tf.convert_to_tensor(x)
x = torch.tensor(x, dtype=torch.float32).to(data.features.device)
# 或者使用torch.from_numpy(注意numpy默认是float64,建议转成float32匹配原特征类型)
x = torch.from_numpy(x.astype(np.float32)).to(data.features.device)
额外优化建议
  • 不要在forward函数内重复读取CSV文件:每次前向传播都读文件会严重拖慢运行效率,建议在类的__init__方法中提前加载这些数据并保存为实例变量。
  • 规范特征选择流程:SelectKBest的fit_transform应该只在训练集上执行,测试集仅用transform,避免在forward里每次都拟合,防止数据泄露影响模型泛化能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:05:23