【已解決】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
- Python3類方法報錯takes 0 positional arguments but 1 was givenPython
- TypeError: object() takes no parametersErrorObject
- TypeError: The ‘compilation‘ argument must be an instance of Compilation 報錯Error
- 解決The given version [xx] is not supported, only version 1 to 10 is supported in this buildUI
- python argument 1 must be 2-item sequence, not intPython
- JPA-style positional param was not an integral ordinal錯誤解決辦法
- @Autowired 注入 **required a single bean, but 2 were found**UIBean
- 解決 TypeError: Type aliases cannot be used with isinstance(). 辦法Error
- TypeError: Descriptors cannot not be created directly問題的解決Error
- 解決jpa查詢時,Unable to locate Attribute with the the given name錯誤
- npm報錯 TypeError [ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string.Received undefineNPMError
- 刪除大量檔案Argument list too long錯誤解決
- 問題解決:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- Flutter+小程式容器: 1+1>2的解決方案Flutter
- If I were a boy againAI
- 【已解決】Error filter ListenerStartErrorFilter
- lombok 註解無效 已解決Lombok
- 1.python報錯:TypeError: 'int' object is not subscriptablePythonErrorObject
- el-table翻頁序號不從1開始(已解決)
- linux inode已滿解決方法Linux
- 已解決——ROS2開發環境搭建,亞博智慧小車ROS開發環境
- zblog升級報錯“Invalid argument supplied for foreach”或者“unserialize(): Error at offset”的解決辦法Error
- onMounted is called when there is no active component 已解決
- 【已解決】挖礦病毒 logrotate 185.196.8.123logrotate
- ZBlog升級1.7報錯“Invalid argument supplied for foreach”或者“unserialize(): Error at offset”的解決辦法Error
- takes_ownership(s)語句執行
- Uncaught TypeError: external_echarts_.helper.createTextStyle is not a functionat Object.seriesModel.layoutInstance.ondraw問題的解決ErrorEchartsFunctionObject
- missing ) after argument list
- find: missing argument to `-exec'
- redis lRem 刪除失敗?(已解決)RedisREM
- 【已解決】IDEA 2020.3 java.lang.UnsupportedClassVersionErrorIdeaJavaError
- 解決已安裝opencv但仍提示報錯“no module named cv2“問題OpenCV
- 詳解Python魔法函式,__init__,__str__,__del__Python函式
- Python中的__init__()方法整理中(兩種解釋)Python
- Linux 中 2>&1 解釋Linux
- TypeError: “ModelBase is not iterable”Error
- TypeError: SizeOnlySource is not a constructorErrorStruct