knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(clasifierrr) library(EBImage) library(ranger) library(caret) library(kernlab)
params_df <- tibble::tibble( file = c( system.file( "extdata", "tiny_4T1-shNT-1_layer1.png", package = "clasifierrr"), system.file( "extdata", "tiny_4T1-shNT-1_layer2.png", package = "clasifierrr")), classif = c("spheroid", "bg"), related_file = system.file( "extdata", "tiny_4T1-shNT-1.png", package = "clasifierrr") ) params_df
test_img <- readImageBw(params_df$related_file[[1]]) test_feat <- calc_features(test_img, filter_widths = c(3, 5, 15), shape_sizes = c(71, 101))
trainset <- build_train_multi( params_df, filter_widths = c(3, 5, 15), shape_sizes = c(71, 101)) head(trainset, 2)
The general pattern is that you need to train a model that accepts the predict
method, in this case we will use a simple logistic regression.
trainset2 <- trainset # Logistic regressions need binary outputs trainset2$pixel_class <- trainset2$pixel_class == "spheroid" suppressWarnings({ model_simple_glm <- glm( pixel_class~., data = trainset2, family = binomial(link = "logit")) model_simple_glm })
class_img <- classify_img( classifier = model_simple_glm, feature_frame = test_feat, filter_widths = c(3, 5, 15), shape_sizes = c(71, 101), dims = dim(test_img)) display(class_img, method = "raster")
ctrl <- trainControl(method = "cv", number = 2) model_svmlinear <- train( pixel_class~., data = trainset, method = "svmLinear", trControl = ctrl) model_svmradial <- train( pixel_class~., data = trainset, method = "svmRadial", trControl = ctrl) model_glm <- train( pixel_class~., data = trainset, method = "glm", trControl = ctrl) model_glmnet <- train( pixel_class~., data = trainset, method = "glmnet", trControl = ctrl)
for (classifier in list(model_svmlinear, model_svmradial, model_glm)) { cat(paste( "The model '", classifier$modelInfo$label, "'\nHad a classification accuracy of:", max(classifier$results$Accuracy), "\non its best iteration\n\n")) }
Now that we have a model, we can use the classifier$finalModel
object to
predict our images. Note that not all models give the same type of output.
Some of the will output a classification percentage and others will output an
actual classification.
for (classifier in list(model_svmlinear, model_svmradial, model_glm)) { timetaken <- system.time({ class_img <- classify_img( classifier$finalModel, feature_frame = test_feat, dims = dim(test_img)) }) if (length(unique(as.numeric(class_img))) < 20 & colorMode(class_img) == Grayscale) { class_img <- colorLabels(class_img) } display(class_img, method = "raster") }
class_img <- EBImage::Image( predict(model_glmnet$finalModel, s = model_glmnet$bestTune$lambda, as.matrix(test_feat), type = "response"), dim = dim(test_img) ) display(class_img, method = "raster")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.