Fastai Course Chapter 2 on WSL2. An expanded guide with definitions of… | by David Littlefield

[ad_1]

An expanded guide with definitions of terms and commands

Image by Sandro Katalina

This article is an expanded guide that’s meant to help you learn what’s happening throughout the chapter. It provides definitions of terms, commands, and code that are used in the article. It also includes underlined text which has links to additional definitions in the glossary of the article.

The second chapter from the textbook shows how to build a custom dataset, train a model with the dataset, and build an application with the model using widgets. It sets up an Azure account, finds and downloads the images with an API, and prepares the dataset. It also trains the model, saves and loads the model, and builds an application with the model using widgets.

Open the Notebook:

The Notebook is a document that’s used in Jupyter Notebook to contain the visible content in the web application. It includes the inputs and outputs of computations, markdown text, equations, images, videos, and text. It also has its own kernel that can run code using a single programming language.

  1. Open the web browser
  2. Enter the IP address to the Jupyter Notebook server
  3. Press “Enter”
  4. Click “Desktop”
  5. Click “Fastbook”
  6. Click “Clean”
  7. Click “02_production.ipynb”

Change the Kernel:

The Notebook Kernel is a program that’s used in Jupyter Notebook to run the code from the code cells and display the outputs in a specific programming language. It remembers preceding events and user interactions across time, between code cells, and regardless of the order that the code cells were run.

  1. Click the “Kernel” menu
  2. Select the “Change Kernel” submenu
  3. Click the “FastAI (PyTorch)” menu item

Setup the Fastbook Library:

Fastai is a library that’s used in Python for deep learning. It provides a high-level API that’s built on top of a hierarchy of lower-level APIs which can be rebuilt to customize the high-level functionality. It also provides support for computer vision, natural language processing, and tabular data processing.

  1. Select the code cell
  2. Click “▶ Run”

Import the Fastbook Library and Widgets Module:

Star Import is a syntax that’s used in Python to import an entire library into the namespace. It doesn’t specify what names are being imported which can accidentally overwrite the other functions in the namespace. It also only works well in specific situations like interactive work in Jupyter Notebook.

  1. Select the code cell
  2. Click “▶ Run”

Setup the Azure Account:

Microsoft Azure is a cloud computing service provider that’s used to build, test, deploy, and manage applications and services. It provides software as a service, platform as a service, and infrastructure as a service and supports many programming languages, tools, and frameworks. It can also be used for services such as analytics, virtual computing, storage, and networking.

  1. Visit the official website
  2. Click “Go to the Portal”
  3. Sign in or create a new account
  4. Click “Create a Resource”

Navigate to the Bing Search API:

Bing Search API is an Azure Marketplace service that’s used to access billions of web pages, images, videos, and news results with no ad requirements. It can be customized to local locations or markets to increase relevancy. It also provides 8 features which include image search, video search, news search, web search, visual search, entity search, spellcheck, and autosuggest APIs.

  1. Enter “Bing Search” into the search bar
  2. Click “Bing Search v7”
  3. Click “Create”

Create the Bing Search API Account:

A Bing Search account is required to access the Bing Image Search API that fastai uses to download the image dataset. It has the option to use the free plan in the pricing tier dropdown which includes 3 transactions per second and 1,000 transactions per month. It also wants to assign a resource group to tag other services that share the same lifecycle, permissions, and policies.

  1. Enter a name for the Bing Search account
  2. Select the “Free F1” Pricing Tier
  3. Click “Create New” under the Resource Group
  4. Enter a name for the Resource Group
  5. Click “Ok”
  6. Click “I confirm I have read and understood the notice below”
  7. Click “Create”

Copy the Bing Search API Key:

The Application Programming Interface Key (API Key) is a unique code that’s used to access a REST API. It gets used to track and control how the API is being used which usually prevents malicious use or abuse of the API. It also often acts as both a unique identifier and a secret token for authentication.

  1. Click “Go to Resource”
  2. Click “Keys and Endpoint”
  3. Click “Show Keys”
  4. Copy the code inside the Key 1 text field

Paste the Bing Search API Key:

The single-line stores the API key in the key variable. It gets the key using the get method (which gets the value for an environment variable) in the environ object in the os module from the Python library. It also sets the key parameter (which sets the environment variable) and the default parameter (which sets the return value if there’s no environment variable).

  1. Paste the code over the “XXX”
  2. Select the code cell
  3. Click “▶ Run”

Check the Search Images Bing Function:

The single-line prints a rich string representation of the search_images_bing function. It prints the class, module, function name, input parameters, and default arguments. It also displays a rich representation of whichever object is ran in the code cell using the display function from the IPython library.

  1. Select the code cell
  2. Click “▶ Run”

Get the Image URLs:

The first line stores a list of dictionaries in the results variable. It searches for the images using the search_images_bing function (which makes the API requests and handles the responses) from the fastbook library. It also sets the key parameter (which sets the API key to access the Bing Search API) and the term parameter (which sets the search terms to find the images).

The second line stores a list of URLs for the images in the ims variable. It gets the URLs from the list of dictionaries in the results variable using the attrgot method (which uses the key to extract the related value) in the L class from the fastai library. It also sets the k parameter (which sets the key to access the related value in each dictionary in the list of dictionaries).

The third, fourth, and fifth lines illustrate the process behind the previous lines. It prints an API response from the list of dictionaries in the results variable and an image URL from the list of image URLs in the ims variable. It also prints the number of image URLs that are stored in the ims variable.

  1. Copy the code from below these instructions
  2. Paste the code over the code in the code cell
  3. Select the code cell
  4. Click “▶ Run”

Replace the Images:

The single line replaces the list of image URLs in the ims variable with a list that contains one image URL. It ensures an appropriate image is displayed in the next step (which prevents any potentially unpleasant images from being displayed). It also isn’t necessary and should be considered optional.

  1. Select the code cell
  2. Click “▶ Run”

Download the first image:

The first and second lines store the location to save the image in the dest variable and download the image from the URL in the ims variable. It gets the image using the download_url function (which can download any file from the internet) from the fastai library. It also sets the url parameter (which sets the URL) and the dest parameter (which sets the destination).

  1. Copy the code from below these instructions
  2. Paste the code over the code in the code cell
  3. Select the code cell
  4. Click “▶ Run”

Display the Image in the Output:

The first line stores the image object in the im variable. It gets the image object using the open function (which gets the image from the file path in the dest variable) in the Image module from the PIL library. It also sets the fp parameter (which sets the file pointer that identifies the image file).

The second line displays a thumbnail image. It creates the thumbnail image using the to_thumb method (which uses a copy of the image to preserve the original) in the Image module from the PIL library. It also sets the h para-meter (which sets the height) and the w parameter (which sets the width).

  1. Select the code cell
  2. Click “▶ Run”

Define the Subdirectory Names and Image Directory Path:

The first and second lines store the subdirectory names in the bear_types variable and store the path to the image directory in the path variable. It creates a tuple of subdirectory names (which represents the prediction categories). It also creates a Path object using the Path class (which accepts the file path as a string) in the pathlib module from the Python library.

  1. Select the code cell
  2. Click “▶ Run”

Download the Images:

The first and second lines create the bear directory using the path in the path variable. It checks if the path in the path variable doesn’t exist using the not keyword and the exists method (which checks whether the path exists) in the pathlib module from the Python library. It also creates the directory if the path doesn’t already exist using the mkdir method (which makes the directory) in the pathlib module from the Python library.

The third and fourth lines iterate through the subdirectory names in the bear_types variable and store the path to the subdirectory in the dest variable. It creates the path to the subdirectory by joining the path in the path variable and the subdirectory name in the o variable using the forward slash operator in the pathlib module from the Python library.

The fifth line creates the image subdirectory using the path in the dest variable. It creates the subdirectory using the mkdir method (which makes the subdirectory) in the pathlib module from the Python library. It also sets the exist_ok parameter (which prevents the FileExistsError error).

The sixth line stores the search results in the results variable. It searches for the f-string (which prepends the subdirectory name in the o variable to the bear string) using the search_images_bing function (which makes the API requests and handles the responses) from the fastai library. It also sets the key parameter (which sets the API key to access the Bing Search API) and the term parameter (which sets the search terms to find the images).

The seventh line downloads the images to the subdirectory in the dest variable using the download_images function (which gets the images from a list of URLs) from the fastai library. It sets the dest parameter (which sets the destination) and the urls parameter (which sets the list of URLs). It also gets the list of URLs from the search results in the results variable (which is a list of dictionaries) using the attrgot method (which uses the contentUrl key to extract the URLs) in the L class from the fastai library.

  1. Select the code cell
  2. Click “▶ Run”

Get the File Paths of the Images:

The first line stores the list of file paths in the fns variable. It gets the file paths using the get_image_files function (which finds all the images in the directory and all the subdirectories) in the transforms module from the fastai library. It also sets the path parameter (which sets the directory).

The second line prints the rich string representation of the list of file paths in the fns variable. It prints the number of images that were found in the directory and subdirectories. It also prints a portion of the file paths in the list which includes the directory, subdirectory, file name, and file extension.

The fifth line prints the rich string representation of the list of file paths in the failed variable. It prints the number of images that are broken from the list in the fns variable. It also prints a portion of the file paths in the list which includes the directory, subdirectory, file name, and file extension.

  1. Select the code cell
  2. Click “▶ Run”

Find the Images That Don’t Work:

The first line stores the list of file paths that could not be opened in the failed variable. It gets the file paths using the verify_images function (which checks if the images can be opened) in the utils module from the fastai library. It also sets the fns parameter (which sets the file paths).

The second line prints the rich string representation of the list of file paths in the failed variable. It prints the number of images that are broken from the list in the fns variable. It also prints a portion of the file paths in the list which includes the directory, subdirectory, file name, and file extension.

  1. Select the code cell
  2. Click “▶ Run”

Delete the Images That Don’t Work:

The single-line deletes the images in the list of file paths in the failed variable. It deletes the images using the map function (which applies a function to the list) and the unlink method (which deletes the image from the computer) in the pathlib module from the Python library. It also sets the function parameter (which sets the function to apply to the list).

  1. Select the code cell
  2. Click “▶ Run”

Create the Data Block:

The single-line stores the data block object in the bears variable. It creates the data block object using the DataBlock class (which gets used to build the data loaders object) in the block module from the fastai library. It also sets the blocks parameter (which sets the input and output data type), the get_items parameter (which sets the list of file paths), the splitter parameter (which sets how to split the dataset into training and validation sets), the get_y parameter (which extracts the labels from the dataset), and the item_tfms parameter (which applies a transformation to the images).

The single line also passes a couple of functions to the DataBlock class to create the data block object. It passes the RandomSplitter function (which randomly splits the dataset into the training and validation sets) in the transforms module from the fastai library and sets the valid_pct parameter (which sets the percentage of data to use for the validation set) and the seed parameter (which sets the random seed). It also passes the Resize function (which resizes the images) in the augment module from the fastai library and sets the size parameter (which sets the image size).

  1. Select the code cell
  2. Click “▶ Run”

Create the Data Loaders:

The single-line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

  1. Select the code cell
  2. Click “▶ Run”

Show the Images From the Validation Set:

The single-line displays images from the data loaders object in the dls variable. It displays the images using the show_batch method (which displays the images from the subset) in the core module in the fastai library. It sets the max_n parameter (which sets the number of images to show) and the nrows parameter (which sets the number of rows to use).

  1. Select the code cell
  2. Click “▶ Run”

Show the Squished Images:

The first line stores a new data block object in the bears variable. It creates the new data block object using the new method (which creates a new data block object with a different transformation) in the block module from the fastai library. It also sets the item_tfms parameter (which sets the new transformation that gets merged with the other item transformations).

The first line also passes a transformation class to the new method to create the data block object. It passes the Resize class (which resizes the image) in the augment module from the fastai library and sets the size parameter (which sets the image size) and the method parameter (which sets the resize method to perform). It also passes the Squish attribute (which squishes the image) in the ResizeMethod in the basics module from the fastai library.

The second line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

The third line displays images from the data loaders object in the dls variable. It displays the images using the show_batch method (which displays the images from the subset) in the core module in the fastai library. It sets the max_n parameter (which sets the number of images to show) and the nrows parameter (which sets the number of rows to use).

  1. Select the code cell
  2. Click “▶ Run”

Show the Padded Images:

The first line stores a new data block object in the bears variable. It creates the new data block object using the new method (which creates a new data block object with a different transformation) in the block module from the fastai library. It also sets the item_tfms parameter (which sets the new transformation that gets merged with the other item transformations).

The first line also passes a transformation class to the new method to create the data block object. It passes the Resize class (which resizes the image) in the augment module from the fastai library and sets the size parameter (which sets the image size), the method parameter (which sets the resize method to perform), and the pad_mode parameter (which sets the type of padding to use). It also passes the Pad attribute (which adds padding to the image) in the ResizeMethod class in the basics module from the fastai library and the zeros attribute (which sets the padding to black pixels).

The second line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

The third line displays images from the data loaders object in the dls variable. It displays the images using the show_batch method (which displays the images from the subset) in the core module in the fastai library. It sets the max_n parameter (which sets the number of images to show) and the nrows parameter (which sets the number of rows to use).

  1. Select the code cell
  2. Click “▶ Run”

Show the Cropped Images:

The first line stores a new data block object in the bears variable. It creates the new data block object using the new method (which creates a new data block object with a different transformation) in the block module from the fastai library. It also sets the item_tfms parameter (which sets the new transformation that gets merged with the other item transformations).

The first line also passes a transformation class to the new method to create the data block object. It passes the RandomResizedCrop class (which resizes the image to a randomly cropped portion) in the augment module from the fastai library and sets the size parameter (which sets the image size) and the min_scale parameter (which sets the lowest scale of the image to use).

The second line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

The third line displays images from the data loaders object in the dls variable. It displays the images using the show_batch method (which displays the images from the subset) in the core module in the fastai library. It sets the max_n parameter (which sets the number of images to show), the nrows parameter (which sets the number of rows to use), and the unique parameter (which uses the same batch for transformations).

  1. Select the code cell
  2. Click “▶ Run”

Show the Augmented Images:

The first line stores a new data block object in the bears variable. It creates the new data block object using the new method (which creates a new data block object with a different transformation) in the block module from the fastai library. It also sets the item_tfms parameter (which sets the new transformation that gets merged with the other item transformations) and the batch_tfms parameter (which sets the transformations for the batches).

The first line also passes a transformation class to the new method to create the data block object. It passes the Resize class (which resizes the image) in the augment module from the fastai library and sets the size parameter (which sets the image size). It also passes the aug_transforms function (which is preset transformations) in the augment module from the fastai library and sets the mult parameter (which increases the augmentation).

The second line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

The third line displays images from the data loaders object in the dls variable. It displays the images using the show_batch method (which displays the images from the subset) in the core module in the fastai library. It sets the max_n parameter (which sets the number of images to show), the nrows parameter (which sets the number of rows to use), and the unique parameter (which uses the same batch for transformations).

  1. Select the code cell
  2. Click “▶ Run”

Create the New Data Loaders:

The first line stores a new data block object in the bears variable. It creates the new data block object using the new method (which creates a new data block object with a different transformation) in the block module from the fastai library. It also sets the item_tfms parameter (which sets the new transformation that gets merged with the other item transformations) and the batch_tfms parameter (which sets the transformations for the batches).

The second line stores the data loaders object in the dls variable. It creates the data loaders object using the dataloaders method (which preprocesses the dataset for the model) in the DataBlock class from the fastai library. It also sets the source parameter (which sets the path to locate the dataset).

  1. Select the code cell
  2. Click “▶ Run”

Train the Image Classification Model:

The first line stores the learner object in the learn variable. It creates the learner object using the cnn_learner function (which builds a learner to perform transfer learning for computer vision) in the learner module from the fastai library. It also sets the dls parameter (which sets the data loaders object), the arch parameter (which sets the architecture to build the model), and the metrics parameter (which sets the metrics to display).

The second line performs transfer learning using the fine_tune method. It trains the final layer of the model (which was replaced during the fine-tuning process) for one epoch and then retrains the entire model (which includes the final layer) for the specified number of epochs. It also sets the epochs parameter (which sets the number of epochs to train the model).

  1. Select the code cell
  2. Click “▶ Run”

Display the Confusion Matrix:

The first line stores the interpretation object in the interp variable. It creates the interpretation object using the from_learner method in the ClassificationInterpretation class (which stores interpretation methods for the classification models) in the interpret module from the fastai library. It also sets the learn parameter (which sets t[-’he learner object).

The second line displays the confusion matrix. It displays the confusion matrix using the plot_confusion_matrix method in the Classification-Interpretation class in the interpret module from the fastai library. It was also mostly copied from the metics module from the sklearn library.

  1. Select the code cell
  2. Click “▶ Run”

Display the Top Losses:

The single line displays the images with the highest loss. It displays the images using the plot_top_losses method (which displays the images and the associated prediction, actual label, loss, and probability) in the Class-ificationInterpretation class in the interpret module from the fastai library. It also sets the k parameter (which sets the number of top losses to display) and the nrows parameter (which sets the number of rows to use).

  1. Select the code cell
  2. Click “▶ Run”

Clean the Images:

The first line stores the images cleaner widget in the cleaner variable. It creates the images cleaner widget using the ImageClassifierCleaner class (which creates the image cleaner) in the widgets module from the fastai library. It also sets the learn parameter (which sets the leaner object).

The second line displays the image cleaner widget. It displays the image subdirectory dropdown (which sets the subdirectory) and the dataset dropdown (which sets the training or validation set). It also displays the images that the model was least confident about from the selected image subdirectory and dataset and displays the action dropdown (which sets whether to keep, delete, or move the image to a different subdirectory).

  1. Select the code cell
  2. Click “▶ Run”

Make the Changes:

The first line deletes the images that were set to “delete” with the image cleaner widget. It iterates through the indexes that get returned by the delete method (which return a list) in the image classifier cleaner object and deletes the images using the unlink method (which deletes the image from the computer) in the pathlib module from the Python library. It also uses the index to get the file path (which is used to delete the image) in the list of file paths in the fns attribute in the image classifier cleaner object.

The second line moves the images that were set to different subdirectories with the image cleaner widget. It iterates through the items (which are tuples that contain the index and the subdirectory) that get returned by the change method (which returns a list) in the image classifier cleaner object and the move method (which moves the image) in the shutil module from the Python library. It also uses the index to get the file path (which is used to move the image) in the list of file paths in the fns attribute in the image classifier cleaner object and sets the src parameter (which sets where the image is at) and the dst parameter (which sets where to move the image).

  1. Copy the code from below these instructions
  2. Paste the code over the code in the code cell
  3. Select the code cell
  4. Click “▶ Run”

Save the Model:

The single line saves the trained model to be used in production. It saves the model using the export function (which saves everything that’s needed to rebuild the learner object for inference) in the Learner module from the fastai library. It also saves the architecture (which defines how to build the model, trained parameters (which define how to make the prediction), and data loader parameters (which define how to transform the data).

  1. Select the code cell
  2. Click “▶ Run”

Check the Saved File:

The first line stores a Path object in the path variable. It creates the Path object using the Path class (which creates a filesystem path object) in the pathlib module from the Python library. It also uses the current directory by default because the args parameter (which sets the file path) wasn’t set.

The second line lists the file paths in the path variable that have the “pkl” file extension. It filters the file paths using the ls method (which displays the contents of the path) in the xtras module from the fastai library. It also sets the file_exts parameter (which sets the file extensions to filter)

  1. Select the code cell
  2. Click “▶ Run”

Load the Model:

The single-line stores a learner object in the learn_inf variable. It loads the learner object using the load_learner function (which loads the learner object from the pickle file) in the Learner module from the fastai library. It also sets the fname parameter (which sets the file path for the pickle file).

  1. Select the code cell
  2. Click “▶ Run”

Make a Prediction:

The single-line makes a prediction about an image. It makes the prediction using the predict method (which returns a tuple with the predicted class, index, and probabilities) in the Learner class in the learner module from the fastai library. It also sets the item parameter (which sets the image).

  1. Copy the code from below these instructions
  2. Paste the code over the code in the code cell
  3. Select the code cell
  4. Click “▶ Run”

Check the Prediction Categories:

The single-line displays the list of possible prediction categories. It gets the list of prediction categories from the vocab attribute in the DataLoaders class in the core module from the fastai library. It also represents the list that’s related to the prediction index and probabilities from the prediction.

  1. Select the code cell
  2. Click “▶ Run”

Create the File Upload Widget:

The first line stores the file upload widget in the btn_upload variable. It creates the file upload widget using the FileUpload class in the widget-_upload module from the ipwidgets library. It also uploads the selected files into the memory of the kernel to be referenced in the notebook.

The second line displays the file upload widget in the output of the Jupyter Notebook REPL. It displays the button (which opens a dialog window to select the files). It also displays the number of selected files in the button (which adds files by clicking the button or resets by running the code cell).

  1. Select the code cell
  2. Click “▶ Run”

Replace the Image:

The single-line stores an object in the btn_upload variable. It creates the object using the SimpleNameSpace class in the types module from the Python library. It also sets the data parameter (which sets the attribute name) and the data argument (which sets the associated attribute value).

Simple Namespace is a class that’s used in Python to create an object that can store attributes. It sets the attribute names by defining the parameters and the attribute values by passing the parameter arguments. It can also add attributes with dot notation or remove attributes with the del keyword.

  1. Copy the code from below these instructions
  2. Paste the code over the code in the code cell
  3. Select the code cell
  4. Click “▶ Run”

Load the Image:

The single-line stores an image object in the img variable. It loads the image object using the create method (which uses the open method in the Image module from the PIL library) in the core module from the fastai library. It also sets the fn parameter (which sets the file path that gets returned from the list of file paths in the data attribute in the btn_upload variable).

  1. Select the code cell
  2. Click “▶ Run”

Create the Output Widget:

The first line stores the output widget in the out_pl variable. It creates the output widget using the Output class (which can capture and display the standard output, standard error, and any rich output that’s generated by the IPython library) in the widget_output module from the ipywidgets library.

The second line clears the data in the output widget in the out_pl variable. It clears the data using the clear_output method (which uses the clear-_output function in the display module from the IPython library) in the Output class in the widget_output module from the ipywidgets module.

The third line displays a thumbnail image when the output widget is called. It displays the thumbnail image using the with statement (which runs the associated code when the output widget is called) and the out_pl variable (which contains the output widget that’s attached to the with statement).

The third line also passes a thumbnail image to the display function. It creates the thumbnail image using the to_thumb method (which creates the image using a copy of the image object in the img variable) in the core module from the fastai library. It also sets the h parameter (which sets the image height) and the w parameter (which sets the image width).

The fourth line calls the output widget in the out_pl variable. It displays the image (which was created using the to_thumb method) that was passed to the display function in the code that’s related to the with statement (which ran because the output widget in the out_pl variable was called).

  1. Select the code cell
  2. Click “▶ Run”

Make a Prediction:

The single-line makes a prediction about an image. It makes the prediction using the predict method in the Leaner class in the learner module from the fastai library and stores the deconstructed prediction (which includes the prediction, prediction index, and probabilities) in the pred, pred_idx, and probs variable. It also sets the item parameter (which sets the image).

  1. Select the code cell
  2. Click “▶ Run”

Create the Label Widget:

The first line stores the label widget in the lbl_pred variable. It creates the label widget using the Label class (which creates a custom description next to a control widget using similar styling as the built-in descriptions for the control widget) in the widget_string module from the ipywidgets library.

The second and third lines set the value of the label and display the label widget in the output. It sets the value attribute (which stores the text value that’s displayed) in the label widget using an f-string (which uses the pred variable to display the prediction and the probs and pred_idx variables to display the probability of that prediction using four decimal places). It also calls the lbl_pred variable(which displays the label widget in the output).

  1. Select the code cell
  2. Click “▶ Run”

Create the Button Widget:

The first line stores the button widget in the btn_run variable. It creates the button widget using the Button class (which displays a button that runs the code in the on_click method when the button is clicked) in the widget-_button module from the ipywidgets library. It also sets the description parameter (which sets the text that’s displayed inside the button widget).

The second line displays the button widget in the output. It displays the button widget which runs whatever function is passed to the callback parameter of the on_click method in the Button class in the widget-_button module from the ipywidgets library. It also doesn’t do anything when the button is clicked because the callback parameter isn’t set yet.

  1. Select the code cell
  2. Click “▶ Run”

Define the Application Logic:

The first six lines define the on_click_classify function. It defines the function (which contains the logic for the application) using the code from the last previous steps. It also loads the image, clears the output, displays the thumbnail image, makes the prediction, and displays the prediction.

The seventh line sets up the function to run when the button is clicked. It sets up the function using the on_click method in the Button class in the widget_button module from the ipywidgets library. It also sets the call-back parameter (which sets the function to run when the button is clicked).

  1. Select the code cell
  2. Click “▶ Run”

Create the File Upload Widget:

The first line stores the file upload widget in the btn_upload variable. It creates the file upload widget using the FileUpload class in the widget-_upload module from the ipwidgets library. It also uploads the selected files into the memory of the kernel to be referenced in the notebook.

  1. Select the code cell
  2. Click “▶ Run”

Create the Application:

The single-line creates the layout for the application. It creates the layout using the VBox class (which displays multiple widgets vertically) in the widgets module from the ipywidgets library. It also sets a list of widgets which includes the new label widget, file upload widget in the btn_upload variable, classify button widget in the btn_run variable, output widget in the out_pl variable, and prediction label widget in the lbl_pred variable.

  1. Select the code cell
  2. Click “▶ Run”
  3. Click “Upload”
  4. Select an image
  5. Click “Classify”

“Hopefully, this article helped you get the 👯‍♀️🏆👯‍♀️, remember to subscribe to get more content 🏅”

Next Steps:

This article is part of a series that helps you set up everything you need to complete the Fast.ai course from start to finish. It contains guides that provide answers to the questionnaire at the end of each chapter from the textbook. It also contains guides that walk through the code step-by-step using definitions of terms and commands, instructions, and screenshots.

WSL2:
01. Install the Fastai Requirements
02. Fastai Course Chapter 1 Q&A
03. Fastai Course Chapter 1
04. Fastai Course Chapter 2 Q&A
05. Fastai Course Chapter 2
06. Fastai Course Chapter 3 Q&A
07. Fastai Course Chapter 3
08. Fastai Course Chapter 4 Q&A

Additional Resources:

This article is part of a series that helps you set up everything you need to start using artificial intelligence, machine learning, and deep learning. It contains expanded guides that provide definitions of terms and commands to help you learn what’s happening. It also contains condensed guides that provide instructions and screenshots to help you get the outcome faster.

Linux:
01. Install and Manage Multiple Python Versions
02. Install the NVIDIA CUDA Driver, Toolkit, cuDNN, and TensorRT
03. Install the Jupyter Notebook Server
04. Install Virtual Environments in Jupyter Notebook
05. Install the Python Environment for AI and Machine Learning
WSL2:
01. Install Windows Subsystem for Linux 2
02. Install and Manage Multiple Python Versions
03. Install the NVIDIA CUDA Driver, Toolkit, cuDNN, and TensorRT
04. Install the Jupyter Notebook Server
05. Install Virtual Environments in Jupyter Notebook
06. Install the Python Environment for AI and Machine Learning
07. Install Ubuntu Desktop With a Graphical User Interface (Bonus)
Windows 10:
01. Install and Manage Multiple Python Versions
02. Install the NVIDIA CUDA Driver, Toolkit, cuDNN, and TensorRT
03. Install the Jupyter Notebook Server
04. Install Virtual Environments in Jupyter Notebook
05. Install the Python Environment for AI and Machine Learning
MacOS:
01. Install and Manage Multiple Python Versions
02. Install the Jupyter Notebook Server
03. Install Virtual Environments in Jupyter Notebook
04. Install the Python Environment for AI and Machine Learning

Glossary:

Jupyter Notebook is a program that’s used to create, modify, and distribute notebooks that contain code, equations, visualizations, and narrative text. It provides an interactive coding environment that runs in the web browser. It also has become a preferred tool for machine learning and data science.
[Return]

Python is an object-oriented language that’s known for its simple syntax, code readability, flexibility, and scalability. It mostly gets used to develop web and software applications. It also has become one of the most popular languages for artificial intelligence, machine learning, and data science.
[Return]

Bing Image Search API is a RESTful web service that’s used to search for images on the internet. It returns the images that the user requested by default. It can also use query parameters to sort and filter the image by aspect ratio, color, recency, height, width, image type, license, and size.
[Return]

Interactive Python (IPython) is the interactive shell and default kernel that’s used in Jupyter Notebook. It runs the Python code that’s contained in the Jupyter Notebook files. It also adds new functionality such as introspection, parallel computing, rich media, shell syntax, tab completion, and history.
[Return]

Python Imaging Library (PIL) is a library that’s used in Python to add image editing capabilities to the Python interpreter. It provides functions to load images from files, process images, and create new images in different file formats. It was also discontinued in 2011 and officially replaced by Pillow.
[Return]

Ipywidgets is a library that’s used in Python to provide interactive HTML widgets for Jupyter Notebook. It includes widgets such as buttons, sliders, and dropdowns that combine Python and JavaScript functionality in the web browser. It also allows users to control the data and visualize changes in the data by responding to events and invoking specified event handlers.
[Return]

[ad_2]

Leave a Comment