本文主要是介绍【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture10 Basic_CNN,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture10 Basic_CNN
部分课件内容:
代码:
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.nn.functional as Fbatch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) #把原始图像转为tensor 这是均值和方差train_set = datasets.MNIST(root='./data/mnist', train=True, download=True, transform=transform)
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)test_set = datasets.MNIST(root='./data/mnist', train=False, download=True, transform=transform)
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=True)
class Net(torch.nn.Module):def __init__(self):super(Net, self).__init__()self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)self.pooling = torch.nn.MaxPool2d(kernel_size=2)self.fc1 = torch.nn.Linear(320, 10)def forward(self, x):batch_size = x.size(0)x = F.relu(self.pooling(self.conv1(x), ))x = F.relu(self.pooling(self.conv2(x), ))x = x.view(batch_size,-1) # flattenx = self.fc1(x)return xmodel = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') #把模型迁移到GPU
model = model.to(device) #把模型迁移到GPUdef train(epoch):running_loss = 0.0for i, data in enumerate(train_loader, 0):inputs, labels = datainputs,labels = inputs.to(device), labels.to(device) #训练内容迁移到GPU上optimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()running_loss += loss.item()if i % 300 == 299: # print every 300 mini-batchesprint('[%d, %5d] loss: %.3f' %(epoch + 1, i + 1, running_loss / 300))running_loss = 0.0def test(epoch):correct = 0total = 0with torch.no_grad():for data in test_loader:images, labels = dataimages,labels = images.to(device), labels.to(device) #测试内容迁移到GPU上outputs = model(images)_, predicted = torch.max(outputs.data, 1)total += labels.size(0)correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))if __name__ == '__main__':for epoch in range(100):train(epoch)if epoch % 10 == 0:test(epoch)
这篇关于【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture10 Basic_CNN的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!