Torch使用
数据载入:
class MyDataset(Dataset):
# TensorDataset继承Dataset, 重载了__init__, __getitem__, __len__
def __init__(self, imagepath,mytransformer):
self.imagepath = imagepath
self.transformer = mytransformer
def __getitem__(self,index):
img = cv2.imread(self.imagepath) # 读取图像
img1 = self.transformer(img)
return img1
def __len__(self):
return len(self.imagepath)
使用方法:
mydataset = MyDataset(img_path,mytrans)
tensor_dataloader = DataLoader(mydataset, # 封装的对象
batch_size=1, # 输出的batchsize
shuffle=True, # 随机输出
num_workers=0) # 只有1个进程
训练流程:
mnist_net = MnistNet()
optimizer = optim.Adam(mnist_net.parameters(), lr=0.001)
for idx, (data, target) in enumerate(train_dataloader):#数据获取
optimizer.zero_grad() #梯度清零
output = mnist_net(data) #前向传播
loss = F.nll_loss(output, target) # 计算loss
loss.backward()#反向传播
optimizer.step()#权重更新
????????
????if idx % 10 == 0: #显示和保存模型
????print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, idx * len(data), len(train_dataloader.dataset),
100. * idx / len(train_dataloader), loss.item()))
torch.save(mnist_net.state_dict(), "model/mnist_net.pkl")
torch.save(optimizer.state_dict(), 'results/mnist_optimizer.pkl')
测试流程:
????????
test_loss = 0
correct = 0
mnist_net.eval()
test_dataloader = get_dataloader(train=False) #数据加载
with torch.no_grad():#无梯度计算
for data, target in test_dataloader:#得到 数据
output = mnist_net(data)#前向传播
test_loss += F.nll_loss(output, target, reduction='sum').item()#计算loss或者是判断正确和错误
pred = output.data.max(1, keepdim=True)[1] # 获取最大值的位置,[batch_size,1]
correct += pred.eq(target.data.view_as(pred)).sum()#进行计数,这部分可以根据实际情况写
test_loss /= len(test_dataloader.dataset)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
test_loss, correct, len(test_dataloader.dataset),
100. * correct / len(test_dataloader.dataset)))
附torch中封装的网络们:
https://pytorch.org/vision/stable/models.html
一般的需求都可以满足,不用自己实现太复杂的;需要自己来做数据处理;
附transformer,数据扩充预处理的用法:
train_transformer = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize([5,1]),
#transforms.RandomResizedCrop(224,scale=(0.5,1.0)),
#transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
#transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
#transforms.ToTensor()
#transforms.ToPILImage()
])
所有的图像扩充方法可以看:
https://pytorch.org/vision/stable/transforms.html
https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#sphx-glr-auto-examples-plot-transforms-py
里面也有random模块,还是相当人性化;
附device:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))
|