【已解決】TypeError: __init__() takes 1 positional argument but 2 were given

Who is abc發表於2019-03-10

convolutional_neural_network程式碼

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

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

num_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001

train_dataset = torchvision.datasets.MNIST(root='../../data',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)
test_dataset = torchvision.datasets.MNIST(root='../../data',
                                          train=False,
                                          transform=transforms.ToTensor())

train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)


class ConvNet(nn.Module):
    def __init(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),  # shape(100, 16, 28, 28)
            nn.BatchNorm2d(16),  # shape(100, 16, 28, 28)
            nn.ReLU(),   # shape(100, 16, 28, 28)
            nn.MaxPool2d(kernel_size=2, stride=2)   # shape(100, 16, 14, 14)
        )
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=1), # shape(100, 32, 14, 14)
            nn.BatchNorm2d(32), # shape(100, 32, 14, 14)
            nn.ReLU(),  # shape(100, 32, 14, 14)
            nn.MaxPool2d(kernel_size=2, stride=2)  # shape(100, 32, 7, 7)
        )
        self.fc = nn.Linear(7 * 7 * 32, num_classes)

    def forward(self, x):  # x.shape (100, 1, 28, 28)
        out = self.layer1(x)  # out.shape (100, 16, 14, 14)
        out = self.layer2(out) # out.shape (100, 32, 7, 7) 
        out = out.reshape(out.size(0), -1)  # out.shape(100, 1586)
        out = self.fc(out)  # out.shape (100, 10) 
        return out


model = ConvNet(num_classes).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)  # shape (100, 1, 28, 28)
        labels = labels.to(device)

        outputs = model(images)  # shape (100, 10)
        loss = criterion(outputs, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
model.eval()
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device)
        labels = labels.to(device)

        outputs = model(images)
        _, prediction = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (prediction == labels).sum().item()

    print('Test Accuracy of the model on the 10000 test image is {}'.format(correct / total))

torch.save(model.state_dict(), 'model.ckpt')

程式碼報錯

TypeError: __init__() takes 1 positional argument but 2 were given

出錯原因

在第30行

	def __init(self, num_classes=10):

__init__函式沒有寫完整,補全為__init__即可

參考

pytorch-tutorial/tutorials/02-intermediate/convolutional_neural_network/main.py
torch.nn.BatchNorm2d
torch.nn.Conv2d
torch.nn.MaxPool2d

相關文章