开发者社区  >  开发问答  >  大佬帮我看看,为啥我这个模型运行时,运行到调用类的地方一直报错?

大佬帮我看看,为啥我这个模型运行时,运行到调用类的地方一直报错?


我这个AlexNet运行train文件时,调用model文件里的类,一直提示下图的这个错误,但是我检查了好几遍,num_classes这个变量都是

1592573821(1)




model文件:


import torch.nn as nn

import torch

class AlexNet(nn.Module):

    def _init_(self,num_classes=1000,init_weights=False):

        super(AlexNet,self)._init_()

        self.features=nn.sequential(

            nn.Conv2d(3,48,kernel_size=11,stride=4,padding=2),

            nn.ReLU(inplace=True),

            nn.MaxPool2d(kernel_size=3,stride=2),

            nn.Conv2d(48,128,kernel_size=5,padding=2),

            nn.ReLU(inplace=True),

            nn.MaxPool2d(kernel_size=3,stride=2),

            nn.Conv2d(128,192,kernel_size=3,padding=1),

            nn.ReLU(inplace=True),

            nn.Conv2d(192,192,kernel_size=3,padding=1),

            nn.ReLU(inplace=True),

            nn.Conv2d(192,128,kernel_size=3,padding=1),

            nn.ReLU(inplace=True),

            nn.MaxPool2d(kernel_size=3,stride=2),

        )

        self.classifier=nn.Sequential(

            nn.Dropout(p=0.5),

            nn.Linear(128*6*6,2048),

            nn.ReLU(inplace=True),

            nn.Dropout(p=0.5),

            nn.Linear(2048,2048),

            nn.ReLU(inplace=True),

            nn.Linear(2048,num_classes),

        )

        if init_weights:

            self._initialize_weights()

            

    def forward(self,x):

        x=self.features(x)

        x=torch.flatten(x,start_dim=1)

        x=self.classifier(x)

        return x

    

    def _initialize_weights(self):

        for m in self.modules():

            if isinstance(m,nn.Conv2d):

                nn.init.kaiming_normal_(m.weight,mode='fan_out',nonlinearity='relu')

                if m.bias is not None:

                    nn.init.constant_(m.bias,0)

            elif isinstance(m,nn.Linear):

                nn.init.normal_(m.weight,0,0.01)

                nn.init.contant_(m.bias,0)


train文件:


import torch

import torch.nn as nn

from torchvision import transforms, datasets, utils

import matplotlib.pyplot as plt

import numpy as np

import torch.optim as optim

from model import AlexNet

import os

import json

import time

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

print(device)

data_transform = {

    "train": transforms.Compose([transforms.RandomResizedCrop(224),

                                 transforms.RandomHorizontalFlip(),

                                 transforms.ToTensor(),

                                 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]),

    "val": transforms.Compose([transforms.Resize((224, 224)),  # cannot 224, must (224, 224)

                               transforms.ToTensor(),

                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}

# data_root = os.path.abspath(os.path.join(os.getcwd(), "../.."))  # get data root path

# image_path = data_root + "\\data_set\\flower_data\\"  # flower data set path

# train_dataset = datasets.ImageFolder(root=image_path + "train",

#                                      transform=data_transform["train"])

train_dataset = datasets.ImageFolder(root='C:/Users/hubaolin/Desktop/CV/B/AlexNet/data_set/flower_data/train',

                                     transform=data_transform["train"])

#'C:\\Users\\hubaolin\\Desktop\\CV\\data_set\\flower_data\\train'

train_num = len(train_dataset)

# {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}

flower_list = train_dataset.class_to_idx

cla_dict = dict((val, key) for key, val in flower_list.items())

# write dict into json file

json_str = json.dumps(cla_dict, indent=4)

with open('class_indices.json', 'w') as json_file:

    json_file.write(json_str)

batch_size = 32

train_loader = torch.utils.data.DataLoader(train_dataset,

                                           batch_size=batch_size, shuffle=True,

                                           num_workers=0)

#validate_dataset = datasets.ImageFolder(root=image_path + "/val",

#                                        transform=data_transform["val"])

validate_dataset = datasets.ImageFolder(root='C:/Users/hubaolin/Desktop/CV/B/AlexNet/data_set/flower_data/train',

                                        transform=data_transform["val"])

val_num = len(validate_dataset)

validate_loader = torch.utils.data.DataLoader(validate_dataset,

                                              batch_size=4, shuffle=True,

                                              num_workers=0)

# test_data_iter = iter(validate_loader)

# test_image, test_label = test_data_iter.next()

# def imshow(img):

#     img = img / 2 + 0.5  # unnormalize

#     npimg = img.numpy()

#     plt.imshow(np.transpose(npimg, (1, 2, 0)))

#     plt.show()

# print(' '.join('%5s' % cla_dict[test_label[j].item()] for j in range(4)))

# imshow(utils.make_grid(test_image))

net = AlexNet(num_classes=5, init_weights=True)

net.to(device)

loss_function = nn.CrossEntropyLoss()

# pata = list(net.parameters())

optimizer = optim.Adam(net.parameters(), lr=0.0002)

save_path = './AlexNet.pth'

best_acc = 0.0

for epoch in range(10):

    # train

    net.train()

    running_loss = 0.0

    t1 = time.perf_counter()

    for step, data in enumerate(train_loader, start=0):

        images, labels = data

        optimizer.zero_grad()

        outputs = net(images.to(device))

        loss = loss_function(outputs, labels.to(device))

        loss.backward()

        optimizer.step()

        # print statistics

        running_loss += loss.item()

        # print train process

        rate = (step + 1) / len(train_loader)

        a = "*" * int(rate * 50)

        b = "." * int((1 - rate) * 50)

        print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate * 100), a, b, loss), end="")

    print()

    print(time.perf_counter()-t1)

    # validate

    net.eval()

    acc = 0.0  # accumulate accurate number / epoch

    with torch.no_grad():

        for val_data in validate_loader:

            val_images, val_labels = val_data

            outputs = net(val_images.to(device))

            predict_y = torch.max(outputs, dim=1)[1]

            acc += (predict_y == val_labels.to(device)).sum().item()

        val_accurate = acc / val_num

        if val_accurate > best_acc:

            best_acc = val_accurate

            torch.save(net.state_dict(), save_path)

        print('[epoch %d] train_loss: %.3f  test_accuracy: %.3f' %(epoch + 1, running_loss / step, val_accurate))

print('Finished Training')


相关回答 

nevermind 18天前 3声望

调了一下好像出结果了


(0) 回复

VueGirl 18天前 207声望


__init__ 函数接受到一个 未知的/超预期的 关键字参数。 

(0) 回复

VueGirl 18天前 207声望

import torch.nn as nn

import torch

class AlexNet(nn.Module):

    def _init_(self,unm_classes=1000,init_weights=False):

num_classes ?   unm_classes ?


(0) 回复

nevermind 回复 VueGirl 18天前

不是,那一段我手输的,你看截图,原代码时num_classes。内容里的改掉了。

(0) 回复

相关问答

等待回答