文章目录
- pytorch 神经网络训练demo
- Result
- 参考来源
pytorch 神经网络训练demo
数据集:MNIST
该数据集的内容是手写数字识别,其分为两部分,分别含有60000张训练图片和10000张测试图片
图片来源:https://tensornews.cn/mnist_intro/
神经网络:RNN, GRU, LSTM
# Importsimport torchimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torch.utils.data import DataLoaderimport torchvision.datasets as datasetsimport torchvision.transforms as transforms# Set devicedevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')# Hyperparametersinput_size = 28sequence_length = 28num_layers = 2hidden_size = 256num_classes = 10learning_rate = 0.001batch_size = 64num_epochs = 2# Create a RNNclass RNN(nn.Module):def __init__(self, input_size, hidden_size, num_layers, num_classes):super(RNN, self).__init__()self.hidden_size = hidden_sizeself.num_layers = num_layersself.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)self.fc = nn.Linear(hidden_size*sequence_length, num_classes) # fully connecteddef forward(self, x):h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)# Forward Propout, _ = self.rnn(x, h0)out = out.reshape(out.shape[0], -1)out = self.fc(out)return out# Create a GRUclass RNN_GRU(nn.Module):def __init__(self, input_size, hidden_size, num_layers, num_classes):super(RNN_GRU, self).__init__()self.hidden_size = hidden_sizeself.num_layers = num_layersself.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)self.fc = nn.Linear(hidden_size*sequence_length, num_classes) # fully connecteddef forward(self, x):h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)# Forward Propout, _ = self.gru(x, h0)out = out.reshape(out.shape[0], -1)out = self.fc(out)return out# Create a LSTMclass RNN_LSTM(nn.Module):def __init__(self, input_size, hidden_size, num_layers, num_classes):super(RNN_LSTM, self).__init__()self.hidden_size = hidden_sizeself.num_layers = num_layersself.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)self.fc = nn.Linear(hidden_size*sequence_length, num_classes) # fully connecteddef 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 Propout, _ = self.lstm(x, (h0, c0))out = out.reshape(out.shape[0], -1)out = self.fc(out)return out# Load datatrain_dataset = datasets.MNIST(root='dataset/',train=True,transform=transforms.ToTensor(), download=True)train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)test_dataset = datasets.MNIST(root='dataset/', train=False,transform=transforms.ToTensor(), download=True)test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)# Initialize network 选择一个即可model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)# model = RNN_GRU(input_size, hidden_size, num_layers, num_classes).to(device)# model = RNN_LSTM(input_size, hidden_size, num_layers, num_classes).to(device)# Loss and optimizercriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=learning_rate)# Train networkfor epoch in range(num_epochs):# data: images, targets: labelsfor batch_idx, (data, targets) in enumerate(train_loader):# Get data to cuda if possibledata = data.to(device).squeeze(1) # 删除一个张量中所有维数为1的维度 (N, 1, 28, 28) -> (N, 28, 28)targets = targets.to(device)# forwardscores = model(data) # 64*10loss = criterion(scores, targets)# backwardoptimizer.zero_grad()loss.backward()# gradient descent or adam stepoptimizer.step()# Check accuracy on training & test to see how good our modeldef check_accuracy(loader, model):if loader.dataset.train:print("Checking accuracy on training data")else:print("Checking accuracy on test data")num_correct = 0num_samples = 0model.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) # 64*784scores = model(x)# 64*10_, predictions = scores.max(dim=1) #dim=1,表示对每行取最大值,每行代表一个样本。num_correct += (predictions == y).sum()num_samples += predictions.size(0) # 64print(f'Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}%')model.train()check_accuracy(train_loader, model)check_accuracy(test_loader, model)
Result
RNN ResultChecking accuracy on training dataGot 57926 / 60000 with accuracy 96.54%Checking accuracy on test dataGot 9640 / 10000 with accuracy 96.40%GRU ResultChecking accuracy on training dataGot 59058 / 60000 with accuracy 98.43%Checking accuracy on test dataGot 9841 / 10000 with accuracy 98.41%LSTM ResultChecking accuracy on training dataGot 59248 / 60000 with accuracy 98.75%Checking accuracy on test dataGot 9849 / 10000 with accuracy 98.49%
参考来源
【1】https://www.youtube.com/watch?v=Gl2WXLIMvKA&list=PLhhyoLH6IjfxeoooqP9rhU3HJIAVAJ3Vz&index=5