1、什么是Pytorch,为什么选择Pytroch?
- 深度学习框架
2、Pytroch的安装
conda install pytorch-cpu torchvision-cpu -c pytorch
3.配置Python环境
- Anaconda
4.准备Python管理器
- Anaconda
5.通过命令行安装PyTorch
conda install pytorch-cpu torchvision-cpu -c pytorch
6.PyTorch基础概念
- Tensor:张量(多维数组)
7.通用代码实现流程(实现一个深度学习的代码流程)
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
device = torch.device("cpu")
# Hyper-parameters
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
# MNIST dataset
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())
# Data loader
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)
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Move tensors to the configured device
images = images.reshape(-1, 28 * 28).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
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()))
# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28*28).to(device)
labels = labels.to(device)
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: {} %'.format(100 * correct / total))
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to data/MNIST\raw\train-images-idx3-ubyte.gz
100.1%
Extracting data/MNIST\raw\train-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to data/MNIST\raw\train-labels-idx1-ubyte.gz
113.5%
Extracting data/MNIST\raw\train-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to data/MNIST\raw\t10k-images-idx3-ubyte.gz
100.4%
Extracting data/MNIST\raw\t10k-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to data/MNIST\raw\t10k-labels-idx1-ubyte.gz
180.4%
Extracting data/MNIST\raw\t10k-labels-idx1-ubyte.gz
Processing...
Done!
Epoch [1/5], Step [100/600], Loss: 0.5448
Epoch [1/5], Step [200/600], Loss: 0.2312
Epoch [1/5], Step [300/600], Loss: 0.1262
Epoch [1/5], Step [400/600], Loss: 0.1997
Epoch [1/5], Step [500/600], Loss: 0.1929
Epoch [1/5], Step [600/600], Loss: 0.1126
Epoch [2/5], Step [100/600], Loss: 0.1524
Epoch [2/5], Step [200/600], Loss: 0.1506
Epoch [2/5], Step [300/600], Loss: 0.0732
Epoch [2/5], Step [400/600], Loss: 0.1012
Epoch [2/5], Step [500/600], Loss: 0.0507
Epoch [2/5], Step [600/600], Loss: 0.0819
Epoch [3/5], Step [100/600], Loss: 0.0578
Epoch [3/5], Step [200/600], Loss: 0.0737
Epoch [3/5], Step [300/600], Loss: 0.0596
Epoch [3/5], Step [400/600], Loss: 0.0587
Epoch [3/5], Step [500/600], Loss: 0.0475
Epoch [3/5], Step [600/600], Loss: 0.0561
Epoch [4/5], Step [100/600], Loss: 0.0366
Epoch [4/5], Step [200/600], Loss: 0.0558
Epoch [4/5], Step [300/600], Loss: 0.0533
Epoch [4/5], Step [400/600], Loss: 0.0772
Epoch [4/5], Step [500/600], Loss: 0.0362
Epoch [4/5], Step [600/600], Loss: 0.0635
Epoch [5/5], Step [100/600], Loss: 0.0400
Epoch [5/5], Step [200/600], Loss: 0.0172
Epoch [5/5], Step [300/600], Loss: 0.0518
Epoch [5/5], Step [400/600], Loss: 0.0423
Epoch [5/5], Step [500/600], Loss: 0.0595
Epoch [5/5], Step [600/600], Loss: 0.0842
Accuracy of the network on the 10000 test images: 97.62 %