首页 > 解决方案 > 对象没有属性?

问题描述

我收到一个属性错误,但即使查看了多个以前的帖子,我也无法弄清楚原因。

import math
import time
import random
import os, sys
import os.path as osp
from itertools import chain
from shutil import copy
import copy as cp
from tqdm import tqdm
import pdb

import numpy as np
from sklearn.metrics import roc_auc_score
import scipy.sparse as ssp
import torch
import torch.nn.functional as F
from torch.nn import BCEWithLogitsLoss
from torch.nn import ModuleList, Linear, Conv1d, MaxPool1d, Embedding
from torch.utils.data import DataLoader

from torch_sparse import coalesce
from torch_scatter import scatter_min
import torch_geometric.transforms as T
from torch_geometric.nn import GCNConv, SAGEConv, global_sort_pool, global_add_pool
from torch_geometric.data import Data, Dataset, InMemoryDataset, DataLoader
from torch_geometric.utils import (negative_sampling, add_self_loops,
                                   train_test_split_edges, to_networkx, 
                                   to_scipy_sparse_matrix, to_undirected)

import warnings
from scipy.sparse import SparseEfficiencyWarning
warnings.simplefilter('ignore',SparseEfficiencyWarning)

from enclosing_subgraph import *

class WLDynamicDataset(Dataset):
    def __init__(self, root, data, split_edge, num_hops, percent=100, split='train', 
                 use_coalesce=False, node_label='drnl', ratio_per_hop=1.0, 
                 max_nodes_per_hop=None, **kwargs):
        self.data = data
        self.split_edge = split_edge
        self.num_hops = num_hops
        self.percent = percent
        self.use_coalesce = use_coalesce
        self.node_label = node_label
        self.ratio_per_hop = ratio_per_hop
        self.max_nodes_per_hop = max_nodes_per_hop
        super(WLDynamicDataset, self).__init__(root)

        pos_edge, neg_edge = get_pos_neg_edges(split, self.split_edge, 
                                               self.data.edge_index, 
                                               self.data.num_nodes, 
                                               self.percent)
        self.links = torch.cat([pos_edge, neg_edge], 1).t().tolist()
        self.labels = [1] * pos_edge.size(1) + [0] * neg_edge.size(1)
        
        if self.use_coalesce:  # compress mutli-edge into edge with weight
            self.data.edge_index, self.data.edge_weight = coalesce(
                self.data.edge_index, self.data.edge_weight, 
                self.data.num_nodes, self.data.num_nodes)

        if 'edge_weight' in self.data:
            edge_weight = self.data.edge_weight.view(-1)
        else:
            edge_weight = torch.ones(self.data.edge_index.size(1), dtype=int)
        self.A = ssp.csr_matrix(
            (edge_weight, (self.data.edge_index[0], self.data.edge_index[1])), 
            shape=(self.data.num_nodes, self.data.num_nodes)
        )
        
    def __len__(self):
        return len(self.links)

    def process(self):
        for idx in range(len(self.links)):
            src, dst = self.links[idx]

            if self.labels[idx]: status = "pos"
            else: status = "neg"

            tmp = k_hop_subgraph(src, dst, self.num_hops, self.A, status, self.ratio_per_hop, 
                                 self.max_nodes_per_hop, node_features=self.data.x)
            data = construct_pyg_graph(*tmp, self.node_label)

            torch.save(data, osp.join(self.processed_dir, 'data_{}.pt'.format(idx)))

    def get(self, idx):
        data = torch.load(osp.join(self.processed_dir, 'data_{}.pt'.format(idx)))
        return data

我收到此错误:

Traceback (most recent call last):
  File "/path/to/run.py", line 302, in <module>
    main()
  File "/path/to/run.py", line 79, in main
    max_nodes_per_hop=args.max_nodes_per_hop,
  File "/path/to/DataSet.py", line 106, in __init__
    super(WLDynamicDataset, self).__init__(root)
  File "/n/home01/vym1/.local/lib/python3.7/site-packages/torch_geometric/data/dataset.py", line 92, in __init__
    self._process()
  File "/n/home01/vym1/.local/lib/python3.7/site-packages/torch_geometric/data/dataset.py", line 165, in _process
    self.process()
  File "/path/to/DataSet.py", line 137, in process
    for idx in range(len(self.links)):
AttributeError: 'WLDynamicDataset' object has no attribute 'links'

我在关于班级的开始中明确定义了它(即。self.links)。不知道为什么它不会显示。有谁知道为什么?

更新:添加了导入和完整的回溯。run.py是我运行的脚本,它把这个脚本叫做DataSet.py

标签: python

解决方案


TL;博士:

更改process方法的名称。或者,如果您有意覆盖它,请确保self.links__init__调用super().


__init__您已经覆盖了在of中调用的方法DataSet。您的简化版本__init__是:

class WLDynamicDataset(Dataset):
    def __init__(...):
        ...
        super(WLDynamicDataset, self).__init__(root)

        ...
        self.links = torch.cat([pos_edge, neg_edge], 1).t().tolist()

现在从回溯中,您有以下从super()调用开始的堆栈:

WLDynamicDataset.__init__ --> super(WLDynamicDataset, self).__init__(root) =>
    Dataset.__init__ --> self._process() =>
       Dataset._process --> self.process() =>
           WLDynamicDataset.process --> self.links

然后你在它被定义之前引用self.linksin 。process__init__


推荐阅读