卷积神经网络无属性错误

No attribute error for Convolutional Neural Networks

提问人:Brandon Doh 提问时间:11/8/2023 更新时间:11/8/2023 访问量:17

问:

第 57 行“x = self.conv_output(x)”处出现无属性错误,表示conv_output没有属性。

!pip install nibabel
import nibabel as nib
import numpy as np
import os

# Define the path to your NIfTI files
nifti_dir = '/work/Cannabis'

# List the NIfTI files in the directory
nifti_files = [os.path.join(nifti_dir, file) for file in os.listdir(nifti_dir) if file.endswith('.nii.gz')]

# Define a function to load and preprocess the NIfTI files
def load_and_preprocess_nifti(file_path):
    nifti_data = nib.load(file_path)  # Load the NIfTI file
    nifti_array = nifti_data.get_fdata()  # Get the image data as a NumPy array

    # Perform any necessary preprocessing here, such as resizing, normalization, etc.
    # nifti_array = your_preprocessing_function(nifti_array)

    return nifti_array

# Create an empty list to store the preprocessed NIfTI data
data_list = []

# Load and preprocess each NIfTI file
for file in nifti_files:
    preprocessed_data = load_and_preprocess_nifti(file)
    data_list.append(preprocessed_data)

# Convert the list of preprocessed data to a NumPy array
data_array = np.array(data_list)

# Define your CNN architecture
import torch
import torch.nn as nn


class SimpleCNN(nn.Module):
    def _SimpleCNN__init__(self):
        super().__init__()
        
        # Assuming conv_output is the output of the last convolutional layer
        # Shape of conv_output: (batch_size, num_channels, height, width)
        
        # Flatten the last convolutional layer's output
        self.conv_output = nn.Flatten()
        
        # Calculate the product of the spatial dimensions (ignoring the batch size)
        input_size = data_array.shape[1] * data_array.shape[2] * data_array.shape[3]
        
        # Reshape the input tensor to match the expected input size
        self.fc1 = nn.Linear(input_size, 64)
        self.fc2 = nn.Linear(64, 2)  # Define num_classes
        

    def forward(self, x):
        x = self.conv_output(x)
        x = self.fc1(x)
        x = torch.relu(x)
        x = self.fc2(x)
        return x

# Instantiate the CNN model
model = SimpleCNN()

# Convert the 'data_array' to a PyTorch tensor
input_tensor = torch.from_numpy(data_array).float()

# Make predictions using your CNN
output = model(input_tensor)

下面是代码的完整错误消息

AttributeError                            Traceback (most recent call last)
Cell In [5], line 70
     67 input_tensor = torch.from_numpy(data_array).float()
     69 # Make predictions using your CNN
---> 70 output = model(input_tensor)

File /shared-libs/python3.9/py/lib/python3.9/site-packages/torch/nn/modules/module.py:1130, in Module._call_impl(self, *input, **kwargs)
   1126 # If we don't have any hooks, we want to skip the rest of the logic in
   1127 # this function, and just call forward.
   1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1129         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130     return forward_call(*input, **kwargs)
   1131 # Do not call functions when jit is used
   1132 full_backward_hooks, non_full_backward_hooks = [], []

Cell In [5], line 57, in SimpleCNN.forward(self, x)
     56 def forward(self, x):
---> 57     x = self.conv_output(x)
     58     x = self.fc1(x)
     59     x = torch.relu(x)

File /shared-libs/python3.9/py/lib/python3.9/site-packages/torch/nn/modules/module.py:1207, in Module.__getattr__(self, name)
   1205     if name in modules:
   1206         return modules[name]
-> 1207 raise AttributeError("'{}' object has no attribute '{}'".format(
   1208     type(self).__name__, name))

AttributeError: 'SimpleCNN' object has no attribute 'conv_output'

我试图将 conv_output 定义为 None,但它仍然说没有 conv_output 的属性。您能否给我有关代码修订的建议,以便代码不再出现任何属性错误。

机器学习 conv-neural-network attributeerror

评论

0赞 lejlot 11/8/2023
这只是一个错别字def _SimpleCNN__init__(self): --> def __init__(self):
0赞 Dr. Snoopy 11/8/2023
我不会说这是错别字,整个名字是不正确的。
0赞 Brandon Doh 11/9/2023
错误已修复,谢谢 😅

答: 暂无答案