将图结构转换矩阵数据转换为PyTorch支持的张量类型时,出现错误AttributeError: ‘Tensor’ object has no attribute ‘todense’
实例来源于《PyTorch深度学习和图神经网络 卷1》实例26:用图卷积神经网络为论文分类
出错部分p284页
原代码:
#将数据转为张量,并分配运算资源
adj = torch.FloatTensor(adj.todense())#节点间的关系
features = torch.FloatTensor(features.todense())#节点自身的特征
labels = torch.LongTensor(labels)#每个节点分类标签
#划分数据集
n_train = 200
n_val = 300
n_text = len(features) -n_train - n_val
np.random.seed(34)
idxs = np.random.permutation(len(features))#将索引打乱顺序
#计算每一个数据集的索引
idx_train = torch.LongTensor(idxs[:n_train])
idx_val = torch.LongTensor(idxs[n_train:n_train+n_val])
idx_test = torch.LongTensor(idxs[n_train+n_val:])
#分配运算资源
adj = adj.to(device)
features = features.to(device)
labels = labels.to(device)
idx_train = idx_train.to(device)
idx_val = idx_val.to(device)
idx_test = idx_test.to(device)
错误提示:
AttributeError Traceback (most recent call last)
Cell In[21], line 2
1 #将数据转为张量,并分配运算资源
----> 2 adj = torch.FloatTensor(adj.todense())#节点间的关系
3 features = torch.FloatTensor(features.todense())#节点自身的特征
4 labels = torch.LongTensor(labels)#每个节点分类标签
AttributeError: 'Tensor' object has no attribute 'todense'
找了一圈没有一样的解决方案,但是在其他问题” module ‘tensorflow’ has no attribute ‘sparse_to_dense’ “的描述中发现了to_dense这样的写法,就查了一下PyTorch文档,发现可能是更新了,确实得写to_dense。
改一下:
adj = torch.FloatTensor(adj.to_dense())#节点间的关系
features = torch.FloatTensor(features.to_dense())#节点自身的特征
顺利运行!