I tried to run the code below for image classification using keras. My motive is to detect if the image is a dog or cat.
> library(keras)
> image_path = 'C:/Users/Joel/Desktop/SJU/Semester 3/R programming/Cat_photo.jpg'
>
> # define image preprocessor for use with keras vgg19
> image_preprocessor = function(image_path) {
> image = image_load(image_path, target_size = c(224,224))
> image = image_to_array(image)
> image = array_reshape(image, c(1, dim(image)))
> image = imagenet_preprocess_input(image)
> return(image)
> }
>
> #function to read in files housing all cat/dog breeds in imagenet labels
> read_dog_cat_labels = function(path) {
> labs = readLines(path)
> labs = trimws(unlist(strsplit(labs, ',')))
> labs = gsub('\\s+', '_', labs)
> return(labs)
> }
>
> #doubt 22 to 26
> # define image paths to classify
> image_paths = list.files('images', recursive = TRUE, full.names = TRUE)
>
> # preprocess images
> image_list = lapply(image_paths, image_preprocessor)
>
> # load vgg19 model pretrained with imagenet
> model = application_vgg19(weights = 'imagenet')
>
> # get model prediction
> preds = lapply(image_list, function(i) {
> imagenet_decode_predictions(predict(model, i), top = 1)[[1]]
> })
>
>
> # convert list of predictions to df and drop class name column
> pred_df = do.call(rbind, preds)
> pred_df$class_name = NULL
>
> #read in breed labels
> dog_labs = read_dog_cat_labels('C:/Users/Joel/Desktop/SJU/Semester 3/R programming/dog_classes.txt')
> cat_labs = read_dog_cat_labels('C:/Users/Joel/Desktop/SJU/Semester 3/R programming/cat_classes.txt')
>
> #create column for labeling dog breeds as dog and cat breeds as cat
> pred_df$catdog = NA
> pred_df$catdog[pred_df$class_description %in% dog_labs] = 'Dog'
> pred_df$catdog[pred_df$class_description %in% cat_labs] = 'Cat'
>
> #add column with image paths
> pred_df$file_name = unlist(image_paths)
> pred_df = pred_df[order(pred_df$score),]
> print(pred_df)
>
However, I get the below error:
> pred_df = pred_df[order(pred_df$score),]
Error in order(pred_df$score) : argument 1 is not a vector
> print(pred_df)
$catdog
[1] NA
$file_name
character(0)
How can I resolve this?