【已解決】TypeError: __init__() takes 1 positional argument but 2 were given
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
相關文章
- Python成功解決TypeError: __init__() missing 1 required positional argument: ‘comment‘PythonErrorUI
- takes 0 positional arguments but 1 was given
- main() takes 0 positional arguments but 1 was givenAI
- bam檔案出錯行(takes from 3 to 5 positional arguments but 6 were given)
- Python 錯誤之函式takes 0 positional arguments but 1 was givenPython函式
- Python3類方法報錯takes 0 positional arguments but 1 was givenPython
- TypeError: object() takes no parametersErrorObject
- Python基礎——positional argument vs keyword argumentPython
- TypeError: The ‘compilation‘ argument must be an instance of Compilation 報錯Error
- python argument 1 must be 2-item sequence, not intPython
- TypeError: Descriptors cannot not be created directly問題的解決Error
- 解決 TypeError: Type aliases cannot be used with isinstance(). 辦法Error
- -bash: /bin/rm: Argument list too long的解決辦法
- JPA-style positional param was not an integral ordinal錯誤解決辦法
- npm報錯 TypeError [ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string.Received undefineNPMError
- 刪除大量檔案Argument list too long錯誤解決
- @Autowired 注入 **required a single bean, but 2 were found**UIBean
- 解決jpa查詢時,Unable to locate Attribute with the the given name錯誤
- 問題解決:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- Flutter+小程式容器: 1+1>2的解決方案Flutter
- 【已解決】Error filter ListenerStartErrorFilter
- lombok 註解無效 已解決Lombok
- Openlayers2切換supermap WMS服務底圖,已解決
- 1.python報錯:TypeError: 'int' object is not subscriptablePythonErrorObject
- el-table翻頁序號不從1開始(已解決)
- DOCTYPE探索【已翻譯100%】(1/2)
- DB2報“資料庫日誌已滿”問題解決DB2資料庫
- VISTA 資源管理器 已停止工作 解決方案(1)
- FatalThrowableError in index.php line 554:Type error: Argument 1 passedErrorIndexPHP
- If I were a boy againAI
- linux inode已滿解決方法Linux
- 已經解決java.lang.OutOfMemoryErrorJavaError
- TextInput should be given height
- 詳解Python中的__init__和__new__Python
- 詳細解讀Python中的__init__()方法Python
- redis lRem 刪除失敗?(已解決)RedisREM
- onMounted is called when there is no active component 已解決
- 已經學會並解決的事情