The fastai library simplifies training fast and accurate neural nets using modern best practices. See the fastai website to get started. The library is based on research into deep learning best practices undertaken at fast.ai
, and includes “out of the box” support for vision
, text
, tabular
, and collab
(collaborative filtering) models.
Our task is to find the center of the head in each image.
To achieve the goal, we need to do the following:
DataBlock
Upload an example:
library(fastai)
library(magrittr)
= 'biwi_head_pose'
path = '09/frame_00667_rgb.jpg'
fname
= Image_create(paste(path,fname,sep = '/'))
img %>% show() %>% plot()
img = readr::read_lines(paste(path,'01/rgb.cal',sep = '/'), n_max = 3) %>% trimws() %>%
cal strsplit('\\s') %>% do.call(rbind,.) %>% apply(.,2,as.numeric)
To add the points, we need to write simple functions:
<- function(f) {
img2txt_name paste(
substr(f, 1, nchar(f)-7), 'pose.txt',
sep = ''
)
}
<- function(coords) {
convert_biwi = coords[1] * cal[1,][1]/coords[3] + cal[1,][3]
c1 = coords[2] * cal[2,][2]/coords[3] + cal[2,][3]
c2 return(tensor(c1,c2))
}
<- function(f) {
get_ctr # trick to make dataloaders work
= as.character(f)
f = readr::read_lines(img2txt_name(f), skip = 4, n_max = 1) %>% trimws() %>%
ctr strsplit('\\s') %>% unlist() %>% as.numeric()
convert_biwi(ctr)
}
<- function(img, pts) {
get_ip TensorPoint_create(pts, img_size = img$size)
}
= readr::read_lines(img2txt_name(paste(path,fname,sep = '/')),
ctr skip = 4, n_max = 1) %>% trimws() %>%
strsplit('\\s') %>% unlist() %>% as.numeric()
Now, it is easier to add red points:
= get_ctr(paste(path,fname,sep = '/'))
ctr = img %>% show(figsize = c(6, 6))
ax %>% get_ip(ctr) %>% show(ctx = ax) %>% plot() img
Prepare data laoder object and see batch:
= DataBlock(blocks = list(ImageBlock(), PointBlock()),
dblock get_items = get_image_files(),
splitter = FuncSplitter(function(x) x$parent$name == '13'),
get_y = get_ctr,
batch_tfms = list(aug_transforms(size = c(120,160)),
Normalize_from_stats(imagenet_stats()
)
)
)
= dblock %>% dataloaders(path, path = path, bs = 64)
dls
%>% show_batch(max_n = 9, figsize = c(9,6)) dls
Run for 5 epochs and see results:
= cnn_learner(dls, resnet34())
learn
%>% lr_find()
learn
%>% plot_lr_find()
learn
= 2e-2
lr
%>% fit_one_cycle(5, slice(lr)) learn
%>% show_results(dpi = 200) learn
epoch train_loss valid_loss time
0 1.818259 0.861968 00:35
1 0.222080 0.056300 00:34
2 0.028511 0.012499 00:33
3 0.017333 0.003378 00:33
4 0.015135 0.004777 00:33