<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Giuseppe Pio Cannata on Medium]]></title>
        <description><![CDATA[Stories by Giuseppe Pio Cannata on Medium]]></description>
        <link>https://medium.com/@cannydatascience?source=rss-2068ede1c367------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IauiKp8b3v5h32lW_9p2kg.jpeg</url>
            <title>Stories by Giuseppe Pio Cannata on Medium</title>
            <link>https://medium.com/@cannydatascience?source=rss-2068ede1c367------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:17:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cannydatascience/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PackML: towards smarter automation]]></title>
            <link>https://levelup.gitconnected.com/packml-towards-smarter-automation-25998a907a57?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/25998a907a57</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[packml]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[industry-4-0]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Mon, 19 May 2025 02:45:51 GMT</pubDate>
            <atom:updated>2025-05-19T02:45:51.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*21h_AS61X8dE00Cd" /><figcaption>iPhoto by <a href="https://unsplash.com/@gitfo?utm_source=medium&amp;utm_medium=referral">Gerrie van der Walt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Industrial automation is a key area in modern industry, as it can optimize production process, increase efficency and reduce the operating costs. By integrating advance technology such as PLC (Programmable Logic Controller), SCADA (Supervisory Control And Data Acquisition), IIoT (Industrial Internet of Things) and robotics, companies can achieve greater flexibility and productivity in their plants.</p><p>At the base of it all, software plays a key role. The increase complexity of industrial plant requires an structured approach to programming, which is why adopting a framework is crucial.</p><p>A well-designed framework must be able to offer the following benefits:</p><ul><li><strong>Modularity and Reusability</strong>: Well-structured software is divided into indipendent modules, facilitating code reuse and maintenance.</li><li><strong>Scalability:</strong> The ability to extend the system without rewrite entire portions of code is essential to adapt to system evolutions.</li><li><strong>Maintainability:</strong> Well-organize code reduces the errors and simplify the debugging, improving system reliability</li><li><strong>Standardization</strong>: The use of common guidelines and templates encourages the collaboration among different development teams</li></ul><h3>1. Pack ML</h3><p>PackML (<em>Packaging Machine Language</em>) is a standard develop by OMAC (<em>Organization for Machine Automation and Control</em>) for machines programming in industial enviroments.</p><p>It is designed to simplify programming, management and communication between different machines and systems, improving their control and maintenance over time.</p><p>The goals can be summarized in the following points:</p><ul><li><strong>Standardization:</strong> Create a common behavior by making it easy to integrate machines from different vendors</li><li><strong>Interoperability:</strong> Improving communication between machine and control systems, enabling different machines to “talk” to each other and to centralized monitoring and management systems.</li><li><strong>Performance Optimization:</strong> Optimizing operations, reducing downtime, improving resource management.</li><li><strong>Industry 4.0 Facilitation</strong>: Support digitization, data collection and real-time communication between machines and centralized systems.</li></ul><h3><strong>2. Standardization of machine behavior</strong></h3><p>Let us now delve into how PackML standardizes the behavior of machines. The standard defines a set of specific states in which, a machine and its subcomponents (<em>Units</em>), can be during the operative cycle.</p><p><strong>2.1. Machine states and transitions between them</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*yN5UBAyy0E7dW7OEMxGN7Q.jpeg" /><figcaption>Fig.1: Rappresentation of standard OMAC</figcaption></figure><p>Fig.1 shows the different possible states of machine (<em>called OMAC states</em>) and the possible transitions between their. In particular, the colors represent the behaviour associated whit each state:</p><ol><li><strong>Green states</strong>: these are transitions states, the phase in which the machine is actived and do the operations to continue in the operative cycle</li><li><strong>Blue state</strong>: is the operational state (EXECUTE) in which the machine is performing its normal operative cycle</li><li><strong>Yellow state</strong>: represent the finished states, in which the machine has completed its operations and is waiting for a specific command to move to the next state. Among these we have:</li></ol><ul><li><em>Initial state</em> (IDLE): the machine is ready to be started, but it’s not running</li><li><em>Completed state</em><strong> (</strong>COMPLETE): The machine has completed production</li><li><em>Stop State </em>(STOPPED): The machine is stopped, but can be restarted</li><li><em>Abort state </em>(ABORTED): The machine is stopped due to a problem</li></ul><p>The PackML framework provides for active operator interaction with the system, in addition to the normal automatic machine cycle. Looking at Fig.1, we can see that there are arrows between the various states that represent possible <strong>transitions</strong>.</p><p>Transitions labeled SC (State Completed) indicate that the current state, once the intended operations are completed, <strong>evolves autonomously</strong> to the next state, without any external intervention.</p><p>In contrast, transitions highlighted in red represent actions that <strong>can be triggered by the operator</strong>, but do <strong>not necessarily </strong>have to be.<br>On what does this difference depend?</p><p>Consider, for example, the <strong>Stop</strong> and<strong> Abort</strong> transitions.<br>Traditionally, the Stop transition is linked to the operator pressing the stop button. However, the programmer can configure the system in a more advanced way by providing that the Stop <strong>is also triggered automatically</strong> in response to certain abnormal process conditions.</p><p>For example, suppose that a product X has to pass through <strong>sensor A </strong>first and within 30 seconds, <strong>sensor B</strong> as well. If this does not happen in the allotted time, the system can automatically trigger the transition to the Stop state, without the manual intervention.</p><p>The same principle applies to the <strong>Abort</strong> transition, typically associated with critical error situations and the emergency button.<br>To better understand, let us analyze a practical example:</p><p>Let us imagine that the machine is in the <strong>Execute</strong> state, i.e., in full operation. At some point, an actuator detects an abnormality, such as <strong>extra torque</strong>, and generates an error. In this case, to prevent possible damage, the programmer must have configured the system so that this type of error automatically triggers the transition to the stop state.</p><p>The machine will then enter the Aborting state, during which it performs all necessary operations to safely stop the motors and bring the entire system to a safe condition. Upon completion of this phase, the system transits into the <strong>Aborted</strong> state, which represents a stable but <strong>non-operational</strong> condition from which it cannot automatically restart.</p><p>At this point, operator <strong>intervention is required</strong>, and the operator must press the <strong>Reset</strong> button. The machine will perform the <strong>Resetting</strong> operations, returning to the <strong>Idle</strong> state, ready for a fresh start.</p><p>Finally, to start the production cycle again, the operator must press the <strong>Start</strong> button. The system will then enter the <strong>Starting</strong> state, during which all preliminary operations will be performed, until it returns to the <strong>Execute</strong> state, resuming normal operation.</p><p><strong>2.2. Distinction between Hold and Suspended</strong></p><p>The <strong>Hold</strong> and <strong>Suspended </strong>states represent two pause conditions that a machine can assume during the normal operating cycle. In both cases, the machine <strong>temporarily suspends activities</strong> while waiting for certain conditions to occur in order to resume the process.</p><p>However, it’s important to distinguish clearly between the two:</p><ul><li>The <strong>Hold</strong> state is used when the machine <strong>cannot continue activity due to an external</strong>, but <strong>not critical</strong>, <strong>temporary condition</strong>, thus not such as to require an Aborted or Stopped state. It is an <strong>automatic transition</strong>, triggered by the system itself. A practical example might be a <strong>lack of material to process</strong>, or a <strong>momentary blockage of a downstream</strong> machine that causes the upstream one to suspend execution while waiting for the flow to resume</li><li>In contrast, the <strong>Suspend</strong> state <strong>represents a manual pause in the cycle</strong>, <strong>intentionally requested by an operator</strong> or by a command from the supervisory system. A typical case is when a <strong>visual product inspection</strong> or scheduled check is performed</li></ul><p>In summary, while <strong>Hold</strong> is an automatic pause due to external operating conditions, <strong>Suspend </strong>is a voluntary and controlled pause by the operator or system. Both allow more flexible and safe management of the production process without completely interrupting the machine cycle.</p><p><strong>2.2. Distinction between Stop and Abort</strong></p><p>One question that might arise is: What is the distinction between Stop and Abort?</p><p>When we talk about Stop, we mean an <strong>Stop in phase</strong>, or rather, a controlled stop of the system. In this mode, the machine neatly terminates ongoing operations, bringing each component to a safe condition. An example might be as follows: Suppose we have a labeling machine that applies labels to water bottles. If the operator presses the stop button while the machine is starting the labeling of a new bottle, the system <strong>does not stop</strong> <strong>immediately</strong>. Instead, the machine completes the labeling in progress, after which it performs the necessary movements <strong>to bring itself to a safe condition</strong> (e.g., bringing the mechanisms to their initial or rest position). Only then, the stop of the machine cycle is made. This type of stop, is typically used in contexts where there is no imminent danger, but it is still necessary to interrupt the production cycle. This transition allows the machine to safeguard ongoing production and maintain internal state consistency.</p><p>Abort, on the other hand, is the most drastic transition. It represents an <strong>immediate and uncontrolled</strong> interruption typical of emergency situations. It is triggered when a major failure or a condition hazardous to people, machines or products occurs.<br>In <em>Abort</em> mode, the first priority is <strong>safety</strong>: all operations are stopped instantaneously, without regard to the current state of the machine.<br>Subsequently, manual intervention and explicit resetting by the operator is often required to resume the production cycle.</p><p><strong>2.4. Units</strong></p><p>To ensure <strong>modularity</strong>, <strong>scalability,</strong> and better <strong>diagnostics,</strong> PackML introduces the concept of <strong>Units</strong>, dividing the machine into <strong>independent subsystems</strong>. Each <strong>Unit</strong> operates autonomously with its own states, but remains synchronized with the overall system.</p><p>In fact, at the hierarchical level, we will have a <strong>Unit Zero</strong> (which we will call <strong>Machine</strong> for simplicity), responsible for managing the <strong>overall OMAC state</strong> of the machine. The other <strong>Units</strong> will model specific parts of our machine, maintaining a dependency on the<strong> Machine </strong>to ensure a coordinated and standardized workflow.</p><h3>3. From theory to programming: Modeling the PackML</h3><p>Let’s focus on figuring out how to transport what we have learned so far into programming. To do this, suppose we need to model a machine divided into two units.</p><p>To make the discussion more generic and accessible, I will use <strong>Python</strong> instead of a tool specific to the automation world. I have chosen not to adopt typical object-oriented programming concepts, such as <strong>inheritance and polymorphism</strong>, to keep the code simpler and more straightforward.</p><p>Through the implementation of a <strong>class</strong>, I simulated the operation of a <strong>PLC</strong>, replicating its typical behavior. The concepts developed are easily adaptable and reusable in different contexts.</p><p>The developed code is available at the following l<a href="https://github.com/GiuseppeCannata/OMAC_Framework">ink</a>.</p><p><strong>3.1 Implementation of Units</strong></p><p>Below are the data structures that we will use throughout the article.</p><pre>class ST_REQUESTS:<br>  State     : int = 0<br>  Mode      : int = 0<br><br>class ST_UNITS_FDKs:<br>  Started   : bool = False<br>  Aborted   : bool = False<br>  Stopped   : bool = False<br>  Resetted  : bool = False<br>  Completed : bool = False<br>  Suspended : bool = False<br>  Unspended : bool = False<br>  Holded    : bool = False<br>  Unholded  : bool = False<br><br>class ST_MACHINE_CMD:<br>  Start     : bool = False<br>  Stop      : bool = False<br>  Abort     : bool = False<br>  Reset     : bool = False<br>  Suspend   : bool = False<br><br>class ST_State:<br>  Text      : str = &#39;&#39;<br>  Value     : int = 0<br><br>class IO_Signals:<br>  start     : bool = False<br>  stop      : bool = False<br>  emergency : bool = False<br>  reset     : bool = False</pre><h4>Machine</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*P04dtf7ygYGi367BOM_uUw.jpeg" /></figure><p>As anticipated, the <strong>Machine</strong> represents <strong>Unit 0</strong> and is responsible for coordinating the other <strong>Units</strong>. To do this, it needs two basic variables:</p><ul><li><strong>Units_Fbks</strong>: a variable of type ST_UNITS_FDKs, used to collect <strong>feedback</strong> sent by the <strong>Units</strong>. This feedback allows the <strong>Machine </strong>to verify the completion of operations in the individual transition states.</li><li><strong>Actual_State:</strong> variable of type ST_STATE, which stores the current <strong>OMAC</strong> state of the <strong>Machine</strong>.</li></ul><p>In addition to the above variables, we must remember to map as inputs the commands of type ST_MACHINE_CMD representing <em>start</em>, <em>stop</em>, <em>abort</em> <em>and</em> etc…, highlighted in red in Fig.1.</p><p>As for the methods we have the <em>init</em> which deals with the initialization of the private/static variables of our Unit and the <em>cycle</em> method in which we are going to define the main state machine.</p><ul><li><strong>Cycle implementation</strong></li></ul><p>A possible implementation of the cyclemethod is presented below. As can be seen, in each <em>transition state</em> (shown in green in Fig. 1), feedback from the units is evaluated to determine the transition to a <em>stable state</em> (shown in yellow). In the latter, the system waits for commands (Cmd) sent by the operator or programmer, as mentioned earlier.</p><p>One difference that might stand out when comparing Fig.1 with the OMAC state machine implementation concerns the handling of the <em>Aborted </em>&gt; <em>Clearing </em>&gt; <em>Stopped</em> &gt; <em>Resetting</em> transition. By personal choice, I decided that at the end of the Aborted state, following a reset command, the system goes directly to the <em>Resetting </em>state, as shown in Fig.2. This choice is motivated by the fact that, in the <em>Aborted</em> state, I typically manage the automation shutdown, thus ensuring that the machine is in a safe condition. At this point, once the reset command is received, it is possible to perform all the necessary reset operations and go directly to the <em>Idle</em> state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*y6PWH5hc1ZGc8lbD4U8u5A.jpeg" /><figcaption>Fig.2: Simplification of the OMAC standard presented in Fig.1</figcaption></figure><p>In addition, as Machine output, the aggregate variables InCycle, InStoppedand InAborted, also shown in Fig.1 and Fig.2, can be updated. These signals allow the current state of the machine to be effectively monitored.</p><pre>def cycle(self):<br><br>        if self.iCmd.Abort and not self.oInAborted:<br>            self.__State.Value = 6<br>        elif self.iCmd.Stop and not self.oInStopped and not self.oInAborted:<br>            self.__State.Value = 4<br><br>        match self.__State.Value:<br><br>            case 0:<br>                self.__State.Text = &#39;IDLE&#39;<br><br>                if self.iCmd.Start:<br>                    self.__State.Value = 1<br><br>            case 1:<br>                self.__State.Text = &#39;STARTING&#39;<br><br>                if self.iUnits_Fbks.Started:<br>                    self.__State.Value = 2<br><br>            case 2:<br>                self.__State.Text = &#39;EXECUTE&#39;<br><br>                if self.iCmd.Complete:<br>                    self.__State.Value = 12  # Completing<br><br>                if self.iCmd.Hold:<br>                    self.__State.Value = 15  # Holding<br><br>                if self.iCmd.Suspend:<br>                    self.__State.Value = 9  # Suspending<br><br>            case 4:<br>                self.__State.Text = &#39;STOPPING&#39;<br><br>                if self.iUnits_Fbks.Stopped:<br>                    self.__State.Value = 5<br><br>            case 5:<br>                self.__State.Text = &#39;STOPPED&#39;<br><br>                if self.iCmd.Reset and not self.iCmd.Stop:<br>                    self.__State.Value = 8  # resetting<br><br>            case 6:<br>                self.__State.Text = &#39;ABORTING&#39;<br><br>                if self.iUnits_Fbks.Aborted:<br>                    self.__State.Value = 7<br><br>            case 7:<br>                self.__State.Text = &#39;ABORTED&#39;<br><br>                if self.iCmd.Reset and not self.iCmd.Abort:<br>                    self.__State.Value = 8  # resetting<br><br>            case 8:<br>                self.__State.Text = &#39;RESETTING&#39;<br><br>                if self.iUnits_Fbks.Resetted:<br>                    self.__State.Value = 0  # idle<br><br>            ## Suspending<br><br>            case 9:<br>                self.__State.Text = &#39;SUSPENDING&#39;<br><br>                if self.iUnits_Fbks.Suspended:<br>                    self.__State.Value = 10<br><br>            case 10:<br>                self.__State.Text = &#39;SUSPENDED&#39;<br><br>                if self.iCmd.Start:<br>                    self.__State.Value = 11<br><br>            case 11:<br>                self.__State.Text = &#39;UNSUSPEND&#39;<br><br>                if self.iUnits_Fbks.Unspended:<br>                    self.__State.Value = 2  # Execute<br><br>            ## Complete<br><br>            case 12:<br>                self.__State.Text = &#39;COMPLETING&#39;<br><br>                if self.iUnits_Fbks.Completed:<br>                    self.__State.Value = 12<br><br>            case 13:<br>                self.__State.Text = &#39;COMPLETE&#39;<br><br>                if self.iCmd.Reset:<br>                    self.__State.Value = 8  # Resetting<br><br>            ## Hold<br>            case 14:<br>                self.__State.Text = &#39;HOLDING&#39;<br><br>                if self.iUnits_Fbks.Holded:<br>                    self.__State.Value = 14<br><br>            case 15:<br>                self.__State.Text = &#39;HELD&#39;<br><br>                if self.iCmd.Unhold:<br>                    self.__State.Value = 15<br><br>            case 16:<br>                self.__State.Text = &#39;UNHOLDING&#39;<br><br>                if self.iUnits_Fbks.Unholded:<br>                    self.__State.Value = 2  # Execute<br><br>        # Output<br>        self.oActual_State.Value = self.__State.Value<br>        self.oActual_State.Text = self.__State.Text<br><br>        self.oInCycle = (self.__State.Value == 0) or \<br>                        (self.__State.Value == 1) or \<br>                        (self.__State.Value == 2) or \<br>                        (self.__State.Value == 3) or \<br>                        (self.__State.Value == 9) or \<br>                        (self.__State.Value == 10) or \<br>                        (self.__State.Value == 11) or \<br>                        (self.__State.Value == 12) or \<br>                        (self.__State.Value == 13) or \<br>                        (self.__State.Value == 14) or \<br>                        (self.__State.Value == 15) or \<br>                        (self.__State.Value == 16)<br><br>        self.oInStopped = (self.__State.Value == 4) or \<br>                          (self.__State.Value == 5)<br><br>        self.oInAborted = (self.__State.Value == 6) or \<br>                          (self.__State.Value == 7)</pre><h4>Units</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*YOMhHZCTtQ7pumkIld-5vg.jpeg" /></figure><p>Each Unit must handle the following data structures:</p><ul><li><strong>Requests:</strong> variable of type ST_REQUESTS, used as input to receive requests from the <strong>Machine</strong>. These requests mainly concern <strong>OMAC</strong> state changes.</li><li><strong>Fbks:</strong> variable of type ST_UNITS_FDKs, used to send <strong>feedback </strong>to the <strong>Machine</strong>.</li></ul><p>Again, as methods we will have <em>init</em> and <em>cycle</em>. In cycle we are going to manage the Unit state machine.</p><ul><li><strong>Cycle implementation</strong></li></ul><p>A possible implementation of the cyclemethod is presented below. As can be seen, the state of the unit follows the state of the Machine. Again, in each transition state Fbks are sent to the Machine. The latter are reset either in the corresponding finite state (e.g. <em>self.oFdks.Stopped</em> is set to True in Stopping while to False in Stopped) and in the Resetting state (so as soon as the Machine enters or InCycle).</p><pre>def cycle(self):<br><br>        self.__State.Value = self.iRequests.State<br><br>        match self.__State.Value:<br><br>            case 0:<br>                self.oFdks.Resetted = False<br>                self.__State.Text = &#39;IDLE&#39;<br><br>            case 1:<br>                self.__State.Text = &#39;STARTING&#39;<br><br>                self.oFdks.Started = True<br><br>            case 2:<br>                self.oFdks.Started = False<br>                self.__State.Text = &#39;EXECUTE&#39;<br><br>            case 3:<br>                self.__State.Text = &#39;COMPLETE&#39;<br><br>                self.oFdks.Completed = True<br><br>            case 4:<br>                self.__State.Text = &#39;STOPPING&#39;<br><br>                self.oFdks.Stopped = True<br><br>            case 5:<br>                self.oFdks.Stopped = False<br>                self.__State.Text = &#39;STOPPED&#39;<br><br>            case 6:<br>                self.__State.Text = &#39;ABORTING&#39;<br><br>                self.oFdks.Aborted = True<br><br>            case 7:<br>                self.oFdks.Aborted = False<br>                self.__State.Text = &#39;ABORTED&#39;<br><br>            case 8:<br>                self.__State.Text = &#39;RESETTING&#39;<br><br>                self.oFdks.Started   = False<br>                self.oFdks.Suspended = False<br>                self.oFdks.Unspended = False<br>                self.oFdks.Holded    = False<br>                self.oFdks.Unholded  = False<br>                self.oFdks.Completed = False<br>                self.oFdks.Stopped = False<br><br>                self.oFdks.Resetted = True<br><br>        ##Suspending<br>            case 9:<br>                self.__State.Text = &#39;SUSPENDING&#39;<br><br>                self.oFdks.Suspended = True<br><br>            case 10:<br>                self.oFdks.Suspended = False<br>                self.__State.Text = &#39;SUSPENDED&#39;<br><br>            case 11:<br>                self.__State.Text = &#39;UNSUSPEND&#39;<br><br>                self.oFdks.Unspended = True<br><br>        ## Complete<br><br>            case 12:<br>                self.__State.Text = &#39;COMPLETING&#39;<br><br>                self.oFdks.Completed = True<br><br>            case 13:<br>                self.__State.Text = &#39;COMPLETE&#39;<br>                self.oFdks.Completed = False<br><br>        ## Hold<br>            case 14:<br>                self.__State.Text = &#39;HOLDING&#39;<br><br>                self.oFdks.Holded = True<br><br>            case 15:<br>                self.__State.Text = &#39;HELD&#39;<br>                self.oFdks.Holded = False<br><br>            case 16:<br>                self.__State.Text = &#39;UNHOLDING&#39;<br><br>                self.oFdks.Unholded = False<br><br>        # Output<br>        self.oActual_State.Value = self.__State.Value<br>        self.oActual_State.Text = self.__State.Text</pre><p><strong>3.2 Exchange of signals between Units</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*qXqPGukQaauGmSMPCG2-Iw.jpeg" /></figure><p>At this point it is necessary to define a class that handles the <strong>exchange of signals</strong> between the <strong>Machine</strong> and its <strong>Units</strong>. This mechanism takes place within the Program, specifically in the methcyclemethod. Here two directions of communication will be handled:</p><ol><li><strong>From the Units to the Machine:</strong></li></ol><ul><li>The <strong>feedback</strong> that the units return will be read.</li><li>These feedbacks <strong>are evaluated with AND-type logic</strong>: for example, in order for the machine to exit the Abortingstate, it is necessary that <strong>all</strong> the units have successfully finished their Aborting phase by setting the variable .oFbks.Abortedto True.</li></ul><p>2. <strong>From Machine to Units:</strong></p><ul><li>The OMAC status to be executed will be sent</li></ul><p>Obviously, we are also going to handle the Start, Stop, Abort, Reset and Suspend commands here. In particular, for the <strong>Stop</strong> and <strong>Abort </strong>commands, it is possible — as anticipated — to include in <strong>OR</strong> logic also any <strong>error conditions coming from the machine automation</strong>, such as faults in <em>motors</em>, <em>valves</em>, or other devices. In this way, the machine can react not only to manual commands given by the operator, but also in case of automatically detected faults.</p><pre>def cycle(self, signals : IO_Signals):<br><br>      #Cmd<br>      #Set the commands to Machine<br>      self.machine.iCmd.Start = signals.start<br>      self.machine.iCmd.Stop  = signals.stop #or sensor.error<br>      self.machine.iCmd.Abort = signals.emergency #or motor.error<br>      self.machine.iCmd.Reset = signals.reset<br>      self.machine.iCmd.Suspend = signals.suspend<br><br>      self.machine.iCmd.Complete = False #Conditions for complete<br>      self.machine.iCmd.Hold     = False #Conditions for Hold<br>      self.machine.iCmd.Unhold   = False #Conditions for Unhold<br><br>      #Fbks<br>      #From Units to Machine<br>      self.machine.iUnits_Fbks.Started   = self.unit1.oFdks.Started   and self.unit2.oFdks.Started<br>      self.machine.iUnits_Fbks.Aborted   = self.unit1.oFdks.Aborted   and self.unit2.oFdks.Aborted<br>      self.machine.iUnits_Fbks.Stopped   = self.unit1.oFdks.Stopped   and self.unit2.oFdks.Stopped<br>      self.machine.iUnits_Fbks.Resetted  = self.unit1.oFdks.Resetted  and self.unit2.oFdks.Resetted<br><br>      self.machine.iUnits_Fbks.Completed = self.unit1.oFdks.Completed and self.unit2.oFdks.Completed<br>      self.machine.iUnits_Fbks.Suspended = self.unit1.oFdks.Suspended and self.unit2.oFdks.Suspended<br>      self.machine.iUnits_Fbks.Unspended = self.unit1.oFdks.Unspended and self.unit2.oFdks.Unspended<br>      self.machine.iUnits_Fbks.Holded    = self.unit1.oFdks.Holded    and self.unit2.oFdks.Holded<br>      self.machine.iUnits_Fbks.Unholded  = self.unit1.oFdks.Unholded  and self.unit2.oFdks.Unholded<br>      self.machine.cycle()<br><br>      #Units<br>      #From Machine to Units<br>      self.unit1.iRequests.State = self.machine.oActual_State.Value<br>      self.unit1.cycle() #Invoke Cycle of unit<br><br>      self.unit2.iRequests.State = self.machine.oActual_State.Value<br>      self.unit2.cycle()</pre><p><strong>4. Conclusions</strong></p><p>In conclusion, we have seen how to program a system according to the PackML standard, analyzing its most relevant aspects for industrial automation. PackML is distinguished by its ability to provide <strong>centralized supervision</strong> through SCADA (Supervisory Control and Data Acquisition) or HMI (Human-Machine Interface) systems.</p><p>By defining standardized <strong>states and transitions</strong>, the operational status of each machine can be collected and monitored in real time from a centralized point. This allows operators not only to check whether a machine is running, in alarm, or stopped, but also to take direct action to change its state, such as starting it, stopping it, or handling any errors.</p><p>Another key element is <strong>interoperability between machines</strong> from different manufacturers, made possible precisely by standardization. By adopting a common set of rules and behaviors, machines can be easily integrated into complex systems without the need for costly customizations. This simplifies integration and improves operational efficiency, making PackML a strategic solution for modern production line management.</p><p><strong>References</strong></p><p>[1] <a href="https://www.omac.org/">Omac.org</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/PackML">PackML</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25998a907a57" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/packml-towards-smarter-automation-25998a907a57">PackML: towards smarter automation</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vanishing gradient in Deep Neural Network]]></title>
            <link>https://medium.com/data-science/vanishing-gradient-in-deep-neural-network-83953217c59f?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/83953217c59f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[sigmoid]]></category>
            <category><![CDATA[relu]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Sat, 25 Sep 2021 17:40:08 GMT</pubDate>
            <atom:updated>2021-09-25T17:40:08.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPRCy47L5K2T9DD6" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Vanishing gradient in Deep Neural Networks</h3><h4>Causes and possible solutions</h4><p>Nowadays, the networks used for image analysis are made by many layers stacked one after the other to form so-called <em>deep networks</em>. One of the biggest problems in training these architectures is the <strong>vanishing gradient:</strong> the gradient assumes a null or asymptotic value at zero, preventing the weights from being updated.</p><p>In this article we will analyse analytically causes of this phenomenon, proposing a first possible solution and leaving more details for further techniques in a later article. Before starting, the examples that will be covered will be elementary to make the treatment easier. Obviously, the same concepts can be applied to more complex architectures.</p><h3>Notation</h3><ul><li><strong>w:</strong><em> </em>weight</li><li><strong><em>z:</em></strong> linear sum of neuron inputs</li><li><strong><em>g:</em> </strong>activation function</li><li><strong><em>a</em></strong><em>: </em>output of the activation function</li><li><strong><em>apex</em></strong>: layer <em>l-</em>th</li><li><strong>L:</strong> loss function</li></ul><h3>1. What is the vanishing gradient?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTPhh99OZ-J6p5OdEeiLiA.png" /><figcaption>Fig.1: The figure shows the features maps obtained at different layers of the FCNN VGG-16 network (Source: Image by me)</figcaption></figure><p>In a deep convolutional network the layers near the input extract<strong> spatial features </strong>from the image: <em>orientation</em> of the contours, presence of <em>angles</em>, presence of <em>textures</em>, <em>color</em> information. Approaching the output layer, <strong>semantic features</strong> will be extracted: presence of <em>mouth</em>, <em>nose</em> ando so on. An example is shown in Fig.1, where there are some feature maps extracted at different layers of VGG-16. In general, by increasing the depth of the network each layers will be able to learn how to extract more <em>general </em>and <em>complex features</em>.</p><p>Deep networks, however, are difficult to train. A problem that we could see is <strong>vanishing gradient</strong>. During the backward pass, the weights of the layers near the input remain constant or update very slowly as opposed to what happens for the layers close to the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NSbQSCtG47GiMS8T.jpeg" /><figcaption>Fig.2: Plain Network with three neurons (Source: Image by me)</figcaption></figure><p>Let us consider the succession of neurons in Fig. 2. We update the weight w^(1) by calculating the derivative of Loss function respect to it. For simplicity, we assume that the bias term <em>b</em> is zero for each neuron. Applying the <em>chain rule</em> [1] and grouping the derivatives of the activation functions we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*mwtSz5iczzrxZnYf.png" /></figure><p>Let’s ask, what can stop or slow down the gradient? We analyze the product ∂<em>a</em> /∂z.</p><p><strong>Case 1:</strong> Suppose that only the <em>i-th</em> is null at each iteration (<em>for example</em> ∂<em>a^(2)</em>/∂z^(2)). In this case, ∂L /∂w^(1) will take on a null value preventing the updating of w^(1) which will remain <strong>constant</strong>. In fact, applying <em>delta rule </em>[2]<em> </em>we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*_u8QKybKWErhknoNF259Pg.png" /></figure><p><strong>Case 2: </strong>Suppose now that each term ∂<em>a</em>^(i)/∂z^(i) has asymptotic zero values at each iteration. In this way, ∂L /∂w^(1) will also be asymptotic at zero and w^(1) will update <strong>very slowly</strong> (<em>we add values close to zero each time</em>). Applying <em>delta rule</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*VuH6B4ycsyHDQsyflBGQ7g.png" /></figure><h3>2. Activation functions with limited output range</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*w0RTVNG2Ep1URuQg35vQBw.png" /><figcaption>Fig.3: The sigmoid function with codomain [0,1] is represented in blue. Its derivative is represented in red. The value of input z is represented on the abscissa axis while the value of the corresponding derivative is represented on the ordinate axis (Source: Image by me)</figcaption></figure><p>From the examples in the previous paragraph, we understand how the choice of the activation function<em> g</em> plays an important role. One of the main causes of the vanishing gradient is due to the use of <em>activation functions</em> with <em>limited output range:</em></p><ul><li>the derivatives ∂<em>a</em>/∂z will be non-zero <strong>only </strong>for input values<em> z </em>that fall within the <em>region of significance</em></li><li>in the region of significance the derivatives assume relatively <strong>small values</strong>. Considering a large number of layers and multiplying the values <em>∂a/∂z</em> we could slow down the gradient</li></ul><p>The two points perfectly reflect what has been said for Case 1 and Case 2. Let us analyze them by considering the sigmoid (σ), shown in Fig.3, as a limited output range activation function. Considering the derivative<em>, </em>the<em> significance region</em> occurs for input values <em>z</em> falling in the interval [-4.4]. For values outside this interval the derivative will be zero<em> (Case 1).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bbTyQgE8iomsDC5B.png" /><figcaption>Fig. 4: Plain Network with K number of neurons (Source: Image by me)</figcaption></figure><p>Now suppose we have a network with K layers in which, for each neuron, <em>z</em> takes value in the region of significance. Calculating the gradient respect to layers K, K-1, K-2 and 1 we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SQK8C8Uic58I0Mhb.jpeg" /></figure><p>By multiplying the red values, we notice how as we move away from the output layer K the product ∂<em>a</em>/ ∂z decreases. If <em>K</em> were equal to 50 layers we will have the <em>Case 2</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*F06OQvuHvsa71Qyg.png" /></figure><h3>3. Rectified Linear Units (ReLU)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*m5IGMCavn1qE3G0XejMdHg.png" /><figcaption>Fig.5: The ReLU function with codomain [0,+inf] is represented in blue. Its derivative is represented in red. The value of input z is represented on the abscissa axis while the value of the corresponding derivative is represented on the ordinate (Source: Image by me)</figcaption></figure><p>The ReLU activation function, shown in Fig. 5, can be formalised by <em>max(0, z). </em>This<em> </em>contributed to the resolution (<em>at least in part)</em> of the vanishing gradient. Observing the derivative in Fig. 6 we notice how for the values of <em>z</em> in R^+ the derivative is unitary thus allowing the passage of the gradient. Problems arise when the input value is negative thus obtaining <em>Case 1</em>. There are variants of Rectified Linear Units such as LeakyReLU and ELU created to mitigate the problem of the null derivative for <em>z</em> &lt; 0.</p><h3>Conclusion</h3><p>Training networks with a large number of layers is not easy. In this article we explored the <em>vanishing gradient </em>problem<em> </em>identifying a possible cause in the choice of activation functions. A proposed solution is the use of Rectified Linear Units which, for positive values, does not obstacle the passage of the gradient. But… ReLU does not completely solve the problem. Another problem is <strong>initialization of the weights. </strong>What would happen if the derivative ∂z /∂<em>a </em>were zero or close to zero for multiple layers? The considerations and examples just discussed for activation functions can be repeated to answer the question.</p><p>If on the one hand, we have the<em> vanishing</em> <em>gradient</em>, on the other we must consider the exact opposite problem, the <em>Exploding gradient</em>: the gradient takes on a high value thus preventing optimization.</p><p>An important contribution to the training of deep networks came with the introduction of <strong>skip connections </strong>which we will discuss in another article<strong>.</strong></p><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Chain_rule">Differential calculus: Chain Rule</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Delta_rule">Gradient descent learning rule: Delta Rule</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83953217c59f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/vanishing-gradient-in-deep-neural-network-83953217c59f">Vanishing gradient in Deep Neural Network</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image derivative]]></title>
            <link>https://medium.com/data-science/image-derivative-8a07a4118550?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a07a4118550</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[edge-detection]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[sobel-filter]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 14:02:01 GMT</pubDate>
            <atom:updated>2021-06-08T19:01:25.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*gsvUL5XMfgwo-JcLWyRGXw.png" /><figcaption>Photo by source <a href="https://www.instagram.com/p/BrxcygVFiNI/">link</a>, edited with permission by the author</figcaption></figure><h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Analysis of the first derivative of an image</h4><p>In a convolutional network, the layers near to the input are used to extract spatial features. This behavior is inspired by what happens in human visual system when we are called to recognize an object. The first information that our brain decodes is the shape, the color, the presence of textures, the orientation of the light and the edges. We extract general information from the world which, as we process it, will allow us to obtain more and more abstract information to recognize the object.</p><p>In this article, we will focus on edge detection or rather the calculus of the image first derivative, taking a look at the differences between the continuous and discrete worlds. Finally, we will analyze the convolution process through two derivation operators and highlighting their advantages and disadvantages.</p><h3>1. Notions of continuous differential calculus</h3><p>Mathematically, the derivative expresses the <strong>rate of local variability </strong>of a function with respect to a direction of development. About that let us consider a signal<em> f </em>: ℝ→ ℝ with only one direction of development <em>x</em>, and let <em>xi</em> be a point in its domain. The information we want to obtain is whether the signal f, at the working point <em>xi</em> (<em>local variability</em>), undergoes a variation (<em>increases or decreases</em>) or remains constant. The idea could be to study the around of the working point or better: (i) evaluate <em>f</em> in <em>xi</em> (ii) evaluate <em>f</em> in<em> xi </em>plus an infinitesimal quantity <em>epsilon </em>(iii) calculate a difference between the two. This is what happens in the calculation of the first derivative which we can formalize with Formula (1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*cau0B_Y73tuBraT4hUg6PA.png" /><figcaption>Formula (1)</figcaption></figure><blockquote>A function f is derivable at a working point xi if the limit of the incremental ratio of the function exists and is finite, as the epsilon increment of the independent variable tends to zero.</blockquote><p><strong>Multidimensional</strong> functions assume particular importance for the following discussion. Let <em>f </em>: ℝ^n → ℝ be a scalar field defined on <em>n</em> directions of development, the calculation of the derivative is done by considering the <strong>partial first derivatives</strong>, or rather the derivatives with respect to each of the <em>n</em> directions. The latter constitute the <strong>gradient</strong> ∇(<em>f</em>) : ℝ^n → ℝ³, a vector field that associates to <strong>each <em>n</em>-dimensional point</strong> of the scalar field a vector. The gradient provides three important pieces of information for each point. The first, the <em>modulus</em>, expresses the amount of variation of the function<em> f</em> around the working point, the second is the <em>versus </em>of growth of the function at the calculation point, and the third is the <em>direction</em>, orthogonal to the contour lines of the scalar field. A graphical representation can be found in Fig.1 in which the scalar field <em>f(x,y) </em>= <em>x</em>²+<em>y</em>² in ℝ² is considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ScTg2IUT677I0ezp.gif" /><figcaption>Fig. 1: (a) shows calculus of the gradient vector ∇f(xi,yj) for a point (xi,yj) taken on the C1 level curve of the function f(x,y) = x²+y². We note that the modulus of the gradient vector at this point is given by the sum (PitagoraTheorem) of the variation along x and y, while the direction is given by calculating the angle θ. The versus, on the other hand, depends on the maximum variation of f (in this case towards the outside of the curve). In (b) we show the construction of the vector field ∇f of the function f(x,y) = x²+y². We note how the gradient vectors, computed this time at different points on the level curves, tend to be larger (higher modulus) as we grow along x and y. This is because, since the gradient modulus is higher than the modulus of the gradient, the gradient vectors tend to be larger. <br>This is because, since the magnitude of the gradient in a point is the amount of variation, the more the values ​​of x and y increase, the greater the variation of f. (Source: Image by me)</figcaption></figure><h3>2. Edge detection</h3><p>Let I[x,y] be our image in two directions of development, x (<em>width</em>) and y (<em>height</em>) respectively. We define an edge as a region of I[x,y] in which there is a <strong>change of color intensity</strong> Fig.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*vsfJdMdbMi6_K4VwdlXjeg.png" /><figcaption>Fig.2. Representation of the three types of edge we can find in image analysis (Image by me, inspired by source <a href="http://vision.stanford.edu/teaching/cs131_fall1718/files/05_edges.pdf">link</a> pg.90)</figcaption></figure><p><em>Edge detection</em> aims to highlight this variation by calculating the <em>gradient of the image</em>. As we know, the gradient is made up of partial first derivatives. Their formalization, as presented in section 1, is valid in the continuous world. An image, on the other hand, is a discrete <strong>multidimensional signal</strong>.</p><p><strong>2.1 Discrete partial derivative</strong></p><p>The feature of <em>discrete multidimensionality</em> involves an approximation of the <strong>continuous partial first derivative</strong> by a <strong>finite difference</strong>, where the epsilon increment does not tend to cancel (ϵ → 0) but takes on a finite value. In the case of our discrete signal I[x,y] the value of the increment is equal to one pixel. <strong>The smallest quantity</strong> for which, given the pixel [<em>xm,yn</em>], we can move around it to assess the local rate of variability is precisely the pixel. Formalizing, we can distinguish three types of finite differences: (<em>a</em>)Forward (b)Backward (c)Central.</p><p>One of the most well-known operations, when we talk about images, is <em>convolution</em>. Given a matrix K (<em>Kernel</em>), the <strong>convolution</strong> makes K slide by a certain <strong>stride</strong> along with the height and width of the image I, performing a weighted sum between the values of the Kernel and the overlapping region of the image. This technique, through an appropriate Kernel transformation, is what we use to apply finite differences on the images by <strong>calculating the partial first derivative</strong> in the two directions of development. A summary and formalization of what has just been said is presented in Tab.1. In the field of <em>computer vision</em> and in particular for <em>edge detection</em>, Central or also called <strong>symmetric differentiation</strong> is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRHNrILWvKug8ICzwyK5xQ.png" /><figcaption>Tab.1: Formalization of the three types of finite differences, Forward, Backward and Central in the development directions x and y and the two-dimensional working point [xm,yn]. To each is associated the corresponding representation through Kernel of dimension 1x3 for the development direction x and 3x1 for the development direction y. (Source: Image by me)</figcaption></figure><p><strong>2.2 Discrete gradient</strong></p><p>The convolution produces a new image, called a <em>features map (F)</em>, having the same dimensions in terms of height and width as I (<strong>stride = 1 and padding = ‘same’</strong>) and in which specific features of I are emphasized. As an example, if we calculate the convolution between I[x,y] and Kx (<em>Kernel of derivation with respect to x</em>), the result will be a new image Fx in which the <em>vertical edges</em> will have a non-zero intensity value to the detriment of the horizontal <em>edges.</em> In particular, we can say that:</p><blockquote>the<strong> intensity value</strong> of the pixel Fx[xm,yn] corresponds to the <strong>value</strong> of the <strong>partial first derivative</strong> at the point I[xm,yn].</blockquote><p>The same analysis can be carried out by considering Ky (<em>derivation kernel with respect to y</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*mzXSAyRX8s8Qm7gitQuY9g.png" /><figcaption>Fig.3: Calculation of the modulus and direction of the gradient using the image I[x,y] as a discrete signal. (Source: Image by me)</figcaption></figure><p>Once the values of the partial derivatives have been obtained, we can calculate the <strong>gradient G</strong>. The latter will associate to each pixel I[xm,yn] the information on the <em>modulus</em>, which will indicate the quantity or magnitude of variation of the image around [xm,yn] and on the <em>direction</em>, which will express the <strong>direction of growt</strong>h <strong>of the color intensity</strong> around the pixel of interest. Fig.3 shows a geometric representation of what has been said. Since we are in the discrete world, a more correct representation can be found in Fig.4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyRzbCBlY689fof-0DaFYQ.png" /><figcaption>Fig.4: (a) shows the image I[x,y] with two edges in the respective directions of development. (b) shows Fx = I*Kx, or rather, the derivative of (a) with respect to x. We note how the vertical edges are highlighted with respect to the horizontal ones. In (c), Fy = I*Ky, or rather, the derivative with respect to y is represented. The behavior, in this case, is opposite to what we saw in (b). Figures (d), (e), (f) report information about the gradient. In particular, for (d) we have the Pitagora sum of the derivatives Fx and Fy. The result is the magnitude or modulus |G[x,y]|. In (e) and (f) the direction of growth of the gradient is represented. As we can see, (e) shows the expected direction of the gradient for each pixel on the edge. The latter is directed to indicate<strong> the growth of the color intensity </strong>around the pixel of interest, in this case from a color intensity of 0 to 255. We can represent this information through an image (f). The angle θ, which indicates the orientation of the gradient, considers a reference system with the pixel in the top left corner as the intersection point of the Cartesian axes and the y-axis in the opposite direction to the standard one. (Source: Image by me)</figcaption></figure><p>For completeness of discussion, the code used to obtain the examples in Fig.5 is presented below. As can be seen, both Kx and Ky are premultiplied by the value -1. More details can be found in Appendix 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aebce8cfb1594ddc1ab7b7b9ecc09be3/href">https://medium.com/media/aebce8cfb1594ddc1ab7b7b9ecc09be3/href</a></iframe><h3>3. Noise</h3><p>An image may present <strong>random variations in color intensity.</strong> This phenomenon is called <strong>digital noise</strong> and occurs especially in low light situations, at high ISO values or in other cases, can be introduced by the sensor itself (<em>ex</em>: CMOS). For edge detection, <strong>noise can cancel the presence of the edge</strong>.</p><p>In this regard, let us consider our image I[x,y] with the addition of noise (in this case <em>salt-and-pepper noise</em>) and plot the intensity histogram (Tab.2). We notice that compared to the case with no noise, the curve is much more undulatory, presenting several peaks called <em>false edges</em>. The derivative will highlight each of them, losing the information on the <em>true edges</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81rOs4W6g7lLD_u5l6LX2Q.png" /><figcaption>Tab.2: Comparison of derivatives calculated on the same image I[x,y] with and without the presence of salt-and-pepper noise (Source: Image by me)</figcaption></figure><p>One way to reduce <em>false edges </em>is to blur the image. The type and amount of blurring depends on the intensity of the noise. Some image blurring techniques combined with the Kx and Ky <em>derivative Kernels</em> are presented below.</p><p><strong>3.1 Blurring with moving average: Prewitt operator</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*-vSi4apFHJVm4-UeqFQAxw.png" /><figcaption>Fig.5: Prewitt operator for identifying vertical edges (Source: Image by me)</figcaption></figure><p><strong>Prewitt’s operator</strong>, as we can see from Fig. 5, consists of several symmetrical derivative Kernels of size 1x3 stacked on top of each other. In particular, it can be decomposed through a matrix product between a three-pixel moving <em>average Kernel</em> and a <em>derivative Kernel.</em> In the literature, we can find this operator premultiplied by 1/9 instead of 1/3. In this case, we are going to perform the <em>average</em> considering all the pixels of the 3x3 derivative Kernel, thus decreasing the amount of noise. The same considerations can be made for the derivative kernel along the y direction.</p><p><strong>3.2 Blurring with a Gaussian filter: Sobel operator</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*-blp9ofkM2z_YG750XQbBA.png" /><figcaption>Fig.6: Sobel operator for vertical edge identification (Source: Image by me)</figcaption></figure><p>The <strong>Sobel operator</strong> is obtained by calculating the derivative of the Gaussian filter. In particular, it can be decomposed through the matrix product between the <em>discrete Gaussian filter</em> and the <em>derivative Kernel</em>. An example of the Sobel operator along x of size 3x3 is presented in Fig.6. The same considerations can be made for the derivative Kernel along the y-direction.</p><h3>4. Problems due to derived kernels</h3><p>Suppose we have a <em>step edge</em> in our image. Applying a <em>derivative Kernel</em>, in particular <em>Central</em>, the edge is represented by a minimum of two pixels. The number of pixels increases if we have a <em>ramp</em> or a <em>root edge</em>. The same phenomenon can be caused not only by the nature of the edge itself but also and above all by the blurring of the image, so using the Sobel and Prewitt operators.</p><p>Again, as mentioned in the previous section, the presence of noise can lead to the loss of edge information and the identification of <em>false edges</em>. Blurring can reduce this phenomenon but not definitively eliminate it. An example is presented in Fig.7, where <em>false edges</em> are still present after a blurring process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*IBaZ3GrBQFfVMyEW_i2qOw.png" /><figcaption>Fig.7: Identification of false edges following a blurring and derivation process carried out with the Sobel operator applied to the image Fig.4 (a) to which a salt-and-pepper noise and a binary thresholding process were added (Source: Image by me)</figcaption></figure><p>These effects can be reduced by using<em> Canny,</em> an edge detector that applies non-maximum suppression and an edge linking process to the result obtained by the Sobel operator, reducing the thickness of the edges and the presence of false positives respectively.</p><h3>Appendix</h3><ol><li><strong>Compute |G[xm,yn]|</strong></li></ol><p>As anticipated in paragraph 2.2, the calculation of the gradient modulus is carried out considering the Pitagora sum between the values of the derivatives with respect to the <em>x </em>and <em>y </em>development directions. The latter could be expensive in computational terms if we think that it has to be applied on 25/30 <em>fps</em> (<em>frames per second</em>) unless subsampling. To lighten the computational load, the modulus of the gradient can be approximated using Formula (2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7El6BH6AGQrBFvpWKvuLg.png" /><figcaption>Formula (2)</figcaption></figure><p><strong>2. Convolution</strong></p><p>In the continuous world, the convolution between two signals <em>f(t)</em> and <em>g(t)</em> results in (i) expressing both functions in a supporting variable (<em>e.g.</em> τ), (ii) assuming that it is g(τ) that is sliding along the new direction, flip the function <em>g</em> with respect to its y-axis (<em>g</em>(-τ)) (iii) adding a variable t to allow sliding (g(t-τ)). (iv) at this point the integral of<em> f</em>(τ) g(t-τ) in dτ [3][4] is calculated.</p><p>The <em>convolve()</em> method of the <em>scipy.ndimage</em> library implements this. So, for the Kernels <em>Kx</em> and <em>Ky</em> to be calculated correctly we need to premultiply them by -1. At this point, applying the <em>convolve()</em> method, and in particular point (<em>ii</em>), we have the correct filter values (Tab.3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ey48Nll4yr0NYPTHtZQk_Q.png" /><figcaption>Tab.3: Representation of derivative Kernels following flip and execution of the scipy.ndimage.convolve() method. (Source: Image by me)</figcaption></figure><p>Not inverting the derivative Kernels and performing the convolution will result in misreading the information for both the derivative value and the direction of the gradient. The modulus of the gradient is not affected as it is formed by positive sums. An example is shown in Fig.8. As we can see, for the left edge where we have a transition from an intensity value of 255 to 0 we expect a negative derivative, but we get a growth value. The same considerations can be made for the right edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*SGL5JEcyVsiDN-B9WIPPJg.png" /><figcaption>Fig.8: Representation of derivative calculation without flip of the derivative Kernel Kx. (Source: Image by me)</figcaption></figure><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Derivative">Derivative — Wikipedia</a></p><p>[2] <a href="http://vision.stanford.edu/teaching/cs131_fall1718/files/05_edges.pdf">Lecture 5: Edge Detection — Stanford University</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Convolution#Definition">Convolution: Definition — Wikipedia</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/File:Convolution3.svg">Convolution: Example — Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a07a4118550" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-derivative-8a07a4118550">Image derivative</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation in Fully Convolutional Networks (FCNs)]]></title>
            <link>https://medium.com/data-science/backpropagation-in-fully-convolutional-networks-fcns-1a13b75fb56a?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a13b75fb56a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 20:08:43 GMT</pubDate>
            <atom:updated>2021-02-03T20:08:43.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FAUh4b-C3kWa_Wjj" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Backpropagation is one of the most important phases during the training of neural networks. As a target, it determines the neural network’s <strong>knowledge</strong> to be understood as the ability to respond properly to future urges. The terms “knowledge” and “properly” must consider two aspects: (i) the first is given by experience, or better, by the information (<em>features</em>) that the network learns to extract from the samples of the dataset (ii) the second by the error calculus or also called <em>loss.</em> In supervised learning, each sample is labelled with a class (<em>classification</em>), with one or more values (<em>regression</em>) or both. Let <em>y_actual </em>be the label assigned to the sample by the supervisor and <em>y_pred</em> the network prediction, the backpropagation phase will ensure that the distance (<em>error</em>) between the two is acceptable. Both errors and features have <strong>weights</strong> associated with them, which when modified during backpropagation, constitute the network’s learned knowledge.</p><p>Before leaving you, I would like to add a few more notes. Backpropagation has two phases. The first one is the calculation of the gradient, or better, of the derivative of the loss function to each network’s weigths. The second is the updating of them (<em>delta rule</em>). This last one can be performed with various optimization algorithms, to name a few Momentum, Adam etc … In this paper, I will concentrate only on the first phase leaving the deepening of the second one to a successive moment. Also, I have not found much evidence on backpropagation applied to convolutional networks and every calculation and interpretation is the result of personal studies. In case of errors or misinterpretations, I would be happy to discuss. Thank you and good reading.</p><h3><strong>Notation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*OmTURPwoTYVnPp5UhQz7Mg.png" /></figure><h3>1. Kernel and convolution</h3><p>One of the questions we might ask is why use a Convolutional Neural Network instead of MLPs to analyze images? Let’s take some example. An image is a sequence of values (<em>pixel intensities</em>) arranged in a matrix. To use an MLPs we should transform the matrix into a vector and present it to the input layer of the network. In this regard, we consider an image X of size (224,224,3) where 224 indicates the height and width while 3 is the depth in colour scale Red, Green, Blue. By transforming it we get a vector of size (150,528, 1) as shown in Fig.4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hu4wsDcxIhcGBC-lxsuvaQ.png" /><figcaption>Fig.4: Representation of a Multi-Layer Perceptrons (MLPs) with input an image X. (Photo by source <a href="https://www.instagram.com/p/Bsl5-0XhJL4/">link</a>, edited with permission by the author)</figcaption></figure><p>There are mainly two errors in this approach. The first is that <strong>the images are spatially ordered data</strong>. To be more clear, the order in which the pixels are arranged to form the matrix provides a great help in features extraction. So it is information that we cannot lose. The second is that using a MLPs<strong> the number of parameters is very high</strong>. Taking our example, there would be 150,528 neurons only for the input layer. Considering 100.000 neurons in the second layer, our network would have 150,528x100,000 = 15,052,800,000 parameters only between the first and second layer, let’s imagine considering the whole network. <em>(Note: more the number of parameters increases, more the training will require time, more it will be difficult to find the optimal, more the model has a greater weight in terms of memory</em>)<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJHjlP9goOT2x3QvRSxmfA.gif" /><figcaption>Fig. 5: Convolution between the image X of dimensions (4,4,1) and the Kernel W of dimensions (2,2) with stride S = [1,1]. The output feature map is denoted by Z and has dimensions (2,2) (Source: Image by me)</figcaption></figure><p>The introduction of the Kernel solves these problems. A Kernel <em>W</em> is a square matrix usually of dimension 2x2, 3x3 or 5x5 that runs by a certain stride S along the width M and the height N of the image X, performing a weighted sum between the values<em> ​​w</em> (<em>weights</em>) of the Kernel and the overlap region. This operation, called <strong>convolution</strong>, considers the spatial order of the pixels and allow a<strong> sharing of weight</strong> <em>w</em> with the pixels of the image, reducing the number of parameters. An example of convolution is shown in Fig.5. The output Z is a <strong>feature map </strong>or rather<strong> </strong>a new image in which specific characteristics of X are emphasized. Assuming the Kernel <em>W</em> highlights the edges, the convolution operation produces a feature map like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4CK-V-nGZvzSDzI30AHiQ.png" /><figcaption>Fig.6: Convolution operation to emphasize the edges of the X image. Factor 1/16 is introduced to reduce noise in the feature map. (Photo by source <a href="https://www.instagram.com/p/Bsl5-0XhJL4/">link</a>, edited with permission by the author)</figcaption></figure><p>As can be seen, in both Fig.5 and Fig.6, Z does not have the same dimensions as the starting image. This effect is called <strong>stride downsampling</strong>. Assuming the dimensions are for X: (Mx, Nx) for W: (Mw, Nw) and stride S, the dimensions of the feature map Z: (Mz, Nz) are calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*skdgoBI-0Ol6L8mw.png" /><figcaption>Formula (1)</figcaption></figure><h3>2. Feed-forward</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*08VjulaTS4hB9gKp.png" /><figcaption>Fig.7: Representation of a Convolutional Neural Network with two convolutional layers (Source: Image by me)</figcaption></figure><p>Let’s consider a network with two convolutional layers, both with a Kernel W of size 2x2 and stride 1 along both the height and the width, and two neurons in the output layer. As an activation function, we do not choose one in particular, generically denote it by <em>g</em>. The input of the network is a grayscale image (<em>single channel</em>) of size 4x4x1 Fig.7.</p><p>Let’s examine the forward phase. Before starting a final note. To build the computational graph, for each pixel of the feature map, it is important to remember which pixels were used during the convolution operation. What we need is the <em>position</em> that we will save in set P.</p><ul><li><strong>Convolution Input X and Layer 1</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*Garwk4i29dvLQBRd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N_XmPWK0FUbUcVf9.png" /><figcaption>(Source: Image by me)</figcaption></figure><ul><li><strong>Convolution output Layer 1 and Layer 2</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*A_XRUDwoEqJCy1pG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O2JJTmK0seZemfoP.png" /><figcaption>(Source: Image by me)</figcaption></figure><ul><li><strong>Fully-Connected</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*_ZswP0ARV6lcZAxJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*sAdCYLQemsxZ2e7J.png" /><figcaption>(Source: Image by me)</figcaption></figure><h3>3. Computational graph</h3><p>We group the information obtained in the forward phase in a computational graph (Fig. 8). This is a representation of our Convolutional Neural Network with a graph in which each node corresponds to a single forward step. In particular, we can see that each of the convolution nodes <em>z</em> has as inputs the nodes with index in P.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gOYbryvz_gfNL8_q.png" /><figcaption>Fig.8: Computational graph’s representation of the network in Fig. 7 (Source: Image by me)</figcaption></figure><h3>4. B<strong>ackpropagation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*3cVGhzY-Fjqhj6dr.png" /><figcaption>Formula (2)</figcaption></figure><p>Let’s consider L as Loss function, the computational graph allows you to easily define the gradient vector ∇wL. This will be used by the delta rule to update the network weights. Formula (2) represents the gradient vector of the network in Fig.7. It consists of three components, also vectors, about the weights of Layer 3 and respectively to the Kernels of Layer 2 and 1. In the following, I analyze each of them using the<em> chain rule </em>to partial derivatives calculus.</p><ul><li><strong>∂L /∂W^(3) calculus</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*u3i7UdV_8C6imnnm.png" /><figcaption>Formula (3)</figcaption></figure><p>Formula (3) is the gradient vector of the weights W Layer 3. A single dependence [Appendix 1.1] must be solved to calculate its elements. As an example, the calculation of the Loss derivative to the weight w1 Layer 3 is shown in Formula (4):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*XqNq0xbzJNM0ogS8.png" /><figcaption>Formula (4)</figcaption></figure><p>Denoting by F (<em>fully</em>) the number of neurons in the last layer for each element <em>n</em> of the vector Formula (3), we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*rHQUru-1Z26MMAzO.png" /><figcaption>Formula (5)</figcaption></figure><ul><li><strong><em>∂</em>L /∂W^(2) calculus</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*j5p7yqPHNUdelKI5.png" /><figcaption>Formula (6)</figcaption></figure><p>Formula (6) is the gradient vector of the matrix W Layer 2. To calculate its elements it is necessary to solve first a single dependence due, as analyzed, to the gradient of Layer 3 and then a multiple dependence [Appendix 1.2] for each of the neurons <em>f.</em> Looking at Fig.8, we can see that (i) each weight <em>w </em>in<em> </em>Layer 2 is present in the different sums <em>zi</em>^(2) due to the shared weights characteristic of the convolution (ii) each neuron <em>f </em>is connected to each of the activation output in Layer 2 for fully connected (<em>since it is a fully connected layer</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZbVaKNeujlf_5jC4jW-Mg.gif" /><figcaption>Fig.9: Calculation of downstream gradients for each Layer 3 zf node (Source: Image by me)</figcaption></figure><p>As an example, we consider the gradient computation respect to the weight <em>w1</em> in Layer 2. For ease of discussion, for each activation node at Layer 2, we compute the <em>upstream gradient</em> obtained by summing the <em>downstream gradients</em> [Appendix 2] of the respective <em>zf</em> Layer 3 nodes. The calculation of the downstreams is shown in Fig.9, each pair is then summed to form the formalized upstream for each activation in Formula (10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xiZ_mVxmvJr4OJhR.png" /><figcaption>Formula (10)</figcaption></figure><p>At this point, the Loss gradient with respect to <em>w1</em> in Layer 2 will be given by Formula (11) in which each of the <em>∂L /∂ai</em> upstream gradient is multiplied by the derivatives of the respective <em>ai</em> and <em>zi</em> nodes. After that, each contribution is summed given step (i) described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BO6Fv7dVK-8A2oGz.png" /><figcaption>Formula (11)</figcaption></figure><p>Starting from what we have seen and generalizing, for each node <em>ai</em> in Layer 2 the upstream gradient will be given by Formula (12). The latter is the Formula (5) in which instead of deriving<em> zf</em> Layer 3 for the weight <em>w</em> we derive for the activation <em>ai</em>, going then to add the contributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*ulJuIOewz8KTcUyl.png" /><figcaption>Formula (12)</figcaption></figure><p>Instead, for each element <em>n</em> of the vector Formula (6), we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*dR1U4MuXcu_O2GNf.png" /><figcaption>Formula (13)</figcaption></figure><p>For completeness, combining Formula (12) and (13) we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yvKhPziQ6vbOkBkb.png" /></figure><ul><li><strong><em>∂</em>L /∂W^(1) calculus</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*pOSxiblAi08Y77Nl.png" /><figcaption>Formula (14)</figcaption></figure><p>Formula (14) is the gradient vector of the matrix W Layer 1. Compared to the previous case, for the computation of partial derivatives it is necessary to solve different steps of multiple dependencies depending on the fully connected and convolution layers. Looking at Fig.8 it is possible to see that (i) each weight of W^(1) is present in the different <em>zj </em>weighted sums of Layer 1 (<em>shared weights</em>).</p><p>As an example, we consider the calculation of the gradient to the weight w1 Layer 1. Again, for each activation node<em> aj</em> in Layer 1 we calculate the <em>upstream gradient</em> formalized in Formula (15). To compute it we use the information we already have. In particular, the upstream gradients in Formula (10) that once we obtain the <em>∂L /∂zi</em>^(2) will allow us to calculate the individual downstream Fig.10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DRPg8PB5fVrhkENZ.gif" /><figcaption>Fig.10: Calculation of downstream gradients for each node zi Layer 2 (Source: Image by me)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4QNno_7ez-OO5O6P.png" /><figcaption>Formula (15)</figcaption></figure><p>At this point, the Loss gradient to <em>w1</em> Layer 1 will be given by Formula (16) in which each of the <em>∂L /∂aj</em> upstream gradients, formalized in Formula (15), is multiplied by the derivatives of the respective activation nodes <em>aj</em> and <em>zj</em>. After that, each contribution is summed for point (i) described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*y9zmVcj-bi4egMGW.png" /><figcaption>Formula (16)</figcaption></figure><p>Starting from what we have seen and generalizing, for each node <em>aj</em> in Layer 1 the upstream gradient will be given by Formula (13) in which instead of deriving <em>zi</em> Layer 2 to weight <em>w</em>, we derive it to <em>aj</em> in Layer 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*uiwTSmEmBMQBbCba.png" /><figcaption>Formula (17)</figcaption></figure><p>Instead, for each element n of the vector Formula (14), we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*tlgrQayrLT1iX1QU.png" /><figcaption>Formula (18)</figcaption></figure><p>For completeness, combining Formula (12), (17) and (18) we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*riMN5fTT4QribB4v.png" /></figure><h3>5.Conclusion</h3><p>In this paper, we have explored the backpropagation phase focusing our analysis on the computational graph of the dummy network in Fig.7. In general, to compute the gradient vector of an l-th convolutional Layer it will be necessary:</p><ul><li>to calculate the upstream gradient for each activation output from layer l</li><li>sum the contributions of the derivative of z with respect to w in layer l (due to shared weights)</li></ul><p>Modern networks are much more complex. Some differences could be in the number of channels of each features map block (imagine more features maps one behind the other as a cube, each of them is a channel) with a consequent increase in the depth of the Kernel W, or we could have more than one Kernel for each layer, or we could have Batch Normalization layers and then apply backpropagation here, or have a bias term for each layer and consider a backpropagation for this term. So the one presented in this article is a simple, but hopefully explanatory example of backpropagation.</p><h3>Appendix</h3><p>In Fig.11 / 12 / 13 is analyzed as an example a node <em>z</em>, the same considerations can be made on any other function.</p><ol><li><strong>Chain rule</strong></li></ol><p>The chain rule is a derivation rule for calculating the derivatives of composite functions [1].</p><p><strong>1.1 Single dependence</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/0*MA5R-SoG_IMX-jpV.png" /><figcaption>Formula (19)</figcaption></figure><p>Let <em>a(t)</em> be a differentiable function in <em>t</em> and<em> z(a(t))</em> a differentiable function in <em>a</em>. The derivative of <em>z</em> respect to <em>t </em>is described by Formula (19). Analyzing the computational graph for the calculation of the derivative we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9mfYy8mmWNCF_qVA.png" /><figcaption>Fig.11: Representation of the derivative for the compound function z(a(t))</figcaption></figure><p><strong>1.2 Multiple dependence</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*RkRxUFJ1BNKzCl_b.png" /><figcaption>Formula (20)</figcaption></figure><p>Let <em>a1(t)</em> and <em>a2(t)</em> be differentiable functions in t and<em> z(a1(t), a2(t))</em> a differentiable function in <em>a1</em> and <em>a2</em>. The derivative of <em>z </em>to <em>t</em> is described by Formula(20). Analyzing the computational graph for the calculation of the derivative we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mdLE-DK08v_Ffm59.png" /><figcaption>Fig.12: Representation of the derivative for the compound function z(a1(t), a2(t))</figcaption></figure><p>2. <strong>Gradient </strong>[2]</p><p>Let <em>a1(.)</em> and <em>a2(.)</em> be two functions and <em>z(a1(.) , a2(.)) </em>a differentiable function in <em>a1</em> and <em>a2</em>. We define:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*9hLSCztOChSMscuj.png" /><figcaption>Fig.13: Representation of different gradient shapes on a single node</figcaption></figure><ul><li><strong>Upstream gradient:</strong> the gradient that node <em>z</em> receives during backpropagation</li><li><strong>Local gradients:</strong> the gradients calculated respect to the inputs of node <em>z</em></li><li><strong>Downstream gradients:</strong> the product (<em>chain rule</em>) between the Upstream gradient and the Local gradients</li></ul><h4>References</h4><p>[1] <a href="https://en.wikipedia.org/wiki/Chain_rule#:~:text=The%20chain%20rule%20states%20that%20the%20derivative%20of%20the%20composite,%E2%88%9216.25%20%C2%B0C%2Fh.">Chain Rule— Wikipedia</a></p><p>[2] <a href="https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1184/lectures/lecture5.pdf">Lecture 5 Stanford Online pg. 54</a></p><h4>Further Resources</h4><ol><li>jefkine kafuna, <a href="https://www.jefkine.com/general/2016/09/05/backpropagation-in-convolutional-neural-networks/">Backpropagation In Convolutional Neural Networks</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a13b75fb56a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/backpropagation-in-fully-convolutional-networks-fcns-1a13b75fb56a">Backpropagation in Fully Convolutional Networks (FCNs)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation nelle Fully Convolutional Neural Networks (FCNNs)]]></title>
            <link>https://cannydatascience.medium.com/backpropagation-nelle-fully-convolutional-neural-networks-fcnns-1471c8e9409c?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/1471c8e9409c</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[intelligenza-artificiale]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Sat, 12 Dec 2020 14:50:03 GMT</pubDate>
            <atom:updated>2021-01-26T20:55:06.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aoN7uT8_2SLROxIl" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Backpropagation nelle Fully Convolutional Networks (FCNs)</h3><p>La backpropagation, in italiano retropropagazione dell’errore, è una della fasi di maggior importanza nel training di reti neurali. Come obiettivo, si pone di determinare, la <strong>conoscenza</strong> della nostra rete intesa come la capacità di rispondere in modo corretto a stimoli futuri. Volendo precisare, i termini “conoscenza” e “corretto” devono tener conto a mio avviso di due aspetti: (i) il primo è dato dall&#39;esperienza, o meglio, dalle informazioni (<em>features</em>) che la rete impara ad estrarre dai campioni del dataset (ii) il secondo dal calcolo dell’errore o anche detto perdita. Nell&#39;apprendimento supervisionato ogni campione è <em>labellato</em> con una classe (<em>classificazione</em>), con uno o più valori (<em>regressione</em>) o ambedue. Sia <em>y_actual </em>la label assegnata al campione dal supervisore e <em>y_pred </em>la predizione della rete, la fase di backpropagation farà si che la distanza (<em>errore</em>) tra le due sia accettabile. Entrambi i punti hanno come soggetto principale i <strong><em>pesi </em></strong>e saranno proprio quest’ultimi ad essere modificati durante la fase di backpropagation costituendo la conoscenza della rete.</p><p>Prima di lasciarvi, vorrei aggiungere ancora alcune note. La backpropagation conta due fasi. La prima è il calcolo del gradiente, o meglio, della derivata della funzione di perdita Loss rispetto ognuno dei pesi della rete. La seconda è l’aggiornamento dei pesi stessi (<em>delta rule</em>). Quest’ultima può essere effettuata con diversi algoritmi di ottimizzazione, per citarne qualcuno Momentum, Adam etc.. In questo articolo mi concentrerò solamente sulla prima fase lasciando l’approfondimento della seconda ad un momento successivo. Inoltre, non ho trovato molti riscontri sulla backpropagation applicata alle reti convoluzionali e ogni calcolo nonché interpretazione è frutto di studi personali. In caso di errori o interpretazioni errate sarei felice di discuterne. Grazie e buona lettura.</p><h3>Notazione</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*RA4n9q8hSxJjTm2UdMhdjA.png" /></figure><h3><strong>1. Kernel e convoluzione</strong></h3><p>Una delle domande che potremmo porci è perché utilizzare una Convolutional Neural Network anziché una MLPs per analizzare le immagini? Facciamo qualche esempio. Un’immagine è una sequenza di valori (<em>intensità dei pixels</em>) disposti a formare una matrice. Per utilizzare una MLPs dovremmo trasformare la matrice in un vettore e presentarlo allo strato di input della rete. A questo proposito, consideriamo un’immagine X di dimensioni (224,224,3) in cui 224 indica l’altezza e larghezza mentre 3 è la profondità in scala di colore Red, Green, Blue. Trasformandola otteniamo un vettore di dimensioni (150.528, 1) come mostrato in Fig.4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hu4wsDcxIhcGBC-lxsuvaQ.png" /><figcaption>Fig.4: Rappresentazione di una Multi Layer Perceptrons (MLPs) con input un’immagine X. (Foto a cura <a href="https://www.instagram.com/luigidvf/">Luigi Di Vito Francesco</a>)</figcaption></figure><p>In realtà, ci sono principalmente due errori in questo tipo di approccio. Il primo è che<strong> le immagini sono dati ordinati spazialmente. </strong>Volendo essere più chiari, l’ordine con cui i pixel sono disposti a formare la matrice fornisce un grande aiuto nell&#39;estrazione delle features. Per cui è un’informazione che non possiamo perdere. Il secondo è che utilizzando una MLPs il <strong>numero di parametri è molto elevato</strong>. Infatti, riprendendo il nostro esempio, solo per lo strato di input ci sarebbero 150.528 neuroni. Considerando un numero di neuroni pari a 100.000 nel secondo strato la nostra rete avrebbe 150.528x100.000 = 15.052.800.000 parametri solo tra il primo e secondo strato, immaginiamo considerando tutta la rete. (Nota: <em>più aumenta il numero di parametri, più il training richiederà tempo, più sarà difficile trovare l’ottimo, più il modello ha un maggiore peso in termini di memoria</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sSj87peJ_FG0YcIQ.gif" /><figcaption>Fig.5: Convoluzione tra l’immagine X di dimensioni (4,4,1) e il Kernel W di dimensioni (2,2) con stride S=[1,1]. La feature map di output è indicata con Z e presenta dimensioni (2,2)</figcaption></figure><p>L’introduzione del Kernel risolve queste problematiche. Un Kernel <em>W</em> è una matrice quadrata solitamente di dimensioni 2x2, 3x3 o 5x5 che scorre di un certo <strong>stride</strong> S<strong> </strong>lungo la larghezza M e l’altezza N dell’immagine X<em>, </em>eseguendo una somma pesata tra i valori <em>w (pesi) </em>del Kernel<em> </em>e la regione di sovrapposizione. Questo tipo di operazione, detta <strong>convoluzione, </strong>tiene conto<strong> </strong>della disposizione spaziale dei pixel sia in input che in output e favorisce una condivisione dei pesi <em>w </em>(<strong>shared weights</strong>) con i diversi pixels dell’immagine, riducendo il numero di parametri in gioco. Un esempio di convoluzione è mostrato in Fig.5. L’output, indicato con Z, è una <strong>feature map </strong>o meglio, una nuova immagine in cui specifiche caratteristiche di X sono messe in risalto<em>. </em>Supponendo<em> </em>che il Kernel W<em> </em>evidenzi i contorni<em>, </em>l’operazione di convoluzione produce una feature map di questo tipo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4CK-V-nGZvzSDzI30AHiQ.png" /><figcaption>Fig.6: Operazione di convoluzione per risaltarne i contorni dell’immagine X. il fattore 1/24 viene introdotto per ridurre il rumore nella feature map. (Foto a cura di <a href="https://www.instagram.com/luigidvf/">Luigi Di Vito Francesco</a>)</figcaption></figure><p>Come è possibile notare sia in Fig.5 che in Fig.6, Z non presenta le stesse dimensioni dell’immagine di partenza. Questo effetto è chiamato <strong>stride downsampling</strong>. Supponendo che le dimensioni in gioco siano per X: (Mx,Nx) per W: (Mw,Nw) e stride S, le dimensioni della feature map Z: (Mz,Nz) sono calcolate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*UhsquLHIRP9kn1C7qrZjyQ.png" /><figcaption>Formula (1)</figcaption></figure><h3>2. Fase di feed-forward</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*bqulDYFlxC1Vt8pojfxADg.png" /><figcaption>Fig.7: Rappresentazione di una Convolutional Neural Network con due strati convoluzionali</figcaption></figure><p>Consideriamo una rete formata da due strati convoluzionali, entrambi con un Kernel W di dimensione 2x2 e stride 1 sia lungo l’altezza che la larghezza e da due neuroni nell&#39;ultimo strato. Come funzione di attivazione non ne scegliamo una in particolare, ma la indichiamo genericamente con <em>g</em>. Ingresso della rete è un immagine in scala di grigio (<em>a singolo canale</em>) di dimensioni 4x4x1 Fig.7.</p><p>Esaminiamo la fase di forward. Prima di iniziare un ultimo appunto. Al fine di costruire il computational graph, per ogni pixel della feature map, è importante ricordare quali pixels sono stati utilizzati durante l’operazione di convoluzione. Ciò di cui abbiamo bisogno è della <em>posizione</em> che salveremo nell’insieme <em>P</em>.</p><ul><li><strong>Convoluzione Input X e Layer 1</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*7bb6XfOgNVNvUVEuXwU36g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyPBHsuHqsEQ0BKXJoSLKQ.png" /></figure><ul><li><strong>Convoluzione output Layer 1 e Layer 2</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*wg8d48Bf1O136LcrZOnpvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19GBcN_iVB206sWZpndcuQ.png" /></figure><ul><li><strong>Fully-Connected</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*b-5pU09elvRHAT93m-gIkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*su5k6muTJ7Y2d3pa1tMM3g.png" /></figure><h3><strong>3. Computational graph</strong></h3><p>Raggruppiamo le informazioni ottenute nella fase di forward in un computational graph (Fig.8). Quest’ultimo è una rappresentazione della nostra Convolutional Neural Network attraverso un grafo in cui, ogni nodo, corrisponde ad un singolo passaggio di forward. In particolare, possiamo notare come ognuno dei nodi <em>z</em> di convoluzione ha come inputs i nodi con indice in P.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2R9lZTy-rVhaRI0zph925g.png" /><figcaption>Fig.8: Rappresentazione del computational graph della rete in Fig.7</figcaption></figure><h3>4. Fase di backpropagation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*cHVKyUzhaBsyELH8rhR5cQ.png" /><figcaption>Formula (2)</figcaption></figure><p>Indicando con L la funzione di Loss, il computational graph consente di definire in modo agevole il vettore gradiente ∇wL. Quest’ultimo sarà poi utilizzato dalla <em>delta rule </em>per aggiornare i pesi della rete. La Formula (2) rappresenta il vettore gradiente della rete in Fig.7. È costituito da tre componenti, vettori anch&#39;essi, in riferimento ai pesi del Layer 3 e rispettivamente ai Kernel dei Layer 2 ed 1. Nel seguito, analizzo ognuna di esse utilizzando la regola della catena (<em>chain rule</em>) per il calcolo delle derivate parziali.</p><ul><li><strong>Calcolo di <em>∂</em>L /∂W^(3)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*BMziRFBySXVGmRzIFiywjA.png" /><figcaption>Formula (3)</figcaption></figure><p>La Formula (3) è il vettore gradiente dei pesi W Layer 3. Per calcolare i suoi elementi è necessario risolvere una dipendenza singola [Appendice 1.1]. Come esempio, in Formula (4) è mostrato il calcolo della derivata della Loss rispetto al peso <em>w</em>1 Layer 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*_70s02Mtn00BR10Xu-Dt9A.png" /><figcaption>Formula (4)</figcaption></figure><p>Indicando con F (<em>fully</em>) il numero di neuroni dell’ultimo strato per ogni elemento <em>n </em>del vettore Formula (3) otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*UscBIGQmvAou25Q6qU14tA.png" /><figcaption>Formula (5)</figcaption></figure><ul><li><strong>Calcolo di <em>∂</em>L /∂W^(2)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*53lZ7ZjH2qV6-i-AQNj-ug.png" /><figcaption>Formula (6)</figcaption></figure><p>La Formula (6) è il vettore gradiente della matrice W Layer 2. Per calcolare i suoi elementi è necessario risolvere dapprima una dipendenza singola dipesa, come analizzato, dal gradiente del Layer 3 e successivamente una dipendenza multipla [Appendice 1.2] per ognuno dei neuroni<em> f</em>. Infatti, osservando la Fig.8, possiamo notare come (i) ogni peso <em>w</em> Layer 2 sia presente nelle diverse somme <em>zi^(2) </em>dovuto, come già discusso, alla condivisione dei pesi (<em>shared weights</em>) caratteristica della convoluzione (ii) ogni neurone <em>f</em> è connesso ad ognuno delle attivazione del Layer 2 per i fully connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cONEgy1qNVciUNIr.gif" /><figcaption>Fig.9: Calcolo dei downstream gradients per ogni nodo zf Layer 3</figcaption></figure><p>Come esempio, consideriamo il calcolo del gradiente rispetto il peso <em>w1 </em>Layer 2. Per semplicità di trattazione, per ogni nodo di attivazione<em> ai </em>Layer 2 calcoliamo l’<em>upstream gradient </em>ottenuto<em> s</em>ommando i <em>downstream gradients </em>[Appendice 2] dei rispettivi nodi <em>zf</em> Layer 3. Il calcolo dei downstream è mostrato in Fig.9, ogni coppia è poi sommata a formare l’upstream formalizzato per ogni attivazione in Formula (10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnNqVrcrGnMBSFcw6vyJYA.png" /><figcaption>Formula (10)</figcaption></figure><p>A questo punto, il gradiente della Loss rispetto <em>w1 </em>Layer 2 sarà dato dalla Formula (11) in cui ognuno degli <em>∂</em>L /∂<em>ai </em>upstream gradient è moltiplicato per le derivate dei rispettivi nodi <em>ai </em>e <em>zi</em>. Dopodiché, ogni contributo è sommato dato il punto (i) descritto precedentemente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzGQE7Nz6_hCoOUpLbx_DQ.png" /><figcaption>Formula (11)</figcaption></figure><p>Partendo da quanto visto e generalizzando, per ogni nodo <em>ai </em>Layer 2 l’upstream gradient sarà dato dalla Formula (12). Quest’ultima, altro non è che la Formula (5) in cui anzichè derivare <em>zf </em>Layer 3 per il peso w deriviamo per l’attivazione <em>ai, </em>andando poi a sommare i contributi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*jlxERd1qYwLWnU5K7EgOaA.png" /><figcaption>Formula (12)</figcaption></figure><p>Invece, per ogni elemento<em> n</em> del vettore Formula (6) otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*LT4KPhcv2BERlB5toENBJw.png" /><figcaption>Formula (13)</figcaption></figure><p>Per completezza, unendo la Formula (12) e la (13) otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bt_e2dn1pH8t6v9nVFxMw.png" /></figure><ul><li><strong>Calcolo di <em>∂</em>L /∂W^(1)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*1fbDg6vZ6Vxr-Wv2B2HhtA.png" /><figcaption>Formula (14)</figcaption></figure><p>La Formula (14) è il vettore gradiente della matrice W Layer 1. Rispetto al caso precedente, per il calcolo delle derivate parziali è necessario risolvere più step di dipendenze multiple in cascata tra loro dipese dai fully connected e dalla convoluzione. Osservando la Fig.8 è possibile notare che (i) ogni peso di W^(1) è presente nelle diverse somme pesate <em>zj</em> del Layer 1 (<em>shared weight</em>s).</p><p>Come esempio, consideriamo il calcolo del gradiente rispetto il peso <em>w1 </em>Layer 1. Anche qui, per ogni nodo di attivazione<em> aj </em>Layer 1 calcoliamo l’<em>upstream gradient </em>formalizzati in<em> </em>Formula (15)<em>. </em>Per calcolarlo utilizziamo le informazioni già in nostro possesso<em>.</em> In particolare, gli upstream gradient in Formula (10) che una volta ottenuto il <em>∂</em>L /∂z<em>i</em>^(2) ci consentiranno di calcolare i singoli downstream Fig.10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eED9ebj53ZIYaz-F.gif" /><figcaption>Fig.10: Calcolo dei downstream gradients per ogni nodo zi Layer 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvzQ3NGGFiE-033VLMHfsQ.png" /><figcaption>Formula (15)</figcaption></figure><p>A questo punto, il gradiente della Loss rispetto <em>w1 </em>Layer 1 sarà dato dalla Formula (16) in cui ognuno dei <em>∂</em>L /∂<em>aj </em>upstream gradients, formalizzato in Formula (15), è moltiplicato per le derivate dei rispettivi nodi di attivazione <em>aj </em>e <em>zj</em>. Dopodiché, ogni contributo è sommato per il punto (i) descritto precedentemente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*umcx04B0C365y2pTO_Xc_g.png" /><figcaption>Formula (16)</figcaption></figure><p>Partendo da quanto visto e generalizzando, per ogni nodo <em>aj </em>Layer 1 l’upstream gradient sarà dato dalla Formula (13) in cui anziché derivare<em> zi </em>Layer 2 rispetto il peso <em>w</em>, deriviamo rispetto <em>aj </em>Layer 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*FvUi9T2y0kyMld55tkLUVg.png" /><figcaption>Formula (17)</figcaption></figure><p>Invece, per ogni elemento<em> n</em> del vettore Formula (14) otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*h6JYqiuBtt1pPdcBWrfo5w.png" /><figcaption>Formula (18)</figcaption></figure><p>Per completezza, unendo la Formula (12), (17) e (18) otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15ZFqxpgZbuTnR8vLrjvQg.png" /></figure><h3><strong>5.Conclusione</strong></h3><p>In questo articolo abbiamo esplorato la fase di backpropagation concentrando le nostre analisi sul computational graph della rete fittizia in Fig.7. In generale, per calcolare il vettore gradiente di un Layer convoluzionale <em>l-esimo </em>sarà necessario:</p><ul><li>calcolare l upstream gradient rispetto ogni attivazione<em> a</em> del Layer<em> l</em></li><li>sommare i contributi di derivazione di <em>z rispetto w </em>del Layer l</li></ul><p>Ovviamente, le reti moderne sono molto più complesse. Alcune differenze potremmo averle nel numero di channels di ogni blocco features map (<em>immagina più features maps una dietro l’altra a mo’ di cubo, ognuna di esse è un channel)</em> con un conseguente aumento della profondità dei Kernel W, oppure potremmo avere per ogni layer più di un Kernel, o ancora avere dei layers di Batch Normalization e quindi applicare la backpropagation anche qui, oppure avere un termine di bias per ogni layer e considerare una retropropagazione anche per questo termine. Ecco, quella presentata in questo articolo è un esempio semplice, ma spero esplicativo della backpropagation.</p><h3><strong>Appendice</strong></h3><p>In Fig.11 / 12 / 13 è analizzato come esempio un nodo <em>z, </em>ovviamente le stesse considerazioni possono essere fatte su qualsiasi altra funzione.</p><ol><li><strong>Chain rule</strong></li></ol><p>La regola della catena, in inglese <em>chain rule</em>, è una regola di derivazione che consente di calcolare le derivate di funzioni composte [1].</p><p><strong>1.1 Dipendenza singola</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*BCeRelNUGqDNeKTVogcrug.png" /><figcaption>Formula (19)</figcaption></figure><p>Sia <em>a(t) </em>funzione differenziabile in <em>t </em>e <em>z(a(t)) </em>funzione differenziabile in <em>a. </em>La derivata di<em> z </em>rispetto a <em>t</em> è descritta dalla Formula (19). Analizzando il computational graph per il calcolo della derivata otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YYyLmmAkFZkGbmgRKzIzw.png" /><figcaption>Fig.11: Rappresentazione della derivata per la funzione composta z(a(t))</figcaption></figure><p><strong>1.2 Dipendenza multipla</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*tXp-FHKarSJ3N9AGHf7RKw.png" /><figcaption>Formula (20)</figcaption></figure><p>Siano <em>a1(t) </em>e<em> a2(t)</em> funzioni differenziabili in<em> t </em>ed<em> z(a1(t), a2(t)) </em>funzione differenziabile in<em> a1 </em>e<em> a2. </em>La derivata di<em> z </em>rispetto <em>t </em>è descritta dalla Formula(20). Analizzando il computational graph per il calcolo della derivata otteniamo<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcTqh6HwTLgyAOhVeF3cxg.png" /><figcaption>Fig.12: Rappresentazione della derivata per la funzione composta z(a1(t), a2(t))</figcaption></figure><p>2. <strong>Gradiente </strong>[2]</p><p><em>Siano a1(.)</em> e<em> a2(.) </em>due funzioni ed <em>z</em>(<em>a1</em>(.) , <em>a2</em>(.)) funzione differenziabile in <em>a1 </em>e <em>a2</em>.<em> </em>Si definisce:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*HXmqY_yFrXTHqjd_-PHkJA.png" /><figcaption>Fig.13: Rappresentazione delle diverse forme di gradiente su un singolo nodo</figcaption></figure><ul><li><strong>Upstream gradient: </strong>il gradiente che il nodo <em>z</em> riceve durante la retropropagazione dell’errore</li><li><strong>Local gradients: </strong>i gradienti calcolati rispetto gli input del nodo<em> z</em></li><li><strong>Downstream gradients: </strong>il prodotto (<em>chain rule</em>) tra l’Upstream gradient e i Local gradients</li></ul><h3><strong>References</strong></h3><p>[1] <a href="https://it.wikipedia.org/wiki/Regola_della_catena">Regola della catena — Wikipedia</a></p><p>[2] <a href="https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1184/lectures/lecture5.pdf">Lecture 5 Stanford Online pg. 54</a></p><h3><strong>Articoli relativi alla CNNs backpropagation</strong></h3><ol><li><a href="https://www.jefkine.com/general/2016/09/05/backpropagation-in-convolutional-neural-networks/">Backpropagation In Convolutional Neural Networks | DeepGrid (jefkine.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1471c8e9409c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Additive skip connection]]></title>
            <link>https://cannydatascience.medium.com/additive-skip-connection-222b45a6a0e2?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/222b45a6a0e2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[residual-block]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[loss-function]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 19:46:54 GMT</pubDate>
            <atom:updated>2020-10-01T15:23:28.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*czEFKeXlhAizCJ8XAB_Iog.jpeg" /><figcaption>Photo by <a href="https://www.flickr.com/photos/k1llyrid0ls/">Killy Ridols</a> — <a href="https://www.flickr.com/photos/40042332@N04/4547441197/">Patagonia</a> on <a href="https://www.flickr.com/">Flickr</a></figcaption></figure><p>Il vanishing gradient, in italiano scomparsa del gradiente, è un fenomeno che si presenta durante il training di reti profonde ed come effetto quello di annullare o rallentare l’aggiornamento dei pesi per alcuni layers della nostra rete. Nell&#39;<a href="https://medium.com/@cannydatascience/vanishing-gradient-in-deep-neural-networks-24d887047bf4">articolo precedente </a>abbiamo individuato due cause principali: (i) riduzione/annullamento del prodotto <em>∂a/∂z </em>dovuto all&#39;utilizzo di funzioni di attivazione a codominio limitato (ii) riduzione/annullamento del prodotto <em>∂z/∂a </em>dovuta ai pesi. Il primo può essere in parte risolto mediante l’utilizzo di funzioni di attivazioni rettificate (i.e ReLU). Quest’ultima, avendo derivata unitaria per input positivo, consente il passaggio del gradiente durante la fase di backpropagation. Un notevole passo avanti per la risoluzione del secondo problema ci fu con l’introduzione delle additive skip connections.</p><h3>Un percorso alternativo per il gradiente</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EotLrzf6oUzf-Cg3khhyw.png" /><figcaption>Fig.1: A sinistra un esempio di successione di layer senza l’utilizzo di nessuna skip connection. A destra un esempio di additive skip connection</figcaption></figure><p>Obiettivo delle <em>additive skip connection</em> è quello di creare un percorso alternativo per il passaggio del gradiente durante la fase di retropropagazione dell’errore. Un esempio è presentato in Fig.1. Con <strong><em>X</em> </strong>indichiamo<strong> l’identità</strong> o meglio l’input in ingresso. Con <strong>F(X, W) </strong>le <strong>trasformazioni non lineari F effettuate sull&#39;input X </strong>dai layers intermedi [1]. Un esempio di trasformazione non linere è <strong>convoluzione + attivazione</strong><em> </em>che possiamo trovare nella Convolutional Neural Networks (CNNs) ed hanno come risultato le features maps.</p><p>Nelle additive skip connection, l’identità X è sommata a F(X, W) producendo l’output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*aEJN4CEUoZTMsIgYhr5bKg.png" /><figcaption>Formula 1</figcaption></figure><p>Successivamente su H(X) verrà applicata una funzione di attivazione ReLU. Analizziamo il gradiente di una singola skip connection per comprendere come questo possa aiutare il gradiente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wlegk6k8HZTrOlCwqnAAWQ.png" /><figcaption>Fig.2: Calcolo del gradiente di un’additive skip connection</figcaption></figure><p>Come possiamo notare dalla Fig.2 il gradiente <em>∂</em>L /<em>∂X</em> è diviso in due componenti. La prima attraversa i weight layers ed è detta <em>percorso di Plain</em>. <strong>La seconda componente</strong>, detta <em>percorso di Skip</em>, non attraversa i weight layers evitando le derivate <em>∂z</em> /<em>∂a</em><strong>. </strong>Questo comportamento<strong> consente di retropropagare l’informazione in modo diretto ad ogni strato meno profondo </strong>[2]<strong>. </strong>Una considerazione su <em>∂A</em>/<em>∂H. </em>In Fig.2 supponiamo che il valore della derivata sia unitario. La funzione ReLU ha una derivata unitaria per valori di input positivi e nulla per valori negativi. Nella pratica, considerando delle features maps, è improbabile che F(X,W)+X sia totalmente negativo tanto da annullare il gradiente.</p><h3><strong>Di quanti layers ho bisogno?</strong></h3><p>Lasciamo la matematica per un’istante e cerchiamo di dare una spiegazione intuitiva<em>. </em>L’ additive skip connection, conosciuto anche con il nome di <strong>blocco residuale, </strong>costituisce l’elemento fondamentale dell’architettura di rete ResNet <em>(rete residuale). </em>Il nome <em>residuo</em> è dovuto alla tecnica di apprendimento di un singolo blocchetto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*mF-jK66urdZCQA81J77QJA.png" /><figcaption>Formula 2</figcaption></figure><p>Il principio alla base di ResNet è il seguente:</p><blockquote><em>Il modello con più layers dovrebbe essere in grado di performare almeno come un modello meno profondo</em></blockquote><p>Il numero di layers in un rete neurale è un hyperparametro. Certo, esistono delle architetture già “pronte all&#39;uso”, ma spesso accade di doverle modificare per adattarle al nostro problema. In accordo con quanto scritto <a href="https://medium.com/p/24d887047bf4#b1e5">qui</a> , ciò che potremmo fare è aggiungere alcuni layers per provare a generalizzare ulteriormente. Bene, consideriamo la rete 1 con un numero di layers <em>N </em>a cui andiamo ad aggiungere una blocco residuale dopo l’ultimo strato. Cosi facendo otteniamo la rete 2 mostrata in Fig.3. Ovviamente la rete 2 ha una profondità maggiore della 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*ukdlwAj90WQrKXA8Dxl6hQ.png" /><figcaption>Fig.3: Rete neurale con aggiunta di un blocco residuale. Immagine tratta dal [3]</figcaption></figure><p>L’ additive skip connection fa queste due considerazioni:</p><ul><li><strong>W=0: se non imparo nulla di nuovo almeno ricordo il passato</strong></li></ul><p>Supponiamo che i pesi dei layers N+1 e N+2 siano nulli. In una CNN l’operazione di convoluzione produrebbe delle features maps vuote: i kernels non evidenziano nessuna caratteristica sull&#39;input X producendo così features maps con pixels di valore 0. Questo accade <strong>quando la rete non riesce a generalizzare ulteriormente, </strong>o meglio<strong>, l’identità è ottima</strong>. Con l’utilizzo del blocco residuale, nonostante i layers N+1 e N+2 non riescano ad estrarre informazione, riusciamo comunque a non annullare l’output consentendo all&#39;informazione X di procedere in avanti. Se avessimo utilizzato un blocco di Plain (<em>come quello presentato in</em> Fig.1), l’output della rete 2 sarebbe stato un insieme di valori nulli perdendo così le informazioni su X. Volendo avere un punto di vista differente possiamo dire che la rete 2, grazie al blocco residuale, performa come la rete meno profonda 1.</p><p>Ma cosa c’entra il residuo? In questo caso il blocco residuale cerca di mappare il suo input (<em>l’identità</em>) pur di non perdere informazione, o meglio, apprende il residuo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*NX710lKev380dEo3ihR_Mw.png" /><figcaption>Formula 3</figcaption></figure><ul><li><strong>W !=0: se imparo qualcosa il passato mi è comunque di aiuto</strong></li></ul><p>Supponiamo che i pesi dei layers N+1 e N+2 non siano nulli, per cui un’operazione di convoluzione produrebbe delle features maps non vuote. In questo caso l’identità <strong>X non è ottima</strong> poiché riusciamo ancora ad estrarre informazione. Bene, “perturbando” l’identità con quanto estratto in N+1 e N+2 aumentiamo la precisione dell’identità.</p><p>Cosa c’entra il residuo? In questo caso il blocco residuale impara a mappare la perturbazione, o meglio, il suo residuo.</p><h3><strong>Oltre il gradiente</strong></h3><p>Abbiamo analizzato sia da un punto di vista analitico che intuitivo i vantaggi per il gradiente nell&#39;utilizzo dell’additive skip connection. Vorrei spendere ancora qualche parola su due punti importanti.</p><h4><strong>Features spaziali in profondità</strong></h4><p><a href="https://medium.com/@cannydatascience/vanishing-gradient-in-deep-neural-networks-24d887047bf4#b1e5">Come sappiamo</a> in una rete convoluzionale gli strati in prossimità dell’input estraggono <strong>features spaziali,</strong> al contrario i layers più in profondità<strong> </strong>estrarranno <strong>features semantiche. </strong>Nelle reti <em>Plain</em> come ad esempio VGG16 o VGG19 le informazioni spaziali difficilmente confluiranno in profondità nella rete. In questo modo perdiamo delle informazioni importanti che potrebbero consentire alla rete di lavorare meglio. Nelle reti residuali abbiamo modo di evitare questa perdita di informazione.</p><p>In Fig.4 è possibile confrontare le features maps estratte dalla rete Plain VGG19 con quelle estratte, allo stesso livello, nella corrispettiva rete residuale ResNet50. Come possiamo osservare, nelle features maps della ResNet50 oltre ad informazioni semantiche troviamo anche informazioni spaziali: i contorni sono ancora presenti in due delle quattro features maps presentate contrariamente a quanto accade per VGG19 che si concentra sulle parti del soggetto in input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udaZ8ZeVNm9rqbIhQ8QQWw.png" /><figcaption>Fig.4: Confronto delle features maps estratte dalla rete di plain VGG-19 e la corrispettiva rete residuale ResNet. Come possiamo osservare nelle features maps relativa alla rete residuale oltre allen informazioni semantiche possiamo trovare anche le informazioni spaziali</figcaption></figure><h4><strong>Loss landscape</strong></h4><p>La fase di retropropagazione dell’errore consente di percorrere la direzione di discesa della funzione di loss. <a href="https://medium.com/p/91c0c900fbc#b091">Nell&#39;articolo sulla backpropagation</a> ho chiamato la rappresentazione tridimensionale della Loss con il nome “valle”… in realtà , il suo vero nome è <strong>loss landscape </strong>[4]. La sua complessità, nonchè forma tridimensionale, dipende dal numero di layers. All&#39;aumentare della profondità della rete questa valle si complica. Più aggiungiamo layers più diventa difficile trovare la direzione di discesa che ci conduce al minimo globale. In gergo, possiamo dire che la funzione di loss diventa <strong>non convessa.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*D25egJFuADRH8lH4ToTjmg.png" /></figure><p>Quando si parla di ottimizzazione di reti, la convessità è un requisito fondamentale. Considera una pallina che scende lunga un paraboloide (funzione convessa). La pallina raggiungerà in maniera semplice il minimo globale, contrariamente a quanto potrebbe accadere con una funzione non convessa. Con l’utilizzo delle skip connections riusciamo a semplificare la loss landscape rendendola <strong>convessa</strong>. Vediamo qualche esempio grafico.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*dMP3hzAPFCegtU5TlsUq0g.png" /><figcaption>Fig.5: Confronto della loss landscape tra l’architettura di rete Plain ResNet-56 e la rete ResNet-56 con skip connections. Da notare che la ResNet</figcaption></figure><p>In Fig.5 viene presentata la loss landscape per una di Plain ResNet-56 senza l’utilizzo delle skip connections. Come possiamo intuire è altamente non convessa. Sostituendo i vari blocchetti di Plain con quelli di skip connection otteniamo la situazione presentata per la ResNer-56 (with skip connections).</p><p><strong>Nota: </strong>Per il plotting della loss landscape di un modello fare riferimento a questo <a href="https://github.com/tomgoldstein/loss-landscape">link Github</a>. All&#39;interno del repo è possibile scaricare dei modelli preipostati. Invece, per plottare la loss landscape di un modello qualsiasi basta salvare il modello in .t7 e modificare <em>cifar10/model_loder.py</em>. Nel mio caso, per la loss landscape di VGG19 ho modificato il model_loder in questo modo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*790NdkjzXhdGp4rOfMhN7A.png" /></figure><p>Purtroppo, i tempi di computazione sono abbastanza elevati e nonostante la parallelizzazione dei jobs e l’utilizzo di GPU su Google Colab non sono riuscito ad ottenere una rappresentazione 3D. Le immagini presenti in Fig.5 sono ottenute da <a href="http://www.telesens.co/loss-landscape-viz/viewer.html">qui</a>, link che presente anche nel repository.</p><h3><strong>Conclusioni</strong></h3><p>La nascita delle skip connections ha introdotto notevoli vantaggi non solo per il problema del vanishing gradient ma anche nel training di reti profonde. In questo articolo abbiamo esaminato una tipologia di skip connection. In realtà, oltre alla <em>somma (H(x) = F(X,w) + X)</em>, possiamo avere skip connections basate sulla <em>concatenazione (H(x) = [F(X,w) , X]). </em>Quest’ultima<em> </em>è presente in reti come UNet e DenseNet.</p><h3><strong>References</strong></h3><p>[1] <a href="https://arxiv.org/pdf/1512.03385.pdf">Deep Residual Learning for Image Recognition</a></p><p>[2] <a href="https://arxiv.org/pdf/1603.05027.pdf">Identity Mappings in Deep Residual Networks</a> pg. 1 a 4</p><p>[3] <a href="https://www.youtube.com/watch?v=RYth6EbBUqM">Why ResNets Work</a></p><p>[4] <a href="https://arxiv.org/pdf/1712.09913.pdf">Visualizing the Loss Landscape of Neural Nets</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222b45a6a0e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vanishing gradient in Deep Neural Networks]]></title>
            <link>https://cannydatascience.medium.com/vanishing-gradient-in-deep-neural-networks-24d887047bf4?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d887047bf4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[relu]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[scomparsa-del-gradeinte]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 15:26:29 GMT</pubDate>
            <atom:updated>2020-09-30T20:37:33.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ErpFKqIOVh4ar87h" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Nel <a href="https://medium.com/@cannydatascience/backpropagation-come-apprende-una-rete-neurale-91c0c900fbc">precedente articolo</a> abbiamo affrontato il tema della backpropagation calcolando il gradiente di una MLPs con tre layers: due nascosti e uno di output. Oggigiorno, le reti utilizzate per la classificazione di immagini o analisi di sequenze (<em>audio, testo etc..</em>) sono formate da molti più layers. Uno dei maggiori problemi nel training di reti profonde è la presenza di <strong>vanishing gradient,</strong> in italiano <em>scomparsa del gradiente</em><strong>:</strong> il gradiente assume un valore nullo o asintotico allo zero impedendo cosi l’aggiornamento dei pesi.</p><h3><strong>Cos’è il vanishing gradient?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-fUdTF_BSPqv_TqbWpssw.png" /><figcaption>Fig.1: In figura sono riportate le features maps ottenute a diversi livelli della rete FCNN VGG-16</figcaption></figure><p>In una rete convoluzionale gli strati in prossimità dell’input estraggono dall&#39;immagine <strong>features spaziali: </strong>orientamento dei contorni, presenza di angoli, informazioni sul colore, presenza di trame etc... Avvicinandoci allo strato di output verranno estratte <strong>features semantiche: </strong>presenza di bocca, naso etc… Un esempio di quanto appena detto è mostrato in Fig.1 in cui sono riportate alcune features maps estratte a diversi livelli di VGG-16. In generale, aumentando la profondità ogni strato sarà in grado di estrarre features più <strong>generali </strong>e <strong>complesse</strong>.</p><p>Le reti profonde sono però difficili da addestrare. Uno dei maggiori problemi è la <em>scomparsa del gradiente</em> o meglio conosciuto con il nome di<em> </em><strong>vanishing gradient. </strong>Durante la fase di backpropagation i pesi degli strati in prossimità dell’input restano costanti o si aggiornano molto lentamente al contrario di quanto accade per gli strati vicini all’output.</p><p>Consideriamo la successione di neuroni in Fig.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dJkJVS3hC9XPWj4J3pehQ.jpeg" /><figcaption>Fig.2: Plain Network con tre neuroni</figcaption></figure><p>Aggiorniamo il peso w^(1) calcolando la derivata <em>∂</em>L /<em>∂</em>w^(1). Per semplicità di trattazione, supponiamo che il termine di <em>bias</em> b sia nullo per ogni neurone<strong>. </strong>Applicando la regola della catena e raggruppando le derivate delle funzioni di attivazione otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*_BJx8o5Gm0HBSgoq-zc9nA.png" /></figure><p>Cosa può fermare/rallentare il gradiente? Analizziamo il prodotto <em>∂a^(i)</em>/<em>∂z</em>^(i).</p><p><strong>Caso 1:</strong> Supponiamo che solamente la <em>i-esima</em> derivata <em>∂a^(i)</em>/<em>∂z</em>^(i) sia nulla ad ogni iterazione (ad esempio <em>∂a^(2)</em>/<em>∂z</em>^(2)). In questo caso <em>∂</em>L /<em>∂</em>w^(1) assumerà un valore nullo impedendo l’aggiornamento di <em>w^(1) </em>che rimarrà <strong>costante</strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*PvmKpvMDZl-S2Az2Xg4I4g.png" /><figcaption>Regola di aggiornamento per il peso w^(1) con derivata <em>∂</em>L / <em>∂</em>w^(1) nulla</figcaption></figure><p><strong>Caso 2: </strong>Supponiamo ora che ogni termine <em>∂a^(i)</em>/<em>∂z^(i)</em> assuma dei valori asintotici allo zero (<em>molto piccoli</em>) ad ogni iterazione. In questo modo <em>∂</em>L/<em>∂</em>w^(1) sarà anch&#39;esso asintotico allo zero e <em>w^(1) </em>si aggiornerà <strong>molto lentamente </strong>(<em>sommiamo di volta in volta valori prossimi allo zero)</em><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*UwXl7c79Hc_CUQvNmmNbhQ.png" /><figcaption>Regola di aggiornamento per il peso w^(1) con derivata <em>∂</em>L / <em>∂</em>w^(1) prossimo allo zero</figcaption></figure><h3>Funzioni di attivazione con codominio limitato</h3><p>Dagli esempi possiamo intuire come la scelta della funzione di attivazione <em>g</em> gioca un ruolo importante. Una delle principali cause della <em>scomparsa del gradiente</em> è dovuta all&#39;utilizzo di <em>funzioni di attivazione </em>con<em> codominio limitato</em>:</p><ul><li>le derivate (<em>∂a/∂z</em>) saranno non nulle solamente per valori di input <em>z</em> che cadono all&#39;interno della <em>regione di significatività</em></li><li>nella regione di significatività le derivate assumono valori relativamente piccoli. Considerando un numero elevato di layers e moltiplicando i valori <em>∂a/∂z </em>potremmo rallentare il gradiente</li></ul><p>I due punti appena descritti rispecchiano perfettamente quanto detto per il Caso 1 e il Caso 2. Analizziamoli considerando come funzione di attivazione a codominio limitato quella sigmoidea <em>(σ) </em>Fig.3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*oZwsRKsN7xjpXVmAyZbV9g.png" /><figcaption>Fig.3: In blu è rappresentata la funzione sigmoidea con codominio [0,1]. In rosso è rappresentata la sua derivata. Sull’asse delle ascisse è rappresentato il valore dell’input z mentre sull’asse delle ordinate il valore di derivata corrispondente</figcaption></figure><p>Considerando la derivata, la <em>regione di significatività </em>si presenta per valori di input che cadono nell&#39;intervallo [-4,4], per valori al di fuori di questo intervallo la derivata sarà nulla (<em>Caso 1).</em></p><p>Ora supponiamo di avere una rete con<em> </em>un<em> </em>numero di layers <em>K</em> (Fig.4) in cui, per ogni neurone, <em>z</em> assume valore nella regione di significatività:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AlapIxPaqukzI-Ckkg-jQ.png" /><figcaption>Fig.4: Plain Network con un numero K di neuroni</figcaption></figure><p>Calcoliamo il gradiente per K, K-1, K-2 ed 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uM3NYEOXXYYEV8WzwdQBSg.jpeg" /></figure><p>Moltiplicando i valori in rosso notiamo come man mano che ci allontaniamo dall’output il prodotto <em>∂a/∂z </em>decresce. Se K fosse uguale a 50 layers (<em>per cui un numero elevato</em>) avremo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/0*rqYCtZ-WydhmQsFX" /></figure><p>o meglio, il Caso 2.</p><h3><em>Rectified Linear Units (</em>ReLU)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*PmLwDmU_dkP8qSxktFf17Q.png" /><figcaption>Fig.5: Rappresentazione grafica della funzione di attivazione ReLU</figcaption></figure><p>L’utilizzo della funzione di attivazione ReLU (Fig.5), ha contribuito alla risoluzione (<em>almeno in parte</em>) del vanishing gradient. Sia<em> z</em> input della funzione di attivazione, possiamo definire matematicamente la ReLU con <em>max(0,z). </em>Osservando la derivata in Fig.6 notiamo come per i valori di <em>z</em> in <em>R^+</em> la<em> </em>derivata è unitaria consentendo così il passaggio del gradiente. Eventuali problemi sorgono quando il valore di input è negativo ottenendo cosi il <em>Caso 1.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*UP-IdQeCm588E5OhBu_NLQ.png" /><figcaption>Fig.6: Rappresentazione grafica della derivata della funzione di attivazione ReLU</figcaption></figure><p>Esistono delle varianti della Rectified Linear Units come LeakyReLU ed ELU nate per mitigare il problema della derivata nulla per z&lt;0.</p><h3><strong>La ReLU, </strong>LeakyReLU ed ELU sono <strong>la soluzione di tutto?</strong></h3><p>Allenare reti con un numero notevole di layers non è semplice. In questo articolo abbiamo esplorato la <em>scomparsa del gradiente</em> identificando una possibile causa nella scelta delle funzioni di attivazione. Una soluzione proposta è l&#39;utilizzo della Rectified Linear Units che per valori positivi, non ostacola il passaggio del gradiente. Ma… la ReLU non risolve totalmente il problema del vanishing gradient. Un’ulteriore fattore da non sottovalutare è <strong>l’inizializzazione dei pesi. </strong>Cosa accadrebbe se la derivata ∂z/∂a fosse nulla o di valore prossimo a zero per più layers?<em> </em>Le considerazioni e gli esempi appena discussi per le funzioni di attivazione possono essere ripetuti per rispondere alla domanda. Se da un lato abbiamo la <em>scomparsa del gradiente</em>, dall&#39;altro dobbiamo considerare il problema esattamente opposto l’<em>Exploding gradient</em>: il gradiente assume un valore elevato impedendo così l’ottimizzazione. Un contributo importante per il training di reti profonde ci fù con l’introduzione delle <a href="https://medium.com/@cannydatascience/additive-skip-connection-222b45a6a0e2"><strong>skip connection</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d887047bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation: Come apprende una rete neurale?]]></title>
            <link>https://cannydatascience.medium.com/backpropagation-come-apprende-una-rete-neurale-91c0c900fbc?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c0c900fbc</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[apprendimento-automatico]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 09:01:57 GMT</pubDate>
            <atom:updated>2020-09-30T21:19:58.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e8X3SWkrEj2PH2Dl" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduzione</h3><p>Una delle tematiche che più mi affascina del mondo Deep Learning è il processo di apprendimento. In questa fase, si determina la “conoscenza” di una rete neurale, o meglio, la capacità di rispondere in maniera corretta ad uno specifico stimolo esterno. Sommariamente possiamo dividerlo in due fasi: <strong>foward </strong>e <strong>backward pass</strong>. In questo articolo ci concentreremo sulla fase di backward.</p><h3><strong>Notazione</strong></h3><ul><li><strong><em>a</em></strong><em>: </em>output della funzione di attivazione del neurone</li><li><strong><em>z</em></strong><em>:</em> somma pesata degli input del neurone</li><li><strong><em>x</em>:</strong> campione di training con features x1, x2</li><li><strong><em>apice </em>(<em>l</em>)</strong>: layer <em>l</em> di riferimento</li><li><strong>pedice</strong>: neurone di riferimento</li></ul><p>Ex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trJP8gavdFoMGmpoeQ-NVw.png" /></figure><h3>1. Apprendimento, un processo di ottimizzazione</h3><p>L’obiettivo di una Multi Layers Perceptrons (MLPs), ma in generale di ogni rete neurale, è quello di <strong>stimare</strong> <strong>i valori W e b </strong>tali per cui ad un’input <em>x, </em>venga associato un output<em> y_pred. </em>Matematicamente questo mapping è definito attraverso la funzione <em>f:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*vPtWEHmwej1bMGRww37yfg.png" /><figcaption>Formula (1)</figcaption></figure><p>I valori di W, detti <em>pesi, </em>costituiscono le connessioni tra i neuroni. Il loro valore è determinato durante la fase di allenamento (<em>training</em>) in modo tale da minimizzare la funzione di perdita. Formalmente questo processo è espresso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*6hZQWqsh3jesipwqh8ed_g.png" /><figcaption>Formula (2)</figcaption></figure><p>dove il primo termine della somma costituisce la funzione di Loss (<em>L) </em>calcolata<em> </em>tra la predizione della rete <em>(y_pred)</em> e il relativo output target <em>(y_true)</em>, <em>R(W)</em> è il termine di regolarizzazione mentre λ è il relativo parametro di regolarizzazione. J(W) esprime la funzione di costo complessiva calcolata sugli <em>N</em> campioni di batch.</p><p>La minimizzazione è un processo di <em>ottimizzazione </em>iterativo. In breve possiamo descriverlo così: nella prima iterazione, i pesi sono inizializzati con valori casuali. I dati, vengono fatti passare in <em>foward</em> lungo gli strati della rete ottenendo una predizione. La predizione viene poi confrontata con l’output target, calcolando attraverso la funzione di loss l’<strong>errore di predizione. </strong>Sulla base della perdita ottenuta, ad ogni iterazione, andremo a propagare in <em>backward </em>l’errore effettuando l’aggiornamento dei pesi.</p><p>Teoricamente…il processo di training termina quando sono stati determinati i valori di W tali per cui l’errore di predizione è il più basso possibile, o meglio, è stato raggiunto il <strong>minimo globale </strong>(<em>ottimo</em>) della funzione di loss L.</p><p>In realtà… per evitare l’overfitting, siamo alla ricerca di un Trade-off tra un basso valore di loss sul set di train ed un opportuno valore di accuratezza sul test di validazione.</p><h3>2. Backward pass</h3><p><strong>2.1 Regola di aggiornamento - Delta rule</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*dEKzCoU2DQt15WXO.jpg" /></figure><p>Possiamo pensare al problema di <em>ottimizzazione</em> come ad un uomo che cammina in una valle in cui intorno ci sono delle montagne. Ognuno dei punti di questa valle corrisponde ad un certo valore di Loss calcolata in funzione dei pesi <em>wi</em> e del termine di bias<em> bi</em>. L’obiettivo del nostro amico è quello di trovare un percorso per arrivare in pianura. Per raggiungere il suo scopo dovrà percorrere una direzione di discesa. Matematicamente la direzione di discesa è data dal <strong>gradiente negativo</strong>. Quest’ultimo è il vettore delle derivate parziali della funzione di <em>Loss</em> lungo ogni dimensione <em>wi </em>e<em> bi</em>. Formalmente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZUhKtWap4C4dbKNblIppw.png" /><figcaption>Formula (3)</figcaption></figure><p>in cui con <em>n </em>indichiamo il numero massimo di termini di bias<em> (uno per ogni neurone) </em>mentre con <em>m </em>il numero massimo di pesi<em>. </em>Trovata la direzione, vediamo come compiere i vari passi. Date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*3rjPY-AHlO9qmu1UwAGkAA.png" /><figcaption>Formula (4)</figcaption></figure><p>ad ogni iterazione la modifica dei pesi e del bias è determinata da <em>∆w </em>e <em>∆b </em>espressi come il prodotto tra il valore di learning rate (<em>η</em>) e il gradiente negativo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*z9A7GsamudL7AlhDuHS4cw.png" /><figcaption>Formula (5)</figcaption></figure><p>Riscrivendo la Formula (4) otteniamo la regola di aggiornamento:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*hRa4t3DYHy2sTAmjl2KNLQ.png" /><figcaption>Formula (6)</figcaption></figure><blockquote><strong>Gradiente</strong>:</blockquote><blockquote>Data la funzione L differenziabile in w1 … wm, b1, …, bn il suo gradiente esprime la direzione di crescita. Anteponendo il segno negativo siamo in grado di ottenere la direzione di discesa della stessa.</blockquote><p><strong>2.2 Dipendenza semplice e multipla</strong></p><p>Bene, la Formula (3) consente di trovare la direzione di discesa ma.. come calcolare le derivate?</p><p>La funzione di Loss ha come parametro <em>f(x,W)</em>. Basiamo le nostre analisi considerando la rete in Fig.4. Ogni neurone presenta un’attivazione <em>sigmoidea </em>e<em> </em>per semplicità di trattazione, poniamo il termine bias a zero per ogni neurone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*PWqQi_CtP_4ooPm1t1WD3w.png" /><figcaption>Fig.4: Rappresentazione di una Multi Layers Perceptrons (MLPs) con due layers nascosti ed uno di output</figcaption></figure><p>La funzione <em>f </em>che verrà adattata sui nostri dati<em> (chiamiamolo modello) </em>può essere riscritta in questo modo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWCMpRrjvHgCEjI7Cg3Peg.png" /><figcaption>Formula (7)</figcaption></figure><p><em>f </em>è una funzione composta, o meglio, al suo interno abbiamo ulteriori funzioni (<em>in tal caso sigmoidee</em>) e così ricorsivamente (<em>le funzioni sigmoidee saranno composte da altre funzioni di attivazione</em>)<em>. </em>Per il calcolo delle derivate, possiamo<em> </em>ricorrere<em> </em>all&#39;utilizzo della <strong>regola della catena </strong>(<em>chain rule</em>) [in Appendice]. Prima di applicarla, scomponiamo la Formula (7) in tutte le sue componenti costruendo il computational graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjANeDk4OvhS-wgEPryzQg.png" /></figure><p>Cerchiamo di muoverci al suo interno calcolando le derivate. Di seguito verranno presentati due esempi: (i) dipendenza singola (ii) dipendenza multipla.</p><ul><li><em>∂</em><strong>L / </strong><em>∂</em><strong>w9 </strong><em>(dipendenza singola)</em></li></ul><p>Proviamo a calcolare la derivata della Loss rispetto <em>w9</em>. Le parti interessate del computational graph sono:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*gqoF3Oc5RWL09wcC6oD6cg.png" /></figure><p>La dipendenza che ci troviamo a dover risolvere è <em>singola</em>, poichè:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*dep9rFo5_pY5kwRaYF25TA.png" /></figure><p>o meglio, volendo fare un confronto con quanto descritto in Appendice abbiamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*HyxdUuzga-27X-w3RjcHPw.png" /></figure><p>Bene, a questo punto, applichiamo la regola:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*xkjNXFPymutiDJprq6eZkQ.png" /></figure><ul><li><em>∂</em><strong>L / </strong><em>∂</em><strong>w1 </strong><em>(dipendenza multipla)</em></li></ul><p>Proviamo a calcolare la derivata rispetto a <em>w1</em>. Le parti interessate del computational graph sono:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eKsLLc6M5xdvdq2YubTDQ.png" /></figure><p>In questo caso le cose si complicano un pò. Andiamo per step.</p><p><strong>step 1</strong></p><p>Prima di tutto dobbiamo raggiungere il blocco<em> z1</em> del layer <em>(3)</em>. Il calcolo non differisce molto da quello precedente. Vediamolo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkVxiUnMeJJQi-SzjEP6zg.png" /></figure><p><strong>step 2</strong></p><p>A questo punto dobbiamo calcolare la derivata di <em>∂z1</em> layer (3)<em> </em>ma.. rispetto a cosa? Ricordiamo che vogliamo raggiungere l’attivazione <em>a1</em> del layer (1)<em>.</em> Zoomiamo il computational graph sulla zona di interesse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNWTsqygMYRDejLzyNXO5w.png" /></figure><p>L’attivazione <em>a1 </em>del layer (1) è input delle due somme lineari<em> z1</em> e <em>z2 </em>entrambe del layer (2). Le rispettive attivazioni verranno sommate in<em> z1</em> del layer (3). Per cui, siccome l’attivazione <em>a1</em> del layer (1) è presente in ambedue i percorsi dobbiamo effettuare le derivate su ambedue. La dipendenza che ci troviamo a risolvere è <em>multipla.</em> In particolare, volendo fare un confronto con quanto detto in Appendice, possiamo dire:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*_8EDC71jfMRAg2ghE4-0uw.png" /></figure><p>Bene, a questo punto, applichiamo la regola:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qb4Wdhb056BkAcKoKd00oA.png" /></figure><p><strong>step 3</strong></p><p>Arrivati a questo punto manca l’ultimo step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwCeBedBJt3zYeAnGUJNyg.png" /></figure><p><strong>uniamo il tutto..</strong></p><p>Riscrivendo formalmente quanto detto otteniamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPsCDgti_qpKCezOyIjjTg.png" /></figure><p><strong>2.3 Calcolo del gradiente</strong></p><p>Dopo aver esaminato i due tipi di dipendenza la stessa analisi può essere condotta per ogni peso <em>wi </em>della MLPs. Posto di seguito le derivate particolarizzate per la MLPs di Fig.4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*LL8xzYea47QfAwn_" /></figure><p>con:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*kDTyhPaVSoV5MjDqNv44xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg-Q2I4vBzBIkA-6WJM0Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQmJBFCRYuQfh-wRyji6Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ttirtkv_fRKrQ41je0XDng.png" /></figure><h3>Appendice</h3><ol><li><strong>Regola della catena</strong></li></ol><p><strong>Singola dipendenza</strong></p><p>Sia <em>f</em> funzione composta da <em>g(x)</em> nella forma<em>: f(g(x)). </em>La derivata di<em> f</em> rispetto ad <em>x</em> può essere ottenuta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*qWvcLA4vh7CcD9XMzkArBQ.png" /></figure><p>Vediamola attraverso il computational graph della funzione <em>f(g(x)):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ZAOeSAdJuTYSAeJ1u4wB0Q.png" /></figure><p><strong>Multi dipendenza</strong></p><p>Sia <em>f</em> funzione composta da <em>g(x) e h(x) </em>nella forma<em>: f(g(x), h(x)). </em>La derivata di<em> f</em> rispetto ad x può essere ottenuta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*63N-wyxQQFKIgyOpp37S2A.png" /></figure><p>Anche in questo caso, analizziamo il computational graph della funzione <em>f(g(x), h(x)):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm_Y5rqCAvcALOxV6yxEog.png" /></figure><h3><strong>References</strong></h3><ul><li><a href="https://www.youtube.com/watch?v=h7iBpEHGVNc">StanfordOnline lecture 3| Loss Functions and Optimization</a></li><li><a href="https://www.youtube.com/watch?v=d14TUNcbn1k">StanfordOnline lecture 4 | Introduction to Neural Networks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c0c900fbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perché dovrei fidarmi di te? (LIME)]]></title>
            <link>https://cannydatascience.medium.com/perch%C3%A9-dovrei-fidarmi-di-te-lime-d0e5a287d0a2?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e5a287d0a2</guid>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[lime]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[explanation]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:36:56 GMT</pubDate>
            <atom:updated>2020-09-30T20:49:37.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IESN9lI6o964og2" /><figcaption>Photo by <a href="https://unsplash.com/@timswaanphotography?utm_source=medium&amp;utm_medium=referral">Tim Swaan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduzione</h3><p>Nello <a href="https://medium.com/@cannydatascience/perch%C3%A9-dovrei-fidarmi-di-te-e5c45a81cbab">scorso articolo</a>, abbiamo visto quanto sia importante capire quali features contribuiscono in maniera significativa alle scelte effettuate da parte del nostro modello. In particolare abbiamo esplorato i metodi CAM e GradCAM e applicato quest’ultimo ad un semplice problema di classificazione.</p><p>Nel seguito continuiamo la fase di debug della nostra Convolutional Neural Netework esplorando LIME.</p><h3><em>Explanation method</em></h3><p>Secondo gli autori [<a href="#baba">1</a>], un buon <em>explanation method</em> dovrebbe avere le seguenti caratteristiche:</p><ul><li><strong>interpretability: </strong>supponiamo che un singolo esempio fornito al nostro modello sia costituito da milioni o miliardi di features. È impensabile che l’utente riesca a capire quali features influiscono di più sul risultato. Per cui, un buon <em>explanation method </em>deve essere in grado di fornire una comprensione qualitativa tra le variabili di input e la risposta fornita dal nostro modello.</li><li><strong>local fidelity: </strong>per spiegare questo concetto consideriamo, per semplicità di trattazione, una Deep Neural Netwok (DNN). Il modello, o meglio, la funzione matematica<em> f(X,W) </em>generata durante la fase di training sarà sicuramente molto molto complessa, pesiamo ad esempio al numero dei pesi o al grado del polinomio<em>. </em>Questo è inevitabile poiché ci concentriamo sulla totalità<strong> </strong>(<strong>globalità</strong>)<strong> </strong>delle features. L’idea è quella di <strong>approssimare </strong>il nostro complesso modello con un modello più semplice costruito su perturbazioni dell’input X (<strong>località </strong>rispetto l’input). <strong>Questo implica che avremo un modello semplificato diverso per ogni input.</strong> Vedremo più avanti cosa si intende.</li><li><strong>model agnostic</strong>: un buon <em>explanation method </em>deve essere in grado di spiegare qualsiasi modello, o meglio, trattare il modello complesso come una <em>black-box.</em></li></ul><h3><strong>LIME</strong></h3><p>LIME acronimo di <strong>L</strong>ocal <strong>I</strong>nterpretable <strong>M</strong>odel-Agnostic <strong>E</strong>xplanations racchiude i concetti appena citati. In Fig.1 è rappresentato il suo comportamento.</p><p>In blu/rosa è rappresentata la funzione<em> f </em>del<em> </em>modello complesso non noto a LIME (<em>model agnostic</em>). La croce rossa in grassetto è il campione <em>C </em>che vogliamo spiegare. Quest’ultimo viene perturbato, generando così le features sulla quale costruiremo (<em>local fidelity</em>) il modello semplificato <em>g </em>che in figura rappresentiamo con la linea tratteggiata<em>. </em>Non tutte le perturbazioni assumono la stessa importanza. Andremo ad adottare una fase di weighted per le singole perturbazioni concentrandoci solo su quelle “più vicine” al campione C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZ1m147rrquhhv_cHX0B2A.png" /><figcaption>Fig.1: Rappresentazione generica del funzionamento di LIME</figcaption></figure><h3><strong>Un pò di formalismo</strong></h3><h4><strong>Dominio di interesse</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*uGNGmqxHda0Ej4K4KrML7g.png" /><figcaption>Fig.2: Rappresentazione (a) immagine originale (b) suddivisione in regioni di similarità dell’immagine originale (c) immagine perturbata ottenuta scegliendo randomicamente quali super-pixel nascondere</figcaption></figure><p>Concentriamo le nostre analisi considerando come dominio di interesse le immagini. Come si può ottenere un’immagine perturbata? Prima di dare una risposta, è bene introdurre il concetto di super-pixel. Un super-pixel (SP) è costituito da un gruppo di pixel che hanno intensità <strong>simile</strong>. Un’esempio è presentato in Fig.2 (b). L’immagine di partenza viene divisa in regioni di similarità. Identificando ogni regione con <em>SPi</em>, la Fig.2 (b) può essere rappresentata attraverso il vettore <em>x’ </em>in cui ogni <em>SPi </em>assume come valore 1 (<em>il super-pixel i-esimo è visibile</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aixwtapcw1XzbUWf2FVRaw.png" /><figcaption>Interpretazione ottenuta grazie alla lettura di<a href="#51b1"> LIME by Kai-Shen Tseng [3]</a></figcaption></figure><p>Scegliendo randomicamente quale <em>SPi</em> mostrare e quale nascondere otteniamo un’immagine perturbata <em>z </em>Fig.3 (c). L’immagine <em>z </em>può essere<em> </em>rappresentata attraverso il vettore <em>z’ </em>in cui specifichiamo<em> </em>se il <em>SPi-esimo </em>è presente o no.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuBItRG7Mbedv-vcBeSUvg.png" /><figcaption>Interpretazione ottenuta grazie alla lettura di<a href="#51b1"> LIME by Kai-Shen Tseng [3]</a></figcaption></figure><p>Formalizzando quanto detto abbiamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*4-JueoShRfbMomSSP0cQew.png" /></figure><blockquote><strong>Attenzione</strong>: è importante notare la distinzione tra<strong> immagine </strong>(x e z) e rappresentazione attraverso <strong>vettore</strong> di SP (x’ e z’)</blockquote><h4><strong>Modello semplificato</strong></h4><p>Consideriamo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*GCvgWiQpuuayvJXIPkBMpg.png" /></figure><p>Nella costruzione del modello semplificato <em>g, </em>LIME minimizza la seguente funzione obiettivo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*AueEoQD5T95C7YNx-18IRg.png" /></figure><p>in cui <em>L(f,g,</em>π<em>) e Ω(g) </em>indicano rispettivamente la misura di loss e il termine di regolarizzazione.<em> </em>La formula (1) è<strong> generica</strong> e può essere utilizzata con <strong>qualsiasi interpretazione di G</strong>.</p><p>Nel seguito la particolarizzeremo trattando modelli lineari della forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*zQNva-a2K5I6ywHmxlTtFQ.png" /></figure><ul><li><strong><em>L(f,g,</em>π<em>) </em>per modelli lineari</strong></li></ul><p>Il termine <em>L(f,g,</em><strong><em>π</em></strong><em>)</em> definisce una misura di perdita (<em>loss</em>), in particolare usiamo una <strong>weighted square loss</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*EZxXM4Jp8Ut87N5BXzMy0w.png" /></figure><p>in cui:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15VbyJufI09IaJb30TxYYw.png" /></figure><p>Esaminiamo il residuo. Sappiamo che l’approccio <strong>linear model </strong>è un’approccio <strong>supervisionato. </strong>In questo caso il valore <em>f(z)</em> è il valore atteso (<em>label</em>). Ciò che cerchiamo di fare è di fittare un iperpiano formula <em>(2</em>)<em> </em>nella dimensione <em>d’</em> (<em>per cui nella dimensione dei super-pixel</em>), minimizzando la distanza tra il valore atteso e la predizione <em>g(z’)</em>.</p><blockquote><strong>Attenzione:</strong> Come accennato è importante distinguere immagine e vettore. Notiamo che l’immagine z è l’input del modello f che nel nostro caso è una CNN, al contrario, il vettore z’ è utilizzato come input per il modello lineare in cui <strong>ogni super-pixel costituisce una feature</strong>.</blockquote><p>Ovviamente il residuo non assume sempre la stessa importanza. Infatti, viene <strong>pesata</strong> considerando la misura di prossimità <strong>π</strong> tra <em>x</em> e <em>z, </em>cioè tra l’immagine originale e la sua perturbazione. La misura di prossimità è data da:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/0*7YXPfJmVJw_fzcKy" /></figure><p>in cui D è la <a href="#f932">L2 distance</a>.</p><ul><li><strong><em>Ω(g) </em>per modelli lineari</strong></li></ul><p>È invece la complessità del modello <em>g</em>. Nella funzione obiettivo è utilizzata come termine di regolarizzazione. Più il modello <em>g </em>è complesso più la funzione obiettivo Ɛ(x)<strong> </strong>verrà penalizzata. Per un modello lineare la complessità è rappresentata dal numero di pesi non nulli. L’idea è quella di avere il <strong>maggior numero</strong> di pesi nulli possibile. In questo, per i modelli di regressione, ci viene in aiuto LASSO.</p><p>LASSO viene utilizzato per problemi di regressione al fine di effettuare:</p><ul><li>L1 regularization</li><li>Features selection</li></ul><p>Matematicamente, considerando la funzione di perdita descritta dalla formula (3), sottopone quest’ultima al vincolo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*zOiYqtk8jH5ZUkpWlT4JjA.png" /></figure><p>in cui <em>w sono i </em>predittori/pesi mentre S è l’upper bound. Graficamente il vincolo descrive una regione “quadrata” (<em>dipende ovviamente da quanti predittori abbiamo, se ne abbiamo due un quadrato, tre un cubo e cosi via</em>) dovuto alla presenza del <em>valore assoluto</em>. La minimizzazione della formula (1) costringerà la funzione di perdita descritta in formula (2) a toccare uno degli spigoli del vincolo azzerando uno o più predittori <em>w</em>, o meglio <strong>riducendo</strong> il <strong>numero dei pesi</strong> e quindi la <strong>complessità del modello lineare</strong>. In Fig.3, mostriamo quanto appena detto, per semplicità di rappresentazione viene graficato un problema bivariato con quindi due soli predittori. Possiamo notare come il processo di minimizzazione porta il predittore <em>w1</em> ad assumere un valore nullo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*dz8yXyU0m_0iZjfCRvo1EQ.png" /><figcaption>Fig.3: In verde è rappresentato il vincolo a cui è soggetto la funzione di perdita. Quest’ultime è rappresentata in rosso. Il punto di intersezione tra i due durante la fase di minimizzazione avviene su uno o più assi, annullando cosi i relativi predittori. In figura w1 assumerà nel modello un valore nullo.</figcaption></figure><p><strong>Riassumendo</strong></p><p>Il modello semplificato <em>g</em> nel caso di <strong>modelli lineari</strong>, può essere descritto matematicamente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqeQ4eWiBUMVzikbWY6r9Q.png" /></figure><p><strong>Ma…</strong></p><p>A cosa serve il modello semplificato?</p><p>Costruendo il modello semplificato sulle perturbazioni siamo in grado di capire quale <strong>combinazione</strong> di super-pixel (<em>nel nostro caso</em>) ha una <strong>probabilità maggiore </strong>di predizione <strong>sulla classe scelta</strong>. Questo rappresenterà la nostra spiegazione.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avblA_PFb4dlH8AtyIQezg.png" /><figcaption>Fig.3: Spiegazione dell’immagine Fig.1 (a). Interpretazione ottenuta modificando lo schema: <a href="https://www.oreilly.com/content/introduction-to-local-interpretable-model-agnostic-explanations-lime/">link</a></figcaption></figure><h3><strong>Algoritmo</strong></h3><p>Di seguito è presentato in formato pseudo-codice i passi seguiti da LIME per ottenere la spiegazione, in questo caso, della nostra immagine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*RBEybhLzv15AePWrY5RPqA.png" /></figure><p>Come requisiti abbiamo bisogno di:</p><ul><li>Il modello complesso <em>f </em>e il numero <em>N</em> di perturbazioni desiderate</li><li>L’immagine che vogliamo spiegare <em>x</em> e la sua rappresentazione in super-pixel <em>x’</em></li><li>Funzione di prossimità <strong>π </strong>(L1 distance per immagini)</li></ul><p>Prima di Iniziare settiamo l’insieme <em>Z</em> all&#39;interno della quale andremo a conservare tutte le informazioni relative alle perturbazioni dell’immagine <em>x:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*FgwwHiu8CRLSpZ0rOZ93Sg.png" /></figure><p>Successivamente andiamo a generare randomicamente le <em>N</em> perturbazioni considerando il vettore di super-pixel <em>x’. </em>Ottenuto<em> </em>Il vettore z’ e calcolate la relativa misura di prossimità <strong>π </strong>e il valore <em>f(z) </em>andiamo ad eseguire un aggiornamento dell’insieme Z attraverso un<em> append:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*woIZlidXgw2p00D5MZ1Vow.png" /></figure><p>Le informazioni cosi ottenute vengono utilizzate per fittare il modello di regressione lineare LASSO:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*Cs6wF5eIzCN98oLZRBIzAw.png" /></figure><h3>Più soggetti</h3><p>Nei paragrafi precedenti ci siamo concentrati sull&#39;analisi di un’immagine con un solo soggetto (<em>cane</em>). È interessante esplorare anche il caso in cui ci siano più soggetti. Nell&#39;articolo [1] gli autori considerano la seguente immagine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*kui9J-rU2rUbDfP_UL9rXQ.png" /></figure><p>passandola in input alla rete Google Inception le <strong>tre top </strong>classi predette sono:</p><ul><li><em>Electric guitar </em>con una probabilità del 32%</li><li><em>Acoustic guitar</em> con una probabilità del 24%</li><li><em>Labrador </em>con una probabilità del 21%</li></ul><p>LIME, effettuando un’analisi per classe, consente di capire quali regione dell’immagine sono coinvolte nelle classificazioni delle classi di cui sopra:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*HOCS40UPpFCdXbs2TaYaGg.png" /></figure><h3><strong>Code</strong></h3><p>La documentazione relativa all&#39;utilizzo di LIME è disponibile al seguente repository: <a href="https://github.com/marcotcr/lime">https://github.com/marcotcr/lime</a></p><h3><strong>Appendice</strong></h3><p><strong>L2 distance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/0*OefNGIn_tR7eYarP" /></figure><p>Con<strong> </strong><em>I</em><strong><em> </em></strong>si identifica l’intensità del pixel<em> p </em>dell’immagine 1 e 2 rispettivamente.</p><h3><strong>References</strong></h3><p>[1] <a href="https://arxiv.org/abs/1602.04938">“Why Should I Trust You?” Explaining the Predictions of Any Classifier</a></p><p>[2] <a href="https://medium.com/@kstseng/lime-local-interpretable-model-agnostic-explanation-%E6%8A%80%E8%A1%93%E4%BB%8B%E7%B4%B9-a67b6c34c3f8">LIME — Local Interpretable Model-Agnostic Explanation Kai-Shen Tseng</a></p><p>[3] <a href="https://www.oreilly.com/content/introduction-to-local-interpretable-model-agnostic-explanations-lime/">Local Interpretable Model-Agnostic Explanations (LIME): An Introduction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e5a287d0a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perché dovrei fidarmi di te?]]></title>
            <link>https://cannydatascience.medium.com/perch%C3%A9-dovrei-fidarmi-di-te-e5c45a81cbab?source=rss-2068ede1c367------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c45a81cbab</guid>
            <category><![CDATA[visualization-nets]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[grad-cam]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Giuseppe Pio Cannata]]></dc:creator>
            <pubDate>Sun, 10 May 2020 17:24:57 GMT</pubDate>
            <atom:updated>2020-09-30T20:53:14.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*09_5WK4LLe3Hoi0F" /><figcaption>Photo by <a href="https://unsplash.com/@imatbagjagumilar?utm_source=medium&amp;utm_medium=referral">Imat Bagja Gumilar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduzione</strong></h3><p>Spesso una Convolutional Neural Network (CNN) è vista come una scatola nera, o meglio, come un qualcosa che data un’immagine di input <em>X</em>, attraverso una funzione del tipo <em>f(X,W)</em>, riesce a mappare un relativo output<em> y</em>. Durante la fase di <em>training</em> accade che otteniamo dei valori elevati circa la metrica di utilizzo (<em>precision, recall ecc..</em>), ma non sappiamo su quali features dell’immagine la rete basa le sue scelte. Uno dei metodi che consentono di rispondere a questo problema è Gradient-weighted Class Activation Mapping (Grad-CAM). Quest’ultimo restituisce una mappa di probabilità in cui le regioni a probabilità maggiore sono quelle che incido sulle scelte effettuate dal nostro modello.</p><h3><strong>Cosa sta guardando la rete?</strong></h3><p>Per capire l’importanza di trovare una risposta a questa domanda facciamo questo esempio. Supponiamo che il mio amico mi chieda di “costruire” una rete neurale per classificare immagini contenenti cani e immagini contenenti gatti (si, è un pò un amante degli animali). Supponiamo di aver allenato la nostra rete neurale ottenendo delle buone performance: 99% di accuracy in fase di test. Armato di una buona dose di orgoglio e felicità per aver risolto il task utilizzo il modello in produzione. Montiamo il tutto su una Raspberry e iniziamo a mostrare i vari frame alla rete. Eseguiamo l’esperimento in casa (beh? che problema c’è?).</p><p>“Inspiegabilmente” il modello sbaglia la classificazione. Sembra non riuscire a riconoscere la classe <em>cane</em>. Ferito nel profondo, cerco di capire il problema guardando gli esempi dati in pasto durante la fase di training. Dopo un’attenta analisi mi rendo conto che le immagini erano tutte all&#39;aperto e in quelle appartenenti alla classe <em>cane</em>, come sfondo c’è sempre del verde.</p><blockquote>Forse la rete non riconosce la presenza di un cane all&#39;interno dell’immagine, ma basa le sue decisioni per questa classe, sulla presenza o meno di verde come background</blockquote><p>Per validare la mia tesi, proviamo il modello in giardino. Funziona!!!</p><h3>Metodi</h3><p>L’esempio appena presentato, per quanto semplice, evidenzia la necessità di capire a cosa attribuire un valore elevato di classificazione. I metodi presentati di seguito sono solo alcuni che possiamo utilizzare per fare debug su una rete.</p><h3>Class Activation Mapping (CAM)</h3><p>CAM acronimo di <strong>Class Activation Mapping,</strong> ha come scopo<strong> </strong>quello di produrre una <strong>mappa di localizzazione</strong> che consente di visualizzare le regioni dell’immagine sui cui la rete base le decisione <em>(dove guarda la rete)</em>. In Fig.1 notiamo che per classificare questa immagine come appartenente alla classe <em>cane</em>, la rete si concentra sulle features relative al volto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*KlLwQdL6YjkerIggO5uZMQ.png" /><figcaption>Fig.1: Mappa di localizzazione ottenuta su immagine RGB avente come soggetto un cane</figcaption></figure><p>Prima di vedere come ottenere la mappa di localizzazione scendiamo nello specifico ed esaminiamo il processo di classificazione. Consideriamo la rete presentata in Fig.2 in cui abbiamo: (i) layer convoluzionali (ii) Global Average Pooling (iii) Softmax</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*pA8SM64z5VMKKSEf9v1P2A.png" /><figcaption>Fig.2: Semplice CNN con tre layer convoluzionali un global average pooling e uno di softmax</figcaption></figure><p>La probabilità <em>y</em> di appartenenza ad una data classe<em> c (nel nostro caso c si riferisce alla classe cane) </em>può essere espressa matematicamente in questo modo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*cRqoGHV6aqrew_aH" /></figure><p>Concentriamoci sull&#39;ultimo strato convoluzionale e chiamiamo il blocco di features maps ottenuto A^k con ogni k-esima features map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*75o6FD2mSsS8vHFCDF927g.png" /></figure><p>in cui con <em>u </em>e<em> v </em>indichiamo rispettivamente l’altezza e la larghezza della features map. Volendo riassumere, le dimensioni del blocco A^k sono (u,v,k). Il blocco viene passato al layer di GAP che applicherà il Global Average Pooling su di esso ottenendo così un tensore di output di dimensioni (1,1,k). A questo punto, ogni feature diventa input dei neuroni presenti nell&#39;ultimo layer su cui andremo ad applicare una somma pesata:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*NxYBGTKXosWYRQnSgnGPVg.png" /></figure><p>I valori del vettore <em>W1 … Wk </em>per la classe<em> c </em>è<em> </em>appreso durante la fase di <em>training</em>.</p><p>A questo punto, per produrre una mappa di localizzazione <em>L</em> relativa alla classe di interesse <em>c</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*2J_QGNSgDWUdF4yRjfuEiw.png" /></figure><p>CAM effettua una somma pesata tra i <em>W1 … Wk </em>e il blocco di features maps A^K:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ygg7OLe2LEWq0bqus0pbNQ.png" /></figure><p><strong>Cons</strong></p><p>Un limite notevole di questa tecnica è la struttura della rete. Infatti CAM funziona solamente su architetture che hanno Global Average Pooling (GAP) come layer prima del Dense che si occupa della classificazione:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*Kg2EJ2pVg2SZ-74dABG3Tw.png" /></figure><p>In caso contrario, se abbiamo dei Fully Connected prima del Softmax, questi devono essere sostituiti con un GAP e la rete riaddestrata poichè abbiamo bisongo di apprende i pesi <em>W1 … Wk </em>per calcolare la mappa di localizzazione.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sXl_0BvONLe_g39pRjvqSQ.png" /></figure><h3><strong>Gradient-weighted Class Activation Mapping (Grad-CAM)</strong></h3><p>Grad-CAM acronimo di <strong>Gradient-weighted Class Activation Mapping</strong> è una tecnica che ci viene in aiuto quando nella nostra architettura di rete non abbiamo un Global Average Pooling. Per ottenere la mappa di localizzazione <em>L</em> relativa ad una classe <em>c:</em></p><ul><li>Computiamo il gradiente di y^c rispetto alle features maps A^k del layer convoluzionale scelto. Sul gradiente ottenuto applichiamo il Global Average Pooling ottenendo il vettore di pesi <em>a:</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/0*h48Pabk69j0gdML-" /></figure><ul><li>Successivamente, andiamo ad eseguire una somma pesata tra il vettore <em>a</em> appena calcolato e le features maps A^k del layer scelto. Il tutto viene poi processato dalla ReLU che azzera i valori negativi del gradiente ottenendo cosi la mappa di localizzazione:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*SoLgcGnrfnj1VaG0MTNU3A.png" /></figure><p><strong>Pro</strong></p><p>A differenza di CAM non siamo vincolati ad utilizzare esclusivamente le features maps dell’ultimo strato convoluzionale, ma possiamo concentrare le nostra analisi per ogni strato conv della nostra rete.</p><h3><strong>Code</strong></h3><p>L’implementazione di Grad-CAM mostrata di seguito rispecchia i passaggi precedentemente affrontati:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7d61ddad6342bf5ae52114e369a4089/href">https://medium.com/media/d7d61ddad6342bf5ae52114e369a4089/href</a></iframe><p>Per semplicità utilizzo VGG16 come rete analizzando l’immagine mostrata in Fig.3. La classe “boxer” in VGG16 corrisponde al 242 neurone dello strato Softmax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*1l9kozh0RYN_ka7AUlGx7w.png" /><figcaption>Fig.3: Immagine di boxer utilizzata per creare la mappa di localizzazione</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c08fbcb2a1c9681f90429b897170e8/href">https://medium.com/media/50c08fbcb2a1c9681f90429b897170e8/href</a></iframe><h3>Conclusioni</h3><p>In questa prima parte abbiamo visto Grad-CAM come tecnica per ottenere mappe di localizzazione e effettuare un primo debug della rete neurale. Nel prossimo articolo vorrei esplorare LIME.</p><p><strong>Nota:</strong> il titolo di questo articolo è tratto dal paper di Marco Tulio Ribeiro, Sameer Singh, Carlos Guestrin: <a href="https://www.kdd.org/kdd2016/papers/files/rfp0573-ribeiroA.pdf">“Why Should I Trust You?” Explaining the Predictions of Any Classifier</a></p><p><strong>P.S:</strong> In realtà non ho allenato una rete per riconoscere cani e gatti. Anzi, forse se lo avessi fatto non avrei utilizzato Accuracy xD</p><h3><strong>References</strong></h3><ul><li><a href="https://arxiv.org/abs/1610.02391">Grad-CAM: Why did you say that? Visual Explanations from Deep Networks via Gradient-based Localization</a></li><li>Parte del<a href="https://github.com/eclique/keras-gradcam/blob/master/gradcam_vgg.ipynb"> Code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c45a81cbab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>