The error "RuntimeError: The expanded size of the tensor (1) must match the existing size (4) at non-singleton dimension 0. Target sizes: [1, 40, 40]. Tensor sizes: [4, 40, 40]" occurs due to a mismatch between the size of the image tensor and the size of the node_features[j] tensor within the load_node_features function.

The load_node_features function creates an empty tensor node_features with a shape of (num_nodes, 1, image_size, image_size). Subsequently, it loads an image for each node and converts it into a tensor. However, the loaded image tensor might have a size different from node_features[j], leading to the error.

To resolve this, you need to ensure that the loaded image tensor matches the size of node_features[j]. This can be accomplished by resizing the image tensor to the desired size before assigning it to node_features[j].

Here's an updated version of the load_node_features function incorporating this fix:

def load_node_features(num_graphs, num_nodes, image_size):  
    all_node_features = torch.empty(num_graphs, num_nodes, 1, image_size, image_size, dtype=torch.float)  
  
    for i in range(num_graphs):  
        node_features = torch.empty(num_nodes, 1, image_size, image_size, dtype=torch.float)  
  
        for j in range(num_nodes):  
            file_path = f'C:\Users\jh\Desktop\data\input\images\{i+1}.png_{j}.png'  
  
            # Load image and convert to tensor  
            image = PIL.Image.open(file_path)  
            image = transforms.Resize((image_size, image_size))(image) # Resize image to desired size  
            image = transforms.ToTensor()(image)  
  
            node_features[j] = image  
  
        all_node_features[i] = node_features  
  
    return all_node_features  

By using transforms.Resize to resize the image tensor to (image_size, image_size), you guarantee that its size aligns with the size of node_features[j], thus eliminating the error.

Fixing RuntimeError: Expanded Size Mismatch in PyTorch GCN Model

原文地址: https://www.cveoy.top/t/topic/pk7m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录