我正在Pytorch
中使用CNN学习图像分类。在我开始构建CNN
体系结构时,我遇到了2个问题:
运行代码时,我得到的警告是-warnings.warn("train_labels has been renamed targets")
虽然我尝试使用print
函数打印损失和准确性,但没有打印任何内容。
为了您的更好理解,我在这里发布了我的代码。 先谢谢了。感谢您在这些问题上提供的帮助和提示。
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.drop_out(out)
out = self.fc1(out)
out = self.fc2(out)
return out
from torch import optim
model = ConvNet()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
loss_list = []
acc_list = []
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
outputs = model(images)
loss = criterion(outputs, labels)
loss_list.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
total = labels.size(0)
_, predicted = torch.max(outputs.data, 1)
correct = (predicted == labels).sum().item()
acc_list.append(correct / total)
if (i + 1) % 100 == 0:
print("Epoch [{}\{}], Step [{}\{}], Loss: {:.4f}, Accuracy: {:.2f}%"
.format(epoch + 1, num_epochs, i + 1, total_step, loss.item(),
correct / total) * 100)
# Test the model
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print("Test Accuracy of the model on the 10000 test images: {} %".format((correct / total) * 100))