Machine Learning and Deep Learning Artificial Intelligence is one of the most popular trends of recent times. Machine learning and deep learning constitute artificial intelligence. The Venn diagram shown below explains the relationship of machine learning and deep learning − Machine Learning Machine learning is the art of science of getting computers to act as per the algorithms designed and programmed. Many researchers think machine learning is the best way to make progress towards human-level AI. Machine learning includes the following types of patterns Supervised learning pattern Unsupervised learning pattern Deep Learning Deep learning is a subfield of machine learning where concerned algorithms are inspired by the structure and function of the brain called artificial neural networks. All the value today of deep learning is through supervised learning or learning from labelled data and algorithms. Each algorithm in deep learning goes through the same process. It includes a hierarchy of nonlinear transformation of input that can be used to generate a statistical model as output. Consider the following steps that define the Machine Learning process Identifies relevant data sets and prepares them for analysis. Chooses the type of algorithm to use Builds an analytical model based on the algorithm used. Trains the model on test data sets, revising it as needed. Runs the model to generate test scores. Difference between Machine Learning and Deep learning In this section, we will learn about the difference between Machine Learning and Deep Learning. Amount of data Machine learning works with large amounts of data. It is useful for small amounts of data too. Deep learning on the other hand works efficiently if the amount of data increases rapidly. The following diagram shows the working of machine learning and deep learning with the amount of data − Hardware Dependencies Deep learning algorithms are designed to heavily depend on high-end machines unlike the traditional machine learning algorithms. Deep learning algorithms perform a number of matrix multiplication operations, which require a large amount of hardware support. Feature Engineering Feature engineering is the process of putting domain knowledge into specified features to reduce the complexity of data and make patterns that are visible to learning algorithms it works. Example − Traditional machine learning patterns focus on pixels and other attributes needed for feature engineering process. Deep learning algorithms focus on high-level features from data. It reduces the task of developing new feature extractor of every new problem. Problem Solving Approach The traditional machine learning algorithms follow a standard procedure to solve the problem. It breaks the problem into parts, solve each one of them and combine them to get the required result. Deep learning focusses in solving the problem from end to end instead of breaking them into divisions. Execution Time Execution time is the amount of time required to train an algorithm. Deep learning requires a lot of time to train as it includes a lot of parameters which takes a longer time than usual. Machine learning algorithm comparatively requires less execution time. Interpretability Interpretability is the major factor for comparison of machine learning and deep learning algorithms. The main reason is that deep learning is still given a second thought before its usage in industry. Applications of Machine Learning and Deep Learning In this section, we will learn about the different applications of Machine Learning and Deep Learning. Computer vision which is used for facial recognition and attendance mark through fingerprints or vehicle identification through number plate. Information Retrieval from search engines like text search for image search. Automated email marketing with specified target identification. Medical diagnosis of cancer tumors or anomaly identification of any chronic disease. Natural language processing for applications like photo tagging. The best example to explain this scenario is used in Facebook. Online Advertising. Future Trends With the increasing trend of using data science and machine learning in the industry, it will become important for each organization to inculcate machine learning in their businesses. Deep learning is gaining more importance than machine learning. Deep learning is proving to be one of the best techniques in state-of-art performance. Machine learning and deep learning will prove beneficial in research and academics field. Conclusion In this article, we had an overview of machine learning and deep learning with illustrations and differences also focusing on future trends. Many of AI applications utilize machine learning algorithms primarily to drive self-service, increase agent productivity and workflows more reliable. Machine learning and deep learning algorithms include an exciting prospect for many businesses and industry leaders.
Category: Machine Learning
Theano – Shared Variables Many a times, you would need to create variables which are shared between different functions and also between multiple calls to the same function. To cite an example, while training a neural network you create weights vector for assigning a weight to each feature under consideration. This vector is modified on every iteration during the network training. Thus, it has to be globally accessible across the multiple calls to the same function. So we create a shared variable for this purpose. Typically, Theano moves such shared variables to the GPU, provided one is available. This speeds up the computation. Syntax You create a shared variable you use the following syntax − import numpy W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), ”W”) Example Here the NumPy array consisting of four floating point numbers is created. To set/get the W value you would use the following code snippet − import numpy W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), ”W”) print (“Original: “, W.get_value()) print (“Setting new values (0.5, 0.2, 0.4, 0.2)”) W.set_value([0.5, 0.2, 0.4, 0.2]) print (“After modifications:”, W.get_value()) Output Original: [0.1 0.25 0.15 0.3 ] Setting new values (0.5, 0.2, 0.4, 0.2) After modifications: [0.5 0.2 0.4 0.2]
Theano – Trivial Training Example Theano is quite useful in training neural networks where we have to repeatedly calculate cost, and gradients to achieve an optimum. On large datasets, this becomes computationally intensive. Theano does this efficiently due to its internal optimizations of the computational graph that we have seen earlier. Problem Statement We shall now learn how to use Theano library to train a network. We will take a simple case where we start with a four feature dataset. We compute the sum of these features after applying a certain weight (importance) to each feature. The goal of the training is to modify the weights assigned to each feature so that the sum reaches a target value of 100. sum = f1 * w1 + f2 * w2 + f3 * w3 + f4 * w4 Where f1, f2, … are the feature values and w1, w2, … are the weights. Let me quantize the example for a better understanding of the problem statement. We will assume an initial value of 1.0 for each feature and we will take w1 equals 0.1, w2 equals 0.25, w3 equals 0.15, and w4 equals 0.3. There is no definite logic in assigning the weight values, it is just our intuition. Thus, the initial sum is as follows − sum = 1.0 * 0.1 + 1.0 * 0.25 + 1.0 * 0.15 + 1.0 * 0.3 Which sums to 0.8. Now, we will keep modifying the weight assignment so that this sum approaches 100. The current resultant value of 0.8 is far away from our desired target value of 100. In Machine Learning terms, we define cost as the difference between the target value minus the current output value, typically squared to blow up the error. We reduce this cost in each iteration by calculating the gradients and updating our weights vector. Let us see how this entire logic is implemented in Theano. Declaring Variables We first declare our input vector x as follows − x = tensor.fvector(”x”) Where x is a single dimensional array of float values. We define a scalar target variable as given below − target = tensor.fscalar(”target”) Next, we create a weights tensor W with the initial values as discussed above − W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), ”W”) Defining Theano Expression We now calculate the output using the following expression − y = (x * W).sum() Note that in the above statement x and W are the vectors and not simple scalar variables. We now calculate the error (cost) with the following expression − cost = tensor.sqr(target – y) The cost is the difference between the target value and the current output, squared. To calculate the gradient which tells us how far we are from the target, we use the built-in grad method as follows − gradients = tensor.grad(cost, [W]) We now update the weights vector by taking a learning rate of 0.1 as follows − W_updated = W – (0.1 * gradients[0]) Next, we need to update our weights vector using the above values. We do this in the following statement − updates = [(W, W_updated)] Defining/Invoking Theano Function Lastly, we define a function in Theano to compute the sum. f = function([x, target], y, updates=updates) To invoke the above function a certain number of times, we create a for loop as follows − for i in range(10): output = f([1.0, 1.0, 1.0, 1.0], 100.0) As said earlier, the input to the function is a vector containing the initial values for the four features – we assign the value of 1.0 to each feature without any specific reason. You may assign different values of your choice and check if the function ultimately converges. We will print the values of the weight vector and the corresponding output in each iteration. It is shown in the below code − print (“iteration: “, i) print (“Modified Weights: “, W.get_value()) print (“Output: “, output) Full Program Listing The complete program listing is reproduced here for your quick reference − from theano import * import numpy x = tensor.fvector(”x”) target = tensor.fscalar(”target”) W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), ”W”) print (“Weights: “, W.get_value()) y = (x * W).sum() cost = tensor.sqr(target – y) gradients = tensor.grad(cost, [W]) W_updated = W – (0.1 * gradients[0]) updates = [(W, W_updated)] f = function([x, target], y, updates=updates) for i in range(10): output = f([1.0, 1.0, 1.0, 1.0], 100.0) print (“iteration: “, i) print (“Modified Weights: “, W.get_value()) print (“Output: “, output) When you run the program you will see the following output − Weights: [0.1 0.25 0.15 0.3 ] iteration: 0 Modified Weights: [19.94 20.09 19.99 20.14] Output: 0.8 iteration: 1 Modified Weights: [23.908 24.058 23.958 24.108] Output: 80.16000000000001 iteration: 2 Modified Weights: [24.7016 24.8516 24.7516 24.9016] Output: 96.03200000000001 iteration: 3 Modified Weights: [24.86032 25.01032 24.91032 25.06032] Output: 99.2064 iteration: 4 Modified Weights: [24.892064 25.042064 24.942064 25.092064] Output: 99.84128 iteration: 5 Modified Weights: [24.8984128 25.0484128 24.9484128 25.0984128] Output: 99.968256 iteration: 6 Modified Weights: [24.89968256 25.04968256 24.94968256 25.09968256] Output: 99.9936512 iteration: 7 Modified Weights: [24.89993651 25.04993651 24.94993651 25.09993651] Output: 99.99873024 iteration: 8 Modified Weights: [24.8999873 25.0499873 24.9499873 25.0999873] Output: 99.99974604799999 iteration: 9 Modified Weights: [24.89999746 25.04999746 24.94999746 25.09999746] Output: 99.99994920960002 Observe that after four iterations, the output is 99.96 and after five iterations, it is 99.99, which is close to our desired target of 100.0. Depending on the desired accuracy, you may safely conclude that the network is trained in 4 to 5 iterations. After the training completes, look up the weights vector, which after 5 iterations takes the following values − iteration: 5 Modified Weights: [24.8984128 25.0484128 24.9484128 25.0984128] You may now use these values in your network for deploying the model.
Scikit Image – Image Stack A stack, in general, refers to a collection of independent components that collaborate to enable a particular functionality of an application. On the other hand, an image stack combines a group of images that share a common reference. While the images in the stack may vary in terms of quality or content, they are organized together for efficient processing and analysis. The image stack is grouped together for analysis or processing purposes, allowing for efficient batch operations. In the scikit-image library, the io module offers functions push() and pop() specifically for working with the image stack. The Io.pop() and io.push() functions The pop() function is used to remove an image from the shared image stack. It returns the image that has been popped from the stack as a NumPy ndarray. And the push(img) function is used to add a specific image to the shared image stack. It takes a NumPy ndarray (image array) as input. Example The following example demonstrates how to push images onto the shared stack using io.push() and retrieve images from the stack using io.pop(). It will also show that attempting to pop an image from an empty stack will raise an error named IndexError. import skimage.io as io import numpy as np # Generate images with random numbers image1 = np.random.rand(2, 2) image2 = np.random.rand(1, 3) # Push all image onto the shared stack one by one io.push(image1) io.push(image2) # Pop an image from the stack popped_image_array1 = io.pop() # Display the popped image array print(“The array of popped image”,popped_image_array1) # Pop another image from the stack popped_image_array2 = io.pop() # Display the popped image array print(“The array of popped image”,popped_image_array2) popped_image_array3 = io.pop() # Output IndexError popped_image_array3 Output The array of popped image [[0.58981037 0.04246133 0.78413075]] The array of popped image [[0.47972125 0.55525751] [0.02514485 0.15683907]] ————————————————————————— IndexError Traceback (most recent call last) ~AppDataLocalTempipykernel_7922226447525.py in < module > 23 24 # will rice an IndexError —> 25 popped_image_array3 = io.pop() 26 popped_image_array3 ~anaconda3libsite-packagesskimageio_image_stack.py in pop() 33 34 “”” —> 35 return image_stack.pop() IndexError: pop from empty list The last two lines of the above example will raise an IndexError. This is because there are only two images pushed onto the shared stack using io.push(), but the third call to io.pop() attempts to pop an image from the stack, causing an IndexError since the stack is empty after the first two pops.
TensorFlow – Installation To install TensorFlow, it is important to have “Python” installed in your system. Python version 3.4+ is considered the best to start with TensorFlow installation. Consider the following steps to install TensorFlow in Windows operating system. Step 1 − Verify the python version being installed. Step 2 − A user can pick up any mechanism to install TensorFlow in the system. We recommend “pip” and “Anaconda”. Pip is a command used for executing and installing modules in Python. Before we install TensorFlow, we need to install Anaconda framework in our system. After successful installation, check in command prompt through “conda” command. The execution of command is displayed below − Step 3 − Execute the following command to initialize the installation of TensorFlow − conda create –name tensorflow python = 3.5 It downloads the necessary packages needed for TensorFlow setup. Step 4 − After successful environmental setup, it is important to activate TensorFlow module. activate tensorflow Step 5 − Use pip to install “Tensorflow” in the system. The command used for installation is mentioned as below − pip install tensorflow And, pip install tensorflow-gpu After successful installation, it is important to know the sample program execution of TensorFlow. Following example helps us understand the basic program creation “Hello World” in TensorFlow. The code for first program implementation is mentioned below − >> activate tensorflow >> python (activating python shell) >> import tensorflow as tf >> hello = tf.constant(‘Hello, Tensorflow!’) >> sess = tf.Session() >> print(sess.run(hello))
TensorFlow – Hidden Layers of Perceptron In this chapter, we will be focus on the network we will have to learn from known set of points called x and f(x). A single hidden layer will build this simple network. The code for the explanation of hidden layers of perceptron is as shown below − #Importing the necessary modules import tensorflow as tf import numpy as np import math, random import matplotlib.pyplot as plt np.random.seed(1000) function_to_learn = lambda x: np.cos(x) + 0.1*np.random.randn(*x.shape) layer_1_neurons = 10 NUM_points = 1000 #Training the parameters batch_size = 100 NUM_EPOCHS = 1500 all_x = np.float32(np.random.uniform(-2*math.pi, 2*math.pi, (1, NUM_points))).T np.random.shuffle(all_x) train_size = int(900) #Training the first 700 points in the given set x_training = all_x[:train_size] y_training = function_to_learn(x_training) #Training the last 300 points in the given set x_validation = all_x[train_size:] y_validation = function_to_learn(x_validation) plt.figure(1) plt.scatter(x_training, y_training, c = ”blue”, label = ”train”) plt.scatter(x_validation, y_validation, c = ”pink”, label = ”validation”) plt.legend() plt.show() X = tf.placeholder(tf.float32, [None, 1], name = “X”) Y = tf.placeholder(tf.float32, [None, 1], name = “Y”) #first layer #Number of neurons = 10 w_h = tf.Variable( tf.random_uniform([1, layer_1_neurons], minval = -1, maxval = 1, dtype = tf.float32)) b_h = tf.Variable(tf.zeros([1, layer_1_neurons], dtype = tf.float32)) h = tf.nn.sigmoid(tf.matmul(X, w_h) + b_h) #output layer #Number of neurons = 10 w_o = tf.Variable( tf.random_uniform([layer_1_neurons, 1], minval = -1, maxval = 1, dtype = tf.float32)) b_o = tf.Variable(tf.zeros([1, 1], dtype = tf.float32)) #build the model model = tf.matmul(h, w_o) + b_o #minimize the cost function (model – Y) train_op = tf.train.AdamOptimizer().minimize(tf.nn.l2_loss(model – Y)) #Start the Learning phase sess = tf.Session() sess.run(tf.initialize_all_variables()) errors = [] for i in range(NUM_EPOCHS): for start, end in zip(range(0, len(x_training), batch_size), range(batch_size, len(x_training), batch_size)): sess.run(train_op, feed_dict = {X: x_training[start:end], Y: y_training[start:end]}) cost = sess.run(tf.nn.l2_loss(model – y_validation), feed_dict = {X:x_validation}) errors.append(cost) if i%100 == 0: print(“epoch %d, cost = %g” % (i, cost)) plt.plot(errors,label=”MLP Function Approximation”) plt.xlabel(”epochs”) plt.ylabel(”cost”) plt.legend() plt.show() Output Following is the representation of function layer approximation − Here two data are represented in shape of W. The two data are: train and validation which are represented in distinct colors as visible in legend section.
Scikit Image – Displaying Images Displaying or visualizing images plays a crucial role in image processing and computer vision tasks. It is necessary to visualize images when performing image processing operations such as cropping, resizing, rotating, or applying various filters. Displaying images refers to the process of visualizing or presenting digital images on a screen or other output devices. It allows us to view and interpret the content of images in a visual format. In the scikit-image library, the io module offers functions like imshow() and show() for displaying images on a screen. These functions are useful for displaying the results of image manipulation operations. Using the io.imshow() method The skimage.io.imshow() method is used to display an image. It opens a window and displays the image using the specified or default image plugins. Following is the syntax and parameters of this method − skimage.io.imshow(arr, plugin=None, **plugin_args) Following are the parameters of this function − arr − An ndarray or a string representing image data or the name of an image file. plugin − A string specifying the name of the plugin to be used. If not provided, the function will attempt to find a suitable plugin from the available options, starting with “imageio”. **plugin_args − Additional keyword arguments that are passed to the chosen plugin. Example The following example will display the image using the default image plugin. from skimage import io # Displaying image using the image name io.imshow(”Images/logo-w.png”) Output Running the above code gives us the following result − <matplotlib.image.AxesImage at 0x20980099d30 > Using the io.show() method The skimage.io.show() function is used to display pending images in scikit-image. It launches the event loop of the current GUI plugin and shows all images that have been queued for display using the imshow() function. This is particularly useful when working with non-interactive scripts. Following is the syntax of this method − skimage.io.show() Note, If you are working in an interactive environment, such as Jupyter Notebook or an interactive Python shell, you can simply use imshow() to display the image. However, if you are running a non-interactive script, it is best to include show() at the end to ensure that all images are displayed before the script terminates. Example 1 The following example will display an image using the imshow() and show() methods. from skimage import io # Read the image from an URL image = io.imread(”https://www.tutorialspoint.com/images/logo.png”) # Display an image io.imshow(image) io.show() Output Running the above code gives us the following result − Example 2 The following example will display the 2 images using the imshow() and show() methods. from skimage import io import numpy as np import time image1 = np.random.randint(0, 256, size=(50, 50, 3), dtype=np.uint8) image2 = np.random.randint(0, 256, size=(50, 50), dtype=np.uint8) # Displaying the image1 io.imshow(image1) io.show() # Displaying the image2 io.imshow(image2) io.show() Output The above program generates the following output − Following is the second image −
Scikit Image – Using Plugins A plugin refers to an extension or external software component that can enhance the functionality of the program by adding specific features to it thus improving its functionality. Plugins in Python Scikit Image The Python scikit-image (skimage) library comes with a variety of plugins that can be used to handle image IO operations, such as reading, writing, and displaying images. The available plugins in the scikit-image library include popular libraries like Matplotlib, PIL (Python Imaging Library), GDAL, SimpleITK, tifffile, PyFITS, and ImageIO. Each plugin specializes in a specific image IO operation. The scikit-image library loads the plugins as needed, to ensure optimal performance, and to allow efficient resource utilization. This means that plugins are only loaded when explicitly required or when set as default. This dynamic loading mechanism ensures that only the necessary plugins are loaded, depending on the specific image I/O operation. Also, the scikit-image library provides a range of functional tools to handle and operate plugins. These tools allow users to customize their image IO operations, let’s discuss some key plugin functions available in the skimage.io module. Listing the available plugins The function io.find_available_plugins(loaded=False) is used to list the available plugins in scikit-image (skimage.io). And it returns a dictionary with plugin names as keys and exposed functions as values. Following is the syntax of this function − skimage.io.find_available_plugins(loaded=False) The parameter “loaded” takes a boolean value. If it is set to True, only the loaded plugins will be shown. By default, all plugins are displayed. Example 1 The following example demonstrates the use of io.find_available_plugins() function to list all the available plugins and their corresponding exposed functions. import skimage.io as io # List all available plugins available_plugins = io.find_available_plugins() # Display the plugin names and their exposed functions for plugin_name, exposed_functions in available_plugins.items(): print(”Plugin:”, plugin_name) print(“Exposed Functions:”, exposed_functions) print() Output Plugin: fits Exposed Functions: [”imread”, ”imread_collection”] Plugin: gdal Exposed Functions: [”imread”, ”imread_collection”] Plugin: gtk Exposed Functions: [”imshow”] Plugin: imageio Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: imread Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: matplotlib Exposed Functions: [”imshow”, ”imread”, ”imshow_collection”, ”imread_collection”] Plugin: pil Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: qt Exposed Functions: [”imshow”, ”imsave”, ”imread”, ”imread_collection”] Plugin: simpleitk Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: tifffile Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Example 2 Let”s get the information about loaded plugins only. from skimage import io # List loaded plugins only available_plugins = io.find_available_plugins(loaded=True) # Display the loaded plugin names and their exposed functions for plugin_name, exposed_functions in available_plugins.items(): print(”Plugin:”, plugin_name) print(“Exposed Functions:”, exposed_functions) print() Output Plugin: imageio Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: matplotlib Exposed Functions: [”imshow”, ”imread”, ”imshow_collection”, ”imread_collection”] Plugin: tifffile Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Retrieving Info about a specific plugin The function io.plugin_info(plugin) is used to retrieve information about a specific plugin. It returns a dictionary containing information about the plugin, such as the description, and provides nothing but available function names. Following is the syntax of this function − skimage.io.plugin_info(plugin) The parameter “plugin” takes a string representing the name of the plugin for which you want to retrieve information. Example 1 The following example demonstrates how to use the io.plugin_info() function to retrieve the information about the ”pil” plugin. from skimage import io # Get information about the ”pil” plugin plugin_info = io.plugin_info(”pil”) # Print the plugin information print(“Description:”, plugin_info[”description”]) print(“Available Functions:”, plugin_info[”provides”]) print() Output Description: Image reading via the Python Imaging Library Available Functions: imread, imsave Example 2 In this example, we will get information about the ”matplotlib” plugin. from skimage import io # Get information about the ”matplotlib” plugin plugin_info = io.plugin_info(”matplotlib”) # Print the plugin information print(“Description:”, plugin_info[”description”]) print(“Available Functions:”, plugin_info[”provides”]) print() Output Description: Display or save images using Matplotlib Available Functions: imshow, imread, imshow_collection, _app_show Retrieving the plugin order The io.plugin_order() function is used to obtain the currently preferred plugin order. Following is the syntax of this function − skimage.io.plugin_order() The function returns a dictionary with function names as keys and the corresponding values are lists of plugins in the order of preference. Example Following is an example of using the plugin_order() function to obtain the currently preferred plugin order. from skimage import io # Get the currently preferred plugin order order_dict = io.plugin_order() # Print the plugin loading order print(“Preferred Plugin Order:”) for function_name, plugins in order_dict.items(): print(“Function:”, function_name) print(“Plugins in order of preference:”, plugins) print() Output Preferred Plugin Order: Function: imread Plugins in order of preference: [”imageio”, ”matplotlib”] Function: imsave Plugins in order of preference: [”imageio”] Function: imshow Plugins in order of preference: [”matplotlib”] Function: imread_collection Plugins in order of preference: [”imageio”, ”matplotlib”] Function: imshow_collection Plugins in order of preference: [”matplotlib”] Function: _app_show Plugins in order of preference: [”matplotlib”] Setting the default plugin The io.use_plugin() function is used to set the default plugin for a specified operation. The specified plugin will be loaded if it hasn”t been loaded already. Following is the syntax of this function − skimage.io.use_plugin(name, kind=None) Here are the parameters of this function − name − A string representing the name of the plugin is to be set as the default. kind (optional) − A string represents the specific function for which the plugin is being set. It can take one of the following values: ”imsave”, ”imread”, ”imshow”, ”imread_collection”, ”imshow_collection”. By default, the plugin is set for all functions. Example The following example shows the change in the plugin loading order after setting the default plugin. from skimage import io # Get the currently preferred plugin order order_dict_1 = io.plugin_order() # Print the plugin loading order print(“Plugin Order before Setting the default plugin:”) for function_name, plugins in order_dict_1.items(): print(function_name) print(“Plugin order:”, plugins) print() # Set the default plugin for all functions io.use_plugin(”qt”) # Get the preferred plugin order after setting the default plugin order_dict_2 = io.plugin_order() # Print the plugin loading order print(“Plugin Order after setting the default plugin: “) for function_name, plugins in order_dict_2.items(): print(function_name) print(“Plugin order:”, plugins) print() Output Plugin Order before Setting the default plugin: imread Plugin order: [”imageio”, ”matplotlib”] imsave Plugin order: [”imageio”] imshow Plugin order: [”matplotlib”] imread_collection Plugin
Scikit Image – Using Napari Scikit Image with Napari Napari is a powerful Python library for n-dimensional image visualization, annotation, and analysis. It provides a flexible and interactive environment for working with image data. Following are some key features and capabilities of Napari − Viewing and Exploring − Napari allows you to view and explore n-dimensional arrays on a canvas. It supports 2D, 3D, and higher-dimensional data, providing a responsive and interactive visualization experience. Overlay derived data − Napari enables you to overlay derived data such as points, polygons, segmentations, labels, and more. Annotation and Editing − Napari provides tools for annotating and editing the derived datasets. You can add, modify, or delete annotations interactively using a variety of tools. Napari integrates with standard data structures like NumPy or Zarr arrays, enabling efficient annotation and analysis workflows. And it is a fast, interactive viewer for multi-dimensional images in Python. Also, it provides a user-friendly interface, extensive customization options, and the ability to integrate with other scientific Python libraries. Installation of Napari To use Napari, you will need the following requirements − Python > = 3.8 − Napari requires Python version 3.8 or higher. Make sure you have a compatible version installed on your system. Ability to Install Python Packages − You should have the ability to install Python packages using either pip or conda-forge. These are package managers that allow you to easily install and manage Python libraries and dependencies. Additionally, it is recommended to have − Environment Manager (such as Conda) − While not strictly required, having an environment manager like Conda can be beneficial. Conda allows you to create isolated Python environments. It provides a convenient way to manage your Python environment and ensure compatibility with other libraries and tools. Installing Napari using pip To install Napari using pip, just run the following command in your command prompt − python -m pip install “napari[all]” Installing Napari using Conda-Forge If you”re using the Anaconda distribution already in your system then you can directly install napari from the conda-forge channel. Following is the command − conda install -c conda-forge napari Once Napari is installed, you can use it in your Python scripts. Below are a few basic Python programs that demonstrate how to use the Napari library along with scikit-image to perform data visualization tasks effectively. Example 1 The following example demonstrates how to display an image using the Viewer() method in the Napari library. import napari from skimage import io # Read an image image = io.imread(”Images/logo-w.png”) # Display the image using Napari viewer = napari.Viewer() viewer.add_image(image, name=”Tutorialspoint”) Output On executing the above program, you will get the following output − Example 2 The following example demonstrates how to apply a circular mask to an image using scikit-image and display the original image and the masked images using the Napari library. import napari from skimage import io # Load the image image_path = ”Images_/Zoo.jpg” image = io.imread(image_path) image_copy = np.copy(image) # Create circular mask rows, cols, _ = image.shape row, col = np.ogrid[:rows, :cols] center_row, center_col = rows / 2, cols / 2 radius = min(rows, cols) / 2 outer_disk_mask = ((row – center_row)**2 + (col – center_col)**2 > radius**2) # Apply mask to image image[outer_disk_mask] = 0 # Display the image using Napari viewer = napari.Viewer() viewer.add_image(image_copy, name=”Input Image”) viewer.add_image(image, name=”Output masked Image”) Output On executing the above program, you will get the following output −
TensorFlow – Multi-Layer Perceptron Learning Multi-Layer perceptron defines the most complicated architecture of artificial neural networks. It is substantially formed from multiple layers of perceptron. The diagrammatic representation of multi-layer perceptron learning is as shown below − MLP networks are usually used for supervised learning format. A typical learning algorithm for MLP networks is also called back propagation’s algorithm. Now, we will focus on the implementation with MLP for an image classification problem. # Import MINST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets(“/tmp/data/”, one_hot = True) import tensorflow as tf import matplotlib.pyplot as plt # Parameters learning_rate = 0.001 training_epochs = 20 batch_size = 100 display_step = 1 # Network Parameters n_hidden_1 = 256 # 1st layer num features n_hidden_2 = 256 # 2nd layer num features n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input x = tf.placeholder(“float”, [None, n_input]) y = tf.placeholder(“float”, [None, n_classes]) # weights layer 1 h = tf.Variable(tf.random_normal([n_input, n_hidden_1])) # bias layer 1 bias_layer_1 = tf.Variable(tf.random_normal([n_hidden_1])) # layer 1 layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, h), bias_layer_1)) # weights layer 2 w = tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])) # bias layer 2 bias_layer_2 = tf.Variable(tf.random_normal([n_hidden_2])) # layer 2 layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, w), bias_layer_2)) # weights output layer output = tf.Variable(tf.random_normal([n_hidden_2, n_classes])) # biar output layer bias_output = tf.Variable(tf.random_normal([n_classes])) # output layer output_layer = tf.matmul(layer_2, output) + bias_output # cost function cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits = output_layer, labels = y)) #cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(output_layer, y)) # optimizer optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) # optimizer = tf.train.GradientDescentOptimizer( learning_rate = learning_rate).minimize(cost) # Plot settings avg_set = [] epoch_set = [] # Initializing the variables init = tf.global_variables_initializer() # Launch the graph with tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples / batch_size) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) # Fit training using batch data sess.run(optimizer, feed_dict = { x: batch_xs, y: batch_ys}) # Compute average loss avg_cost += sess.run(cost, feed_dict = {x: batch_xs, y: batch_ys}) / total_batch # Display logs per epoch step if epoch % display_step == 0: print Epoch:”, ”%04d” % (epoch + 1), “cost=”, “{:.9f}”.format(avg_cost) avg_set.append(avg_cost) epoch_set.append(epoch + 1) print “Training phase finished” plt.plot(epoch_set, avg_set, ”o”, label = ”MLP Training phase”) plt.ylabel(”cost”) plt.xlabel(”epoch”) plt.legend() plt.show() # Test model correct_prediction = tf.equal(tf.argmax(output_layer, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, “float”)) print “Model Accuracy:”, accuracy.eval({x: mnist.test.images, y: mnist.test.labels}) The above line of code generates the following output −