I have trained a model I want to use, and now want to create a code snippet for the prediction in a separate python script.
The shortest I ended up with so far is the code below, which is not ideal because
- I have to create dummy directories with dummy images even though I don’t want to train the model
- I have to copy the model manually after I run fastai once so it has created the models directory
Do you have any suggestions how to make this more elegant (ideally without creating the dummy directory with dummy images) ?
### Initialize once #To make this work, I need to create and enter dummy data into the PATH directory: # mkdir -p data/train/dog; mkdir -p data/train/notdog; # echo > data/train/dog/0.jpg # echo > data/train/notdog/0.jpg # mkdir -p data/valid/dog; mkdir -p data/valid/notdog; # echo > data/valid/dog/0.jpg # echo > data/valid/notdog/0.jpg arch = resnet34 sz = 224 PATH = "data" air_data = ImageClassifierData.from_paths(PATH, tfms=tfms_from_model(arch, sz)) air_learn = ConvLearner.pretrained(arch, air_data, precompute=False) # After fast.ai created the models directory, i need to manaully copy my pretrained model # mv 224_all_mymodel.h5 data/models/224_all.h5 air_learn.load('224_all') trn_tfms, air_val_tfms = tfms_from_model(arch, sz) ### Prediction code for each image, this I can run after I initialised once as above filename="image.jpg" im = air_val_tfms(open_image(filename)) # Load Image using fastai open_image in dataset.py log_preds_single = air_learn.predict_array(im[None]) # Predict Image maxP = np.argmax(log_preds_single, axis=1) # Pick the index with highest log probability probs_single = np.exp(log_preds_single) # If you want the probabilities of the classes actualclass = air_data.classes[maxP] # Look up tactualPT return actualclass