pytorch + visdom CNN處理自建圖片數(shù)據(jù)集的方法
環(huán)境
系統(tǒng):win10
cpu:i7-6700HQ
gpu:gtx965m
python : 3.6
pytorch :0.3
數(shù)據(jù)下載
來源自Sasank Chilamkurthy 的教程; 數(shù)據(jù):下載鏈接。
下載后解壓放到項(xiàng)目根目錄:
數(shù)據(jù)集為用來分類 螞蟻和蜜蜂。有大約120個(gè)訓(xùn)練圖像,每個(gè)類有75個(gè)驗(yàn)證圖像。
數(shù)據(jù)導(dǎo)入
可以使用 torchvision.datasets.ImageFolder(root,transforms) 模塊 可以將 圖片轉(zhuǎn)換為 tensor。
先定義transform:
ata_transforms = {
'train': transforms.Compose([
# 隨機(jī)切成224x224 大小圖片 統(tǒng)一圖片格式
transforms.RandomResizedCrop(224),
# 圖像翻轉(zhuǎn)
transforms.RandomHorizontalFlip(),
# totensor 歸一化(0,255) >> (0,1) normalize channel=(channel-mean)/std
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
]),
"val" : transforms.Compose([
# 圖片大小縮放 統(tǒng)一圖片格式
transforms.Resize(256),
# 以中心裁剪
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
}
導(dǎo)入,加載數(shù)據(jù):
data_dir = './hymenoptera_data'
# trans data
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}
# load data
data_loaders = {x: DataLoader(image_datasets[x], batch_size=BATCH_SIZE, shuffle=True) for x in ['train', 'val']}
data_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
print(data_sizes, class_names)
{'train': 244, 'val': 153} ['ants', 'bees']
訓(xùn)練集 244圖片 , 測(cè)試集153圖片 。
可視化部分圖片看看,由于visdom支持tensor輸入 ,不用換成numpy,直接用tensor計(jì)算即可 :
inputs, classes = next(iter(data_loaders['val'])) out = torchvision.utils.make_grid(inputs) inp = torch.transpose(out, 0, 2) mean = torch.FloatTensor([0.485, 0.456, 0.406]) std = torch.FloatTensor([0.229, 0.224, 0.225]) inp = std * inp + mean inp = torch.transpose(inp, 0, 2) viz.images(inp)

創(chuàng)建CNN
net 根據(jù)上一篇的處理cifar10的改了一下規(guī)格:
class CNN(nn.Module):
def __init__(self, in_dim, n_class):
super(CNN, self).__init__()
self.cnn = nn.Sequential(
nn.BatchNorm2d(in_dim),
nn.ReLU(True),
nn.Conv2d(in_dim, 16, 7), # 224 >> 218
nn.BatchNorm2d(16),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2), # 218 >> 109
nn.ReLU(True),
nn.Conv2d(16, 32, 5), # 105
nn.BatchNorm2d(32),
nn.ReLU(True),
nn.Conv2d(32, 64, 5), # 101
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.Conv2d(64, 64, 3, 1, 1),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.MaxPool2d(2, 2), # 101 >> 50
nn.Conv2d(64, 128, 3, 1, 1), #
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.MaxPool2d(3), # 50 >> 16
)
self.fc = nn.Sequential(
nn.Linear(128*16*16, 120),
nn.BatchNorm1d(120),
nn.ReLU(True),
nn.Linear(120, n_class))
def forward(self, x):
out = self.cnn(x)
out = self.fc(out.view(-1, 128*16*16))
return out
# 輸入3層rgb ,輸出 分類 2
model = CNN(3, 2)
loss,優(yōu)化函數(shù):
line = viz.line(Y=np.arange(10)) loss_f = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=LR, momentum=0.9) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)
參數(shù):
BATCH_SIZE = 4 LR = 0.001 EPOCHS = 10
運(yùn)行 10個(gè) epoch 看看:
[9/10] train_loss:0.650|train_acc:0.639|test_loss:0.621|test_acc0.706
[10/10] train_loss:0.645|train_acc:0.627|test_loss:0.654|test_acc0.686
Training complete in 1m 16s
Best val Acc: 0.712418

運(yùn)行 20個(gè)看看:
[19/20] train_loss:0.592|train_acc:0.701|test_loss:0.563|test_acc0.712
[20/20] train_loss:0.564|train_acc:0.721|test_loss:0.571|test_acc0.706
Training complete in 2m 30s
Best val Acc: 0.745098

準(zhǔn)確率比較低:只有74.5%
我們使用models 里的 resnet18 運(yùn)行 10個(gè)epoch:
model = torchvision.models.resnet18(True) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 2)
[9/10] train_loss:0.621|train_acc:0.652|test_loss:0.588|test_acc0.667
[10/10] train_loss:0.610|train_acc:0.680|test_loss:0.561|test_acc0.667
Training complete in 1m 24s
Best val Acc: 0.686275
效果也很一般,想要短時(shí)間內(nèi)就訓(xùn)練出效果很好的models,我們可以下載訓(xùn)練好的state,在此基礎(chǔ)上訓(xùn)練:
model = torchvision.models.resnet18(pretrained=True) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 2)
[9/10] train_loss:0.308|train_acc:0.877|test_loss:0.160|test_acc0.941
[10/10] train_loss:0.267|train_acc:0.885|test_loss:0.148|test_acc0.954
Training complete in 1m 25s
Best val Acc: 0.954248
10個(gè)epoch直接的到95%的準(zhǔn)確率。

示例代碼:https://github.com/ffzs/ml_pytorch/blob/master/ml_pytorch_hymenoptera
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python利用Flask-Mail實(shí)現(xiàn)發(fā)送郵件詳解
Flask?的擴(kuò)展包?Flask?-?Mail?通過包裝了?Python?內(nèi)置的smtplib包,可以用在?Flask?程序中發(fā)送郵件。本文將利用這特性實(shí)現(xiàn)郵件發(fā)送功能,感興趣的可以了解一下2022-08-08
利用 Python ElementTree 生成 xml的實(shí)例
這篇文章主要介紹了利用 Python ElementTree 生成 xml的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python中使用百度音樂搜索的api下載指定歌曲的lrc歌詞
這篇文章主要介紹了python中使用百度音樂搜索的api下載指定歌曲的lrc歌詞,同時(shí)也分析出了歌曲的下載地址,需要的朋友可以參考下2014-07-07
Python高級(jí)property屬性用法實(shí)例分析
這篇文章主要介紹了Python高級(jí)property屬性用法,結(jié)合實(shí)例形式分析了Python property屬性的功能及各種常見的使用技巧,需要的朋友可以參考下2019-11-11

