根據上一篇文章分7部分講解了基于torch識别分類圖檔的例子,修改了部分代碼,識别指定類型的圖檔分類識别。
1 生成用于訓練的t7檔案
-- generate training material t7 files
require 'io'
require 'xlua'
require 'image'
dataNum =
imgSize =
aImgs = torch.Tensor(batchSize, , imgSize, imgSize):zero():float()
label1 = {}
for idx = ,dataNum do
im_name = string.format('/home/cgy/torch_bak/image/Chinese flag/%02d.jpg',idx)
--xlua.progress(idx, dataNum)
local img1 = image.load(im_name)
aImgs[idx] = image.scale(img1, imgSize, imgSize):float()
label1[idx] =
end
print('Save Anchor Images: aImgs.t7: ')
--Create the table to save
label = torch.Tensor(label1)
data_to_write = { data = aImgs, label = label }
--Save the table in the /home
torch.save('/home/cgy/torch_bak/image/Chinese flag/train_TEST.t7', data_to_write)
2 測試待訓練的t7檔案
-- load test
require 'paths'
require 'nn'
trainset = torch.load('/home/cgy/torch_bak/image/Chinese flag/train_TEST.t7')
trainset.data = trainset.data:double()
for idx = , do
--print(trainset.label[idx])
itorch.image(trainset.data[idx])
end
3 設定訓練參數,生成模型
require 'paths';
require 'nn';
trainset = torch.load('/home/cgy/torch_bak/image/Chinese flag/train_TEST.t7')
setmetatable(trainset,
{__index = function(t,i)
return {t.data[i],t.label[i]}
end}
);
trainset.data = trainset.data:double()
function trainset:size()
return self.data:size(1)
end
---Normalize data
mean = {}
stdv = {}
for i=, do
mean[i] = trainset.data[{ {}, {i}, {}, {} }]:mean()
print('Channel ' .. i .. ', Mean: ' .. mean[i])
trainset.data[{ {}, {i}, {}, {} }]:add(-mean[i])
stdv[i] = trainset.data[{ {}, {i}, {}, {} }]:std()
print('Channel ' .. i .. ', Standard Deviation:' .. stdv[i])
trainset.data[{ {}, {i}, {}, {} }]:div(stdv[i])
end
--資料的預處理
net = nn.Sequential()
--change 1 channel to 3 channels
--net:add(nn.SpatialConvolution(1, 6, 5, 5))
net:add(nn.SpatialConvolution(, , , ))
net:add(nn.ReLU())
net:add(nn.SpatialMaxPooling(,,,))
net:add(nn.SpatialConvolution(, , , ))
net:add(nn.ReLU())
net:add(nn.SpatialMaxPooling(,,,))
net:add(nn.View(**))
net:add(nn.Linear(**, ))
net:add(nn.ReLU())
net:add(nn.Linear(, ))
net:add(nn.ReLU())
net:add(nn.Linear(, ))
net:add(nn.LogSoftMax())
criterion = nn.ClassNLLCriterion();
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate =
trainer.maxIteration =
trainer:train(trainset)
4 驗證訓練結果
for idx = , do
itorch.image(trainset.data[idx])
predicted = net:forward(trainset.data[idx])
print(predicted:exp())
end