Bear Classifier
from pathlib import Path
root = Path().cwd()/"images"
#rmtree(root) #Deletes all previous images
from jmd_imagescraper.core import *
duckduckgo_search(root, "Grizzly", "Grizzly bears", max_results=300)
duckduckgo_search(root, "Black", "Black bears", max_results=300)
duckduckgo_search(root, "Teddy", "Teddy bears", max_results=300)
#duckduckgo_search(root, "Random", "Random images", max_results=300)
from jmd_imagescraper.imagecleaner import *
display_image_cleaner(root)
bears = DataBlock(
blocks=(ImageBlock, CategoryBlock), #Independent are images, dependent is the categories
get_items=get_image_files,
splitter=RandomSplitter(valid_pct=0.2, seed=42),
get_y=parent_label,
item_tfms=RandomResizedCrop(224, min_scale=0.5),
batch_tfms=aug_transforms())
dls = bears.dataloaders(root)
dls.valid.show_batch(max_n=4, nrows=1) #Viewing data
learner = cnn_learner(dls, resnet18, metrics = accuracy)
learner.fine_tune(2)
learner.export(fname='bear.pkl')
path = Path()
path.ls(file_exts='.pkl')
learn_inf = load_learner(path/'bear.pkl')
uploader = widgets.FileUpload()
uploader
img = PILImage.create(uploader.data[0])
img.to_thumb(192)
learn_inf.predict(img)
It got it correct!
uploader = widgets.FileUpload()
uploader
img = PILImage.create(uploader.data[0])
img.to_thumb(192)
learn_inf.predict(img)
It only got 1 correct - This is because our model isn't made to do multi-labels
def parent_label_multi(o):
return [Path(o).parent.name]
bears2 = DataBlock(
blocks=(ImageBlock, MultiCategoryBlock), #Independent are images, dependent is the multiple labels
get_items=get_image_files,
splitter=RandomSplitter(valid_pct=0.2, seed=42),
get_y= parent_label_multi,
item_tfms=Resize(128))
dls2 = bears2.dataloaders(root)
dls2.show_batch()
dls2.vocab
learn2 = cnn_learner(dls2, resnet18, metrics=partial(accuracy_multi, thresh=0.2)) #lets just pick a tresh of .2
learn2.fine_tune(2)
uploader = widgets.FileUpload()
uploader
img = PILImage.create(uploader.data[0])
img.to_thumb(200)
learn2.predict(img)
It got both of them right!
uploader = widgets.FileUpload()
uploader
img = PILImage.create(uploader.data[0])
img.to_thumb(200)
learn2.predict(img) #It works
Notice that there is no prediction! This is the other benifit of a multi-label classifier!
btn_upload = widgets.FileUpload()
out_pl = widgets.Output()
lbl_pred = widgets.Label()
btn_run = widgets.Button(description='Classify')
def on_click_classify(change):
img = PILImage.create(btn_upload.data[-1])
out_pl.clear_output()
with out_pl: display(img.to_thumb(128,128))
pred,pred_idx,probs = learn_inf.predict(img)
lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'
btn_run.on_click(on_click_classify)
VBox([widgets.Label('Select your bear!'),
btn_upload, btn_run, out_pl, lbl_pred])