这里还是使用MNIST数据集进行处理,直接上代码(不懂看注释~)
#导入相应包
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transform
#定义cuda加速
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#定义输入维度、隐藏层维度、输出维度、训练次数、batch大小、学习率
input_size = 28 * 28
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
#定义训练集测试集并转为DataLoader格式
train_dataset = torchvision.datasets.MNIST(root='data/',
train=True,
transform=transform.ToTensor(),
download=True)
test_dataset = torchvision.datasets.MNIST(root='data/',
train=False,
transform=transform.ToTensor())
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)
#定义模型
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)
#定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
for epoch in range(num_epochs):
#遍历数据集进行训练
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1, 28 * 28).to(device)
labels = labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if((i+1) % 100 == 0):
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch, num_epochs, i+1, total_step, loss.item()))
#设置无梯度模式进行测试查看精度
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)
_, predict = torch.max(outputs.data, 1)
total += labels.shape[0]
correct += (predict == labels).sum().item()
print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
torch.save(model.state_dict(), 'model.ckpt')
输出如下:
Epoch [0/5], Step [100/600], Loss: 0.1658
Epoch [0/5], Step [200/600], Loss: 0.3905
Epoch [0/5], Step [300/600], Loss: 0.1464
Epoch [0/5], Step [400/600], Loss: 0.2937
Epoch [0/5], Step [500/600], Loss: 0.2443
Epoch [0/5], Step [600/600], Loss: 0.0820
Epoch [1/5], Step [100/600], Loss: 0.1177
Epoch [1/5], Step [200/600], Loss: 0.1299
Epoch [1/5], Step [300/600], Loss: 0.1143
Epoch [1/5], Step [400/600], Loss: 0.0830
Epoch [1/5], Step [500/600], Loss: 0.1383
Epoch [1/5], Step [600/600], Loss: 0.0745
Epoch [2/5], Step [100/600], Loss: 0.1163
Epoch [2/5], Step [200/600], Loss: 0.0630
Epoch [2/5], Step [300/600], Loss: 0.0738
Epoch [2/5], Step [400/600], Loss: 0.0474
Epoch [2/5], Step [500/600], Loss: 0.0874
Epoch [2/5], Step [600/600], Loss: 0.1105
Epoch [3/5], Step [100/600], Loss: 0.0503
Epoch [3/5], Step [200/600], Loss: 0.0636
Epoch [3/5], Step [300/600], Loss: 0.0599
Epoch [3/5], Step [400/600], Loss: 0.0385
Epoch [3/5], Step [500/600], Loss: 0.0644
Epoch [3/5], Step [600/600], Loss: 0.0296
Epoch [4/5], Step [100/600], Loss: 0.0091
Epoch [4/5], Step [200/600], Loss: 0.0263
Epoch [4/5], Step [300/600], Loss: 0.0255
Epoch [4/5], Step [400/600], Loss: 0.0307
Epoch [4/5], Step [500/600], Loss: 0.0537
Epoch [4/5], Step [600/600], Loss: 0.0589
Accuracy of the network on the 10000 test images: 98.03 %
可以看到精度达到98%,而且我们还是比较简单的初级模型,并未对参数进行寻优,且为对数据进行处理。