参考Aladdin Persson的视频
全连接神经网络:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
class NN(nn.Module):
def __init__(self, input_size, num_classes):
super(NN, self).__init__()
self.fc1 = nn.Linear(input_size, 50)
self.fc2 = nn.Linear(50, num_classes)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
input_size = 784
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 1
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = NN(input_size=input_size, num_classes=num_classes).to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device)
targets = targets.to(device)
data = data.reshape(data.shape[0], -1)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device)
y = y.to(device)
x = x.reshape(x.shape[0], -1)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct)/num_samples*100:.2f}')
model.train()
check_accuracy(train_loader,model)
check_accuracy(test_loader,model)
CNN:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
class CNN(nn.Module):
def __init__(self, in_channels=1, num_classes=10):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
self.pool = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
self.conv2 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
self.fc1 = nn.Linear(16 * 7 * 7, num_classes)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool(x)
x = F.relu(self.conv2(x))
x = self.pool(x)
x = x.reshape(x.shape[0], -1)
x = self.fc1(x)
return x
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
in_channel = 1
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 1
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = CNN().to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device)
targets = targets.to(device)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device)
y = y.to(device)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct) / num_samples * 100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader, model)
RNN:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
input_size = 28
sequence_length = 28
num_layers = 2
hidden_size = 256
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 2
# RNN
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size * sequence_length, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# Forward Prop
out, _ = self.rnn(x, h0)
out = out.reshape(out.shape[0], -1)
out = self.fc(out)
return out
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device).squeeze(1)
targets = targets.to(device)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device).squeeze(1)
y = y.to(device)
#x = x.reshape(x.shape[0], -1)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct) / num_samples * 100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader, model)
GRU的改动很小:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
input_size = 28
sequence_length = 28
num_layers = 2
hidden_size = 256
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 2
# RNN
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size * sequence_length, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# Forward Prop
out, _ = self.gru(x, h0)
out = out.reshape(out.shape[0], -1)
out = self.fc(out)
return out
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device).squeeze(1)
targets = targets.to(device)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device).squeeze(1)
y = y.to(device)
#x = x.reshape(x.shape[0], -1)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct) / num_samples * 100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader, model)
LSTM:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
input_size = 28
sequence_length = 28
num_layers = 2
hidden_size = 256
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 2
# RNN
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size * sequence_length, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# Forward Prop
out, _ = self.lstm(x, (h0, c0))
out = out.reshape(out.shape[0], -1)
out = self.fc(out)
return out
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device).squeeze(1)
targets = targets.to(device)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device).squeeze(1)
y = y.to(device)
#x = x.reshape(x.shape[0], -1)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct) / num_samples * 100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader, model)
双向LSTM:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# hyperparameters超参数
input_size = 28
sequence_length = 28
num_layers = 2
hidden_size = 256
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 2
# LSTM
class BRNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(BRNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True,
bidirectional=True)
self.fc = nn.Linear(hidden_size*2, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)
out, (hidden_state, cell_state) = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
# Load Data
train_datasets = datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=False)
train_loader = DataLoader(dataset=train_datasets, batch_size=batch_size, shuffle=True)
test_datasets = datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=False)
test_loader = DataLoader(dataset=test_datasets, batch_size=batch_size, shuffle=False)
# 初始化神经网络
model = BRNN(input_size, hidden_size, num_layers, num_classes).to(device)
# 设置loss和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
# 将数据放到cuda中
data = data.to(device).squeeze(1)
targets = targets.to(device)
# forward
lables = model(data)
loss = criterion(lables, targets)
# backward
optimizer.zero_grad()
loss.backward()
# 梯度下降
optimizer.step()
def check_accuracy(loader, model):
if loader.dataset.train:
print("训练集准确率:")
else:
print("测试集准确率:")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device).squeeze(1)
y = y.to(device)
#x = x.reshape(x.shape[0], -1)
scores = model(x)
_, predictions = scores.max(1)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(f'{num_correct} / {num_samples},准确率{float(num_correct) / num_samples * 100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader, model)