<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Cristobal Eyzaguirre</title>
    <description>Cristobals&apos;s blog,use Jekyll and github pages.</description>
    <link>https://ceyzaguirre4.github.io/</link>
    <atom:link href="https://ceyzaguirre4.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Tue, 21 Apr 2026 21:04:35 +0000</pubDate>
    <lastBuildDate>Tue, 21 Apr 2026 21:04:35 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>Differentiable Adaptive Computation Time for Visual Reasoning (CVPR 2020)</title>
        <description>&lt;div style=&quot;text-align:center&quot;&gt;&lt;em&gt;(if answer is ready: stop wasting computation)&lt;/em&gt;&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;On tasks where the complexity needed to answer varies it makes intuitive sense that model complexity should vary accordingly.
The ability to adaptively allocate more resources to difficult tasks is one that all humans possess and is evident in the increased requirements needed for complex mathematics compared to simple everyday tasks.
This post introduces DACT &lt;a href=&quot;http://arxiv.org/abs/2004.12770&quot;&gt;[0]&lt;/a&gt;, a new algorithm for achieving adaptive computation time that, unlike existing approaches, is fully differentiable.
We put it to the test on Visual Reasoning datasets and find that our models learns to actively adapt their architectures according, balancing high accuracy with as-little-as-possible computation.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://arxiv.org/abs/2004.12770&quot;&gt;LINK TO ARXIV [0]&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/ceyzaguirre4/DACT-MAC&quot;&gt;LINK TO CODE&lt;/a&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-setting-visual-question-answering&quot;&gt;The Setting: Visual Question Answering&lt;/h2&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/tennis1.png&quot; alt=&quot;How many balls is the kid holding?&quot; /&gt;&lt;/th&gt;
                
                  &lt;th style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/th&gt;
                
              
            
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/tennis2.png&quot; alt=&quot;How many birds is he holding?&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;How many balls is the kid holding?&lt;/em&gt;&lt;/td&gt;
                
                  &lt;td style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/td&gt;
                
              
            
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;How many birds is he holding?&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;Visual Question Answering (VQA) &lt;a href=&quot;https://visualqa.org&quot;&gt;[1]&lt;/a&gt; is a task where, for a given input image, question pair, we expect the model to return an answer.
The difficulty of the task lies in the openness for both the question and image: because any image or plain-text question are valid expecting the model to output convincing answers can be seen as a more general Turing-test.
These datasets pose challenging natural language questions about images whose solution requires the use of perceptual abilities, such as recognizing objects or attributes, identifying spatial relations, or implementing high-level capabilities like counting.
For example, in the images above we see examples of two very similar (counting) questions for images from the Visual Genome dataset &lt;a href=&quot;https://visualgenome.org&quot;&gt;[2]&lt;/a&gt; that necessitate a broad understanding of the relation holding and a general purpose counting algorithm.&lt;/p&gt;

&lt;!--
![](/images/dact/clevr_eg.png)
*Examples of questions in the CLEVR dataset that show a significant variation in the number of reasoning steps that are needed to answer them correctly.* --&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/clevr_eg.png&quot; alt=&quot;Examples of questions in the CLEVR dataset that show a significant variation in the number of reasoning steps that are needed to answer them correctly.&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;Examples of questions in the CLEVR dataset that show a significant variation in the number of reasoning steps that are needed to answer them correctly.&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;In open tasks such as this we find that instances entail diverse levels of complexity as both questions and images can be arbitrarily simple or difficult.
Two examples from the CLEVR dataset &lt;a href=&quot;http://cs.stanford.edu/people/jcjohns/clevr/&quot;&gt;[3]&lt;/a&gt; are shown above.
Even in the very restricted subset of all possible images and questions included in this dataset (vocabulary of 28 words, generated images of the same objects) we find significant variation in complexity.
Specifically, while the question of the first example involves just the identification of a specific attribute from a specific object, the second question requires the identification and comparative analysis of several attributes from several objects.
We argue that dealing with this openness is paramount for more general intelligence and propose Adaptive Computation Time algorithms such as ACT &lt;a href=&quot;https://arxiv.org/abs/1603.08983&quot;&gt;[4]&lt;/a&gt; as possible solutions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;existing-adaptive-approaches&quot;&gt;Existing Adaptive Approaches&lt;/h2&gt;

&lt;h3 id=&quot;1-modular-networks&quot;&gt;1. Modular Networks&lt;/h3&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/modules_spec.png&quot; alt=&quot;Specialized Modules&quot; /&gt;&lt;/th&gt;
                
                  &lt;th style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/th&gt;
                
              
            
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/modules_gen.png&quot; alt=&quot;General Purpose Module&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;Specialized Modules&lt;/em&gt;&lt;/td&gt;
                
                  &lt;td style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/td&gt;
                
              
            
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;General Purpose Module&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;We consider modular networks those where modules are combined from a collection processing modules.
Here we distinguish between two kinds:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;those in which a controller selects the appropriate specialized module (eg. IEP &lt;a href=&quot;https://arxiv.org/abs/1705.03633&quot;&gt;[5]&lt;/a&gt; show in figure).&lt;/li&gt;
  &lt;li&gt;those where a single general purpose module is used repeatedly for a fixed number of times (eg. MAC &lt;a href=&quot;https://arxiv.org/abs/1803.03067&quot;&gt;[6]&lt;/a&gt; shown in figure).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Only the case of specialized modules is adaptive, but the generation of the sequences requires costly supervision or elaborate reinforcement learning training schemes.&lt;/p&gt;

&lt;p&gt;The second case (general purpose modules) always executes the same module a fixed number of times, so no module selection training is needed.
However, this approach is not adaptive as the processing pipeline is always the same.
In our work, we build upon one of these networks by using DACT to adaptively select the horizon of the computational pipeline (instead of having it as a fixed hyper-parameter).&lt;/p&gt;

&lt;h3 id=&quot;2-act&quot;&gt;2. ACT&lt;/h3&gt;

&lt;p&gt;An algorithm for adaptive computation in neural networks already existed: ACT.
I’ve already written a detailed explanation of how and why it works in a &lt;a href=&quot;/ACT&quot;&gt;previous post&lt;/a&gt;, but the TLDR is that it works by forcing that the weights used to combine each step’s output into the final answer sum exactly one.
To achieve this a non-differentiable piecewise function is used, namely: if the sum of the weights is more than one, then change the last weight so that the sum is exactly one.
It has seen some success reducing computation in computer vision and natural language processing problems.
However, we found that its theoretical shortcomings limited its usefulness for Visual Reasoning tasks (see Results), so we proposed a novel fully-differentiable algorithm.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;how-it-works&quot;&gt;How it works&lt;/h2&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/diagram.png&quot; alt=&quot;The final answer Y is built up from the sub-answers from each module. The maximum contribution of any one of these steps is limited by all earlier ones, and any step can choose to limit contribution of subsequent ones.&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;The final answer Y is built up from the sub-answers from each module. The maximum contribution of any one of these steps is limited by all earlier ones, and any step can choose to limit contribution of subsequent ones.&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;DACT was formulated as a differentiable alternative to ACT.
In other words, it was designed to provide a means by which a model can halt computation without adding noise to the gradients.&lt;/p&gt;

&lt;!-- Our approach maintains the full gradient by **only halting during evaluation** (and not during training).
The weights used to combine all the step output’s are described by a monotonically decreasing probability distribution that implicitly includes future steps yet to be computed.
The result is a fully differentiable model for training with gradient descent whose computation can be reduced during inference by mathematically determining when the interruption cannot change the output. --&gt;

&lt;p&gt;Our formulation can be applied to any model or ensemble that can be decomposed as a series of modules or submodels $m_n$, $n ∈ [1,…,N]$ that can be ordered by complexity.
For example, recurrent networks are composed by iterative steps, CNNs by residual blocks, and ensembles by smaller models.
We refer to the composition as our final model or ensemble $M$, and to its output as $Y$.
This work focusses on its application to a recurrent visual reasoning architecture called MAC.&lt;/p&gt;

&lt;p&gt;The core of the DACT algorithm is that any step can limit the total contribution of subsequent steps.
To achieve this we use the sigmoidal halting values $h_n \in \left] 0, 1 \right[ $ to inductively define $p_n$ as:&lt;/p&gt;

\[p_n = \prod_{i=1}^{n}h_{i} = h_{n} p_{n-1}\]

&lt;p&gt;We observe that $p_n$ is monotonically decreasing for increasing values of $n$.
Through their halting values each $n$th step can choose to either maintain the probability ($h_n \approx 1$) or reduce it ($h_n &amp;lt; 1$).
The value of $p_n$ can be interpreted as the probability that a subsequent step might change the value of the final answer.
Consequently, we define the initial value $p_0 = 1$.&lt;/p&gt;

&lt;p&gt;The final answer $Y$ is built incrementally using the sub-answers of each step using accumulator variables $a_n$ for $n \in [1 \dots N]$ such that $Y = a_N$:&lt;/p&gt;

\[a_n = \begin{cases}
    \overrightarrow{0} &amp;amp; \text{if } n=0\\
    y_n p_{n-1} + a_{n-1} \left( 1 - p_{n-1} \right) &amp;amp; \text{otherwise}
  \end{cases}\]

&lt;p&gt;It follows from this definition that $Y$ can always be rewritten as a weighted sum of intermediate outputs $y_n$.
The relative relevance of each $y_n$ to the final output is thus constrained by $p_{n-1}$ which in turn is constrained by the $h_n$s of earlier steps.&lt;/p&gt;

&lt;p&gt;We observe that this means that, for some step $n$ with low associated $p_n$, then $a_n \approx Y$.&lt;/p&gt;

&lt;h3 id=&quot;putting-it-all-together&quot;&gt;Putting it all together…&lt;/h3&gt;

&lt;p&gt;During evaluation / test we want to identify the step where $a_n \approx Y$ to halt computation.
How you choose to define $\approx$ in your code depends on you and the use-case.
For this work we say that $a_n$ is similar enough to $Y$ once we are sure that the class with highest probability in $a_n$ is the same as in $Y$.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_steps&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# run another step
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;answer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;run_module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;answer_can_change&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We say that the answer cannot change when the top class in $a_n$ will necessarily be the same as in $Y$ after all $d = N - n$ remaining steps.
In particular, we are interested in checking if it’s possible that the probability associated to the &lt;em&gt;runner up&lt;/em&gt; (second best) class $c^{ru}$ can surpass that of the top class ($c^*$).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;answer_can_change&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# get top and runner-up classes
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;c_star&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;get_max_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;answer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;c_ru&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;get_ru_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;answer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# check if answer cant change
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_star&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_ru&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The top answer is most likely to change if all $d$ remaining steps assign probability $0$ to $c^*$ and $1$ to $c^{ru}$.
This scenario is the worst case from the perspective of the stability of the answer as it leads to the minimum value that the probability of class $c^*$ can take in $Y$; along with the maximum value for $c^{ru}$.&lt;/p&gt;

&lt;p&gt;Then, after expanding the inductive definition of $a_n$ and replacing the worst-case probabilities we derive a lower bound for the probability of the class $c^*$ in $Y$:&lt;/p&gt;

\[\Pr(c^*, N) \geq \Pr(c^*, n)(1-p_n)^d\]

&lt;p&gt;And an upper bound to the probability of the runner-up class $c^{ru}$:&lt;/p&gt;

\[\Pr(c^{ru}, N) \leq \Pr(c^{ru}, n) + p_n d\]

&lt;p&gt;Therefore during inference we can safely cut computation once we identify a step $n$ such that we know for sure that the top classes in $a_n$ and $Y$ are the same.
Mathematically, this means the &lt;em&gt;halting condition&lt;/em&gt; is achieved when:&lt;/p&gt;

\[\Pr(c^*, n)(1-p_n)^d \geq \Pr(c^{ru}, n) + p_n d\]

&lt;p&gt;&lt;em&gt;(The math and some additional proofs are included in the paper.)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Finally, we add $\rho = \sum_{n=1}^{N} p_n$, a proxy of the total computation, to the loss function to encourage reduced computation:&lt;/p&gt;

\[\hat{L} (x, y) = L (x, y) + \tau \rho(x)\]

&lt;hr /&gt;

&lt;h2 id=&quot;results-clevr&quot;&gt;Results: CLEVR&lt;/h2&gt;

&lt;h3 id=&quot;1-better-accuracy-in-fewer-steps&quot;&gt;1. Better accuracy in fewer steps&lt;/h3&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/mac_steps_acc.png&quot; alt=&quot;Scatterplot of computation (in steps) vs. precision. DACT-MACs shown in color; MACs as diamonds; ACT-MACs as crosses.&quot; /&gt;&lt;/th&gt;
                
                  &lt;th style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/th&gt;
                
              
            
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/convergence.png&quot; alt=&quot;Learning curves for different regularization ( 𝜏 ponder cost) values show mean and variance of three runs.&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;Scatterplot of computation (in steps) vs. precision. DACT-MACs shown in color; MACs as diamonds; ACT-MACs as crosses.&lt;/em&gt;&lt;/td&gt;
                
                  &lt;td style=&quot;text-align: center&quot;&gt;&amp;nbsp;&lt;/td&gt;
                
              
            
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;Learning curves for different regularization ( 𝜏 ponder cost) values show mean and variance of three runs.&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;As the scatterplot above shows, DACT enabled MACs (in color) consistently outperform vanilla MACs (shown as diamonds) when both use comparable average numbers of steps.
ACT on the other hand only performs as well or bellow as comparable MACs.
Additionally, the figure shows that DACT responds predictably to changes in the penalty or &lt;em&gt;ponder cost&lt;/em&gt; $\tau$ used (represented by the color), iterating fewer times when more penalty is used.
This again contrasts with ACT which proved to be insensitive to the &lt;em&gt;ponder cost&lt;/em&gt;.
For instance, ACT without ponder cost ($\tau$ = 0.0) performs 3.2 steps on average and obtains an accuracy of 95.8%.&lt;/p&gt;

&lt;h3 id=&quot;2-increased-adaptability-to-changes-in-question-difficulty&quot;&gt;2. Increased adaptability to changes in question difficulty&lt;/h3&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/corr_compare.png&quot; alt=&quot;How many steps are used by adaptive MACs for each question family in the CLEVR dataset. ACT-MACs in a); DACT-MACs shown in b) and c).&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;How many steps are used by adaptive MACs for each question family in the CLEVR dataset. ACT-MACs in a); DACT-MACs shown in b) and c).&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;The motivation behind using adaptive algorithms for this task is to use less computation for the more straightforward questions while still being able to use more computation for difficult ones.
In the figure above &lt;strong&gt;a)&lt;/strong&gt; shows the existing algorithm (ACT) failing to learn how to answer the most straightforward questions in less than three steps, or the hardest in more than five.
The other two images show DACT using most of the available spectrum, showing that DACT enabled MACs are capable of actively allocating more computational resources to questions that need them.
The second image &lt;strong&gt;b)&lt;/strong&gt; shows a variant of DACT that averages approximately the same number of steps as &lt;strong&gt;a)&lt;/strong&gt;, while &lt;strong&gt;c)&lt;/strong&gt; shows a DACT-MAC with lower ponder cost, which uses 50% more reasoning steps on average and thus achieves even better performance.&lt;/p&gt;

&lt;p&gt;The figure shows questions clustered by family type which translates to groups that require similar step sequences to solve.
The fact that DACT shows a remarkable correlation between computation and question family despite not including any type of supervision about these factors evinces the learning of meaningful patterns that correlate with question complexity.
The full &lt;em&gt;heatmap&lt;/em&gt; that shows an example for each question family can be found &lt;a href=&quot;/images/dact/corrs_full.png&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;3-interpretability-gains&quot;&gt;3. Interpretability gains&lt;/h3&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/AttsComp.png&quot; alt=&quot;Visual and linguistic attention maps for both regular MAC (left) and DACT-MAC (right).&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;Visual and linguistic attention maps for both regular MAC (left) and DACT-MAC (right).&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;Besides the obvious and substantial reduction in the number of steps used to answer, our model also contributes to the overall interpretability of the inference.
This is achieved by adding a proxy of the number of steps taken to the loss function, effectively coercing the model into only using fewer (and therefore more likely to be semantically strong) steps.
This translates into more interpretable models.
For instance, the question attentions above show that the last two steps are similar for both models, but that only one of the other ten steps used by MAC was necessary.&lt;/p&gt;

&lt;p&gt;Additionally, the values of $p_n$ and the sub answers $a_n$ provide further insights.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bonus-results-gqa&quot;&gt;Bonus Results: GQA&lt;/h2&gt;

&lt;p&gt;Finally, in order to evaluate the generality of the suggested approach to real data, we evaluate the combined DACT-MAC architecture on the more diverse images and questions in the GQA dataset &lt;a href=&quot;https://arxiv.org/abs/1902.09506&quot;&gt;[7]&lt;/a&gt;.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Method&lt;/strong&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Ponder Cost&lt;/strong&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Steps&lt;/strong&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Accuracy&lt;/strong&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;MAC+Gate&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;NA&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.51&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;MAC+Gate&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;NA&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.52&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;MAC+Gate&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;NA&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.52&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;MAC+Gate&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;NA&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.36&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;MAC+Gate&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;NA&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;6&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.37&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;ACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1e-2&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1.99&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.17&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;ACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1e-3&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2.26&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.04&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;ACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1e-4&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2.31&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.21&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;ACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2.15&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.20&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;DACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5e-2&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1.63&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.23&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;DACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1e-2&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2.77&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.26&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;DACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5e-3&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3.05&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.35&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;DACT&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1e-3&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3.69&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;77.31&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;We find that increasing computational steps doesn’t benefit the chosen architecture (MAC), and therefore adapting computation won’t increase performance.
However, by adding DACT to a pre-trained 4-step MAC and then fine-tuning we find that it again outperforms the existing algorithm in terms of accuracy and responsiveness to &lt;em&gt;ponder cost&lt;/em&gt;.&lt;/p&gt;

&lt;div style=&quot;padding: 10px; border-radius: 10px; border-color: black; border-style: solid; border-width: thin;&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        
          
              
                &lt;th style=&quot;text-align: center&quot;&gt;&lt;img src=&quot;/images/dact/corrs_gqa.png&quot; alt=&quot;How many steps are used by DACT-MACs for each question type in the GQA dataset.&quot; /&gt;&lt;/th&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody style=&quot;border: none&quot;&gt;
      &lt;tr&gt;
        
          
              
                &lt;td style=&quot;text-align: center&quot;&gt;&lt;em style=&quot;font-size: 0.8em&quot;&gt;How many steps are used by DACT-MACs for each question type in the GQA dataset.&lt;/em&gt;&lt;/td&gt;
                
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
            
        
          
              
          
        
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
  
&lt;/div&gt;

&lt;p&gt;Additionally, we find that DACT-MACs adapt the 4-step algorithm reducing computation on some question types, and that the number of steps again correlate strongly with &lt;em&gt;question types&lt;/em&gt; as can be seen in the &lt;em&gt;heatmaps&lt;/em&gt; above.
The same figures also show how the architecture adapts to changes in the &lt;em&gt;ponder cost&lt;/em&gt;, as this penalty decreases DACT adaptively allocates more resources to more complex questions.
The full &lt;em&gt;heatmap&lt;/em&gt; that shows the question types can be found &lt;a href=&quot;/images/dact/corrs_full_gqa.png&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;future-work-ideas-&quot;&gt;Future Work Ideas (!)&lt;/h2&gt;

&lt;p&gt;A few lines for future work:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;using adaptive computation to generate curriculums for curriculum learning.&lt;/li&gt;
  &lt;li&gt;using different &lt;em&gt;halting conditions&lt;/em&gt; with DACT.&lt;/li&gt;
  &lt;li&gt;taking advantage of DACT’s differentiability to use non-linear functions of computation (eg. exponential ponder penalties).&lt;/li&gt;
  &lt;li&gt;applying DACT to other models and datasets. I’m particularly interested in using it on neural state machines &lt;a href=&quot;https://arxiv.org/abs/1907.03950&quot;&gt;[8]&lt;/a&gt; for real adaptive behavior on GQA.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;cite&quot;&gt;Cite&lt;/h2&gt;

&lt;div class=&quot;language-bibtex highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;@article&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;Eyzaguirre2020DifferentiableAC&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Differentiable Adaptive Computation Time for Visual Reasoning}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;author&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Cristobal Eyzaguirre and A. Soto}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;journal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{2020 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;year&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{2020}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;pages&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{12814-12822}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;style&gt;
  /* overwrite mains max width so vis can use full width */
  img {
    max-width:100%;
  }
&lt;/style&gt;

</description>
        <pubDate>Sat, 25 Apr 2020 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/ai/2020/04/25/DACT-for-Visual-Reasoning.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/ai/2020/04/25/DACT-for-Visual-Reasoning.html</guid>
        
        
        <category>Ai</category>
        
      </item>
    
      <item>
        <title>Modelación Linear Discreta</title>
        <description>&lt;p&gt;Parte dos de la guia para estudiar la materia del curso ICS1113 Optimización (curso de la Pontificia Universidad Católica de Chile). 
Faltan algunos.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Técnica 1:&lt;/strong&gt;
Formular restricciones usando lógica proposicional y luego traducir.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$i \rightarrow j$ lo reescribimos como $i \leq j$.&lt;/li&gt;
  &lt;li&gt;$\neg i$ lo reescribimos como $1 - i$.&lt;/li&gt;
  &lt;li&gt;un $\lor$ a la izquierda divide en dos condiciones: $i \lor j \rightarrow k$ se reescribe como $i \leq k$ y $j \leq k$.&lt;/li&gt;
  &lt;li&gt;un $\land$ a la izquierda: $i \land j \rightarrow k$ se reescribe como $i + j \leq k + 1$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Técnica 2:&lt;/strong&gt;
Para restricciones &lt;strong&gt;condicionadas&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;$ax \leq b $ cuando $y$ se escribe: $ax \leq b + m(1-y)$.
Donde m es un valor muy grande, así tenemos que cuando $y=0$ la restricción funciona como si fuera un $ax \leq b + \infty = \infty$ que siempre se cumple.&lt;/p&gt;

&lt;p&gt;$ax \geq b $ cuando $y$ se escribe: $ax \geq b - m(1-y)$.&lt;/p&gt;

&lt;p&gt;Ejemplo para $y \in \{0, 1\}$:&lt;/p&gt;

\[\begin{cases}
ax_i \leq b \qquad  \text{cuando } y = 1\\
ax_i \geq b \qquad \text{eoc.}
\end{cases}\]

&lt;p&gt;Queda:&lt;/p&gt;

\[ax_i \leq b + m(1-y)\]

\[ax_i \geq b - m(y)\]

&lt;p&gt;&lt;strong&gt;Técnica 3:&lt;/strong&gt;
Para &lt;strong&gt;funciones por partes&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;si queremos modelar \(y = 
\begin{cases}
ax + b \qquad  \text{cuando } x \leq k\\
cx + d \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

&lt;p&gt;Defino variables:&lt;/p&gt;

\[x_1 = 
\begin{cases}
x \qquad  \text{cuando } x \leq k\\
0 \qquad \text{eoc.}
\end{cases}\]

\[x_2 = 
\begin{cases}
x \qquad  \text{cuando } x \geq k + 1\\
0 \qquad \text{eoc.}
\end{cases}\]

\[w_1 = 
\begin{cases}
1 \qquad  \text{cuando } x \leq k\\
0 \qquad \text{eoc.}
\end{cases}\]

\[w_2 = 
\begin{cases}
1 \qquad  \text{cuando } x \geq k + 1\\
0 \qquad \text{eoc.}
\end{cases}\]

&lt;p&gt;Las restricciones son:&lt;/p&gt;

\[y = (ax_1 + bw_1) + (cx_2 + dw_2)\]

\[x_1 \leq k w_1\]

\[x_2 \geq (k + 1) w_2\]

\[x = x_1 + x_2\]

\[1 = w_1 + w_2\]

&lt;h3 id=&quot;problema-de-seleccionar-knapsack&quot;&gt;Problema de seleccionar: Knapsack&lt;/h3&gt;

&lt;p&gt;Llevar el producto $i$ me aporta $p_i$ dolares y me cuesta $w_i$. Tengo un total de $W$ dolares. Maxmimizar el precio de los productos que llevo.&lt;/p&gt;

&lt;p&gt;Defino 
\(x_i = 
\begin{cases}
1  \qquad \text{cuando llevo producto } i\\
0  \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

\[\max \sum_i x_i p_i\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\sum_i x_i w_i \leq W\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-costos-fijos-producción-e-inventario-con-costos-fijos-1&quot;&gt;Problema con costos fijos: Producción e inventario con costos fijos 1&lt;/h3&gt;

&lt;p&gt;El mismo problema de producción e inventario (ver publicación pasada), pero si uso maquina en $t$ tengo un costo adicional $k^t$ (o sea, si produzco algo, tengo costo fijo).&lt;/p&gt;

&lt;p&gt;Primero, como es un problema de producción e inventario defino $x_i^t$ como la cantidad de $i$ que produzco en $t$, y $y_i^t$ como hay almacenado de $i$ en $t$.&lt;/p&gt;

&lt;p&gt;Defino  \(w^t = 
\begin{cases}
1  \qquad \text{usé la maquina en } t\\
0  \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

\[\min \sum_i\sum_t x_i^tc_i^t + y_i^th_i^t + w^tt k^tt\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\sum_i x_i^t \leq 0 + mw^t\]

&lt;p&gt;Obtenemos esta restricción usando la técnica 2. Vemos que sólo si se prende la maquina ($w^t = 1$) podemos producir.&lt;/p&gt;

\[y_i^{t-1} + x_i^t = y_i^t + d_i^t  \qquad \forall i,t\]

\[x_{i}^t,y_i^t \geq 0 \qquad \forall i,t\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-costos-fijos-y-continuidad-producción-e-inventario-con-costos-fijos-2&quot;&gt;Problema con costos fijos y continuidad: Producción e inventario con costos fijos 2&lt;/h3&gt;

&lt;p&gt;Imaginemos ahora que en el problema anterior no hay costo fijo si la maquina estuvo prendida en $t-1$ (ej. no es necesario prenderla).&lt;/p&gt;

&lt;p&gt;Defino  \(z^t = 
\begin{cases}
1  \qquad \text{encendí la maquina en } t\\
0  \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

&lt;p&gt;Son las mismas restricciones que las de arriba, sólo agrego:&lt;/p&gt;

\[z_t \geq w^t - w^{t-1}\]

&lt;hr /&gt;
&lt;h3 id=&quot;problemas-de-subdivisionasignación-coloring&quot;&gt;Problemas de subdivision/asignación: Coloring&lt;/h3&gt;

&lt;p&gt;2 nodos en un grafo no pueden tener el mismo color si están conectados ($C_i$ son los nodos conectados con $i$). Minimice la cantidad de colores usados.&lt;/p&gt;

&lt;p&gt;Defino \(x_{ik} = 
\begin{cases}
1 \qquad  \text{cuando nodo } i \text{ es de color } k\\
0 \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

&lt;p&gt;Defino \(y_{k} = 
\begin{cases}
1 \qquad  \text{cuando uso color } k \\
0 \qquad \text{eoc.}
\end{cases}\)&lt;/p&gt;

\[\min \sum_k y_k\]

&lt;p&gt;s.a.&lt;/p&gt;

&lt;p&gt;Todos los nodos con un color: \(\qquad \sum_k x_{ik} = 1 \qquad \forall i\)&lt;/p&gt;

&lt;p&gt;Si uso un color se activa $y_k$: \(\qquad \sum_i x_{ik} \leq 0 + My_k \qquad \forall k\)&lt;/p&gt;

&lt;p&gt;$x_{i,k} \rightarrow \neg x_{j, k}$ para nodos conectados: \(\qquad x_{ik} \leq 1- x{jk} \qquad \forall i, k, \forall j \in C_i\)&lt;/p&gt;

</description>
        <pubDate>Sun, 21 Apr 2019 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/classnotes/2019/04/21/Modelaci%C3%B3n-Linear-Discreta.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/classnotes/2019/04/21/Modelaci%C3%B3n-Linear-Discreta.html</guid>
        
        
        <category>Classnotes</category>
        
      </item>
    
      <item>
        <title>Modelación Linear Continua</title>
        <description>&lt;p&gt;Esta guía la cree para mi mismo y el resto de los humanos hispano-hablantes luego de no encontrar una buena fuente para estudiar la materia del curso ICS1113 Optimización (curso de la Pontificia Universidad Católica de Chile).
En ramos como este hay unas pocas “herramientas” que debemos saber usar, combinándolas para lograr modelar el problema. 
Consideré una cantidad extensiva de ejercicios resueltos e intenté destilar en cada uno las técnicas requeridas para resolverlo, luego, definí otro problema de optimización linear mínimo que necesite de la técnica.&lt;/p&gt;

&lt;h3 id=&quot;problema-básico-con-restricciones-movimiento-de-petroleo&quot;&gt;Problema básico con restricciones: Movimiento de petroleo&lt;/h3&gt;

&lt;p&gt;Hay $i$ tipos de petroleo con distintos costos $c_i$ por cada litro de $i$ comprado, y con pesos diferentes $p_i$ por cada litro de $i$. Quiero maximizar mis ganancias, pero sujeto a que la suma de los pesos no puede ser mayor a mi capacidad.&lt;/p&gt;

&lt;p&gt;Defino $x_i$ como cuántos litros de $i$ compro.&lt;/p&gt;

\[\max \sum_i c_i x_i\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\sum_i p_i x_i \leq capacidad\]

\[x_i \geq 0 \qquad \forall i\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-condiciones-donantes-de-sangre&quot;&gt;Problema con condiciones: Donantes de sangre&lt;/h3&gt;

&lt;p&gt;Hay $n$ personas de las que algunas pueden recibir sangre de tipo $i$ y otras no. 
Diremos que las personas con sangre $i$ pueden donar a personas $j$ si $d_{ij} = 1$ y $d_{ij} = 0$ si no pueden hacerlo.
El porcentaje de personas con sangre de tipo $i$ es $p_i$.
El costo por un litro de sangre $i$ es $c_i$.
Si tengo que comprar $n$ litros, minimice los costos pero manteniendo haya un litro para cada persona (comprar n litros).&lt;/p&gt;

&lt;p&gt;Defino $x_{ij}$ como la cantidad de litros de $i$ que compro para $j$.&lt;/p&gt;

\[\min \sum_i c_i x_i\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\sum_j d_{ij} x_{ij} = n p_i \qquad \forall i\]

\[x_{ij} \geq 0 \qquad \forall i, j\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-combinaciones-combos&quot;&gt;Problema con combinaciones: Combos&lt;/h3&gt;

&lt;p&gt;Una empresa tiene 3 productos con precios $y_i$ y costo $c_i$. Los productos se venden individualmente o en “paquetes” (tengo sus precios y costos). 
Maximice ingresos (precio - costo).&lt;/p&gt;

&lt;p&gt;Defino $x_j$ como el número de ofertas del servicio, y considero los productos individualemente y en paquetes como servicios distintos. Luego, tengo y posibles servicios que ofrecer.&lt;/p&gt;

\[\max \sum_j x_j (y_j - c_j)\]

&lt;p&gt;Donde $y_j$ y $c_j$ son los precios/costos individuales cuando el servicio solo contiene un producto, y los precios/costos de los paquetes cuando corresponde.&lt;/p&gt;

&lt;p&gt;s.a.&lt;/p&gt;

\[x_{j} \geq 0 \qquad \forall j\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-relajación-de-restricción-maquinas-con-sobre-tiempo&quot;&gt;Problema con relajación de restricción: Maquinas con sobre-tiempo&lt;/h3&gt;

&lt;p&gt;Maquina produce 5 uds. del producto 1 (que se vende a \$10) o 8 uds. del producto 2 cada hora (se vende a \$12). 
Maquina funciona 8 horas diarias pero puede excederse pagando un costo adicional de \$5 cada hora.
Maximizar ingresos.&lt;/p&gt;

&lt;p&gt;Definimos $x_i$ como el número de productos de tipo $i$ que producimos.&lt;/p&gt;

&lt;p&gt;Definimos $y$ como la cantidad de horas extra trabajadas (nuestro &lt;strong&gt;término de relajacion&lt;/strong&gt;).&lt;/p&gt;

\[\max 10x_1 + 12x_2 - 5y\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\frac{x_1}{5} + \frac{x_2}{8} \leq 8 + y\]

\[x_{i}, y \geq 0 \qquad \forall i\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-con-inventario&quot;&gt;Problema con inventario&lt;/h3&gt;

&lt;p&gt;Comienzo con 1000 unidades en la bodega.
Conozco la demanda (será $d_j^t$ en lugar $j$ en el tiempo $t$), y debo satisfacerla.
El máximo número de unidades de que puedo transportar en $t$ es $L^t$ , y el costo por unidad trasportada es $c_j^t$.&lt;/p&gt;

&lt;p&gt;Defino $x_j^t$ como el número de unidades transportadas a $j$ en tiempo $t$.&lt;/p&gt;

&lt;p&gt;Defino $A^t$ como la cantidad de unidades en bodega en el tiempo $t$.&lt;/p&gt;

\[\min \sum_j \sum_t c_j^t x_j^t\]

&lt;p&gt;s.a.&lt;/p&gt;

\[\qquad A^0 = 1000\]

&lt;p&gt;&lt;strong&gt;Conservación de flujo&lt;/strong&gt;:
\(\qquad A^{t-1} = A^t + \sum_j x_j^t \qquad \forall t\)&lt;/p&gt;

\[\sum_j x_j^t \leq L^t  \qquad \forall t\]

\[x_{j}^t \geq 0 \qquad \forall j, t\]

&lt;hr /&gt;
&lt;h3 id=&quot;problema-de-tareas-con-prerequisitos-planificación-proyecto&quot;&gt;Problema de tareas con prerequisitos: Planificación proyecto&lt;/h3&gt;

&lt;p&gt;La tarea $i \in P$ ($P$ es conjunto de tareas) no puede hacerse antes que ninguna de las tareas en el subconjunto de $P$, $P_i$.
Cada tarea $i$ demora un tiempo fijo $t_i$.
Minimice el tiempo en hacer todas las tareas.&lt;/p&gt;

&lt;p&gt;Definimos $x_i$ como el instante en que se comienza la tarea $i$.
Definimos $z$ como el tiempo de término de la última tarea (el tiempo que es mayor a todos los otros tiempos $\rightarrow$ &lt;strong&gt;máximo&lt;/strong&gt;).&lt;/p&gt;

\[\min z\]

&lt;p&gt;s.a.&lt;/p&gt;

\[z \geq x_i + t_i  \qquad \forall i\]

\[x_i \geq x_j + t_j   \qquad \forall i, \forall j \in P_i\]

\[x_{i} \geq 0 \qquad \forall i\]

&lt;hr /&gt;
&lt;h3 id=&quot;producción-e-inventario-con-vencimiento&quot;&gt;Producción e inventario con vencimiento&lt;/h3&gt;

&lt;p&gt;Produczo producto $i$ con costo unitario $c_i^t$ en tiempo $t$. Tengo bodegas en las que puedo almacenar los productos (con costo $h_i^t$), pero ojo que los productos vencen luego de $q_i$ dias… Minimizar costos de satisfacer la demanda $d_i^t$.&lt;/p&gt;

&lt;p&gt;Primero, como es un problema de producción e inventario defino $x_i^t$ como la cantidad de $i$ que produzco en $t$, y $y_i^t$ como hay almacenado de $i$ en $t$.
Defino &lt;strong&gt;cuanto boto&lt;/strong&gt; del producto $i$ en $t$ como $w_i^t$.&lt;/p&gt;

\[\min \sum_i\sum_t x_i^t c_i^t + y_i^th_i^t\]

&lt;p&gt;s.a.&lt;/p&gt;

\[y_i^{t-1} + x_i^t = y_i^t + d_i^t + w_i^t   \qquad \forall i,t\]

\[w_i^t \geq \sum_{r=1}^{t-q_i}x_i^r - \sum_{r=1}^t d_i^r - \sum_{r=1}^{t-1} w_i^t   \qquad \forall i,t\]

&lt;p&gt;Es decir, en $t$ debo botar al menos tantos productos $i$ como aquellos que he producido que ya han vencido (producidos hace $q_i$ dias o más), sin contar los que vendí y los que ya boté.&lt;/p&gt;

\[x_{i}^t,y_i^t, w_i^t  \geq 0 \qquad \forall i,t\]

\[y_i^0 = 0 \qquad \forall i\]

&lt;hr /&gt;

</description>
        <pubDate>Sun, 21 Apr 2019 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/classnotes/2019/04/21/Modelaci%C3%B3n-Linear-Continua.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/classnotes/2019/04/21/Modelaci%C3%B3n-Linear-Continua.html</guid>
        
        
        <category>Classnotes</category>
        
      </item>
    
      <item>
        <title>PyTorch (1.0), CUDA &amp; cuDNN on MacOS</title>
        <description>&lt;p&gt;This guide was written primarily for my own future use and the methods described have only been tested with my own late 2013 15” Macbook Pro with Nvidia 750m graphics.
Nonetheless, the guide is written in english so as to be useful for many people (although my mother tongue is spanish).
The guide is based on what was published on &lt;a href=&quot;https://groups.google.com/a/allenai.org/forum/#!topic/allennlp-users/uqICoCmXTjo&quot;&gt;this google group&lt;/a&gt; for AllenNLP, completing the information there and updating commands where useful.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;CUDA and cuDNN are used to speed up matrix operations and other operations that are tipically useful for machine learning algorithms. 
Macs have not shipped with nVidia graphics cards since 2013 and it can be difficult to find updated drivers and cuDNN libraries that are compatible with your nVidia graphics card.&lt;/p&gt;

&lt;p&gt;Not all graphics cards are compatible with CUDA, &lt;a href=&quot;https://developer.nvidia.com/cuda-gpus&quot;&gt;here&lt;/a&gt; is a list of those compatible; you need compute capability $\geq$ 3.0 in order to follow the guide.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;cuda-drivers&quot;&gt;CUDA drivers&lt;/h4&gt;

&lt;p&gt;The first step is to update your CUDA drivers.
I found &lt;a href=&quot;https://www.insanelymac.com/forum/topic/324195-nvidia-web-driver-updates-for-macos-high-sierra-update-apr-02-2019/&quot;&gt;this post&lt;/a&gt; where updated drivers can be found for MacOS versions up to 10.13.6 (most recent version when the post was written).
cuDNN requires driver version 378.05 or higher. While the original guide this post is based on didn´t have access to those drivers I found those listed above and can confirm they work.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;cuda-toolkit&quot;&gt;CUDA toolkit&lt;/h4&gt;

&lt;p&gt;The next step is to install CUDA toolkit form &lt;a href=&quot;https://developer.nvidia.com/cuda-downloads&quot;&gt;here&lt;/a&gt;. Select MacOS as the target OS and install the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.dmg&lt;/code&gt;. This will install CUDA $\geq$ 10.1 on your local machine. Follow the onscreen prompts.&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;compatible-clangxcode-version&quot;&gt;Compatible clang/Xcode version&lt;/h4&gt;

&lt;p&gt;The original post sugests installing Xcode 8.3.3 in order to get a compatible clang compiler. 
On their site nVidia says Xcode 10.1 (10B61) is compatible with MacOS 10.13.6 and CUDA 10.1. 
Personally I followed the instructions &lt;a href=&quot;https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html&quot;&gt;here&lt;/a&gt; to install the older version of Xcode after having problems in a later step.
However the problems were unrelated to the clang version and although I didnt test Xcode 10.1, it can make sense to check &lt;a href=&quot;https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html#system-requirements&quot;&gt;here&lt;/a&gt; for the sugested Xcode version for the downloaded CUDA toolkit.&lt;/p&gt;

&lt;p&gt;Older Xcode versions have to be downloaded through the &lt;a href=&quot;https://developer.apple.com/downloads&quot;&gt;Apple developer page&lt;/a&gt;.
Searching for the version number will let you download the version you want.
After downloading the version you can change the selected xcode version by running:&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c&quot;&gt;# first install command line tools (in case they weren&apos;t already)&lt;/span&gt;
xcode-select &lt;span class=&quot;nt&quot;&gt;--install&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;# select the correct version; replace &amp;lt;Xcode_install_dir&amp;gt; with the real dir. &lt;/span&gt;
&lt;span class=&quot;nb&quot;&gt;sudo &lt;/span&gt;xcode-select &lt;span class=&quot;nt&quot;&gt;-s&lt;/span&gt; /Applications/&amp;lt;Xcode_install_dir&amp;gt;/Contents/Developer
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;cudnn&quot;&gt;cuDNN&lt;/h4&gt;

&lt;p&gt;cuDNN can be found &lt;a href=&quot;https://developer.nvidia.com/rdp/cudnn-archive&quot;&gt;here&lt;/a&gt;. You will need to register as a developer (for free) in order to download.
For maximum performance look for the most recent compatible version (under Dec.14); I installed &lt;a href=&quot;https://developer.nvidia.com/compute/machine-learning/cudnn/secure/v7.0.4/prod/9.0_20171031/cudnn-9.0-osx-x64-v7&quot;&gt;cuDNN 7.0.4&lt;/a&gt; for CUDA 9.0 (under Nov.13) since I was following the outdated tutorial.&lt;/p&gt;

&lt;p&gt;The compressed file can be unziped and moved, I moved it to my home (so you will need to change some paths in the following instructions if you dont put it there).&lt;/p&gt;

&lt;p&gt;I found I needed to export more paths than those on the original post. Run the following in your command line:&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;CUDA_HOME&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;~/cudnn
&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;DYLD_LIBRARY_PATH&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$CUDA_HOME&lt;/span&gt;/lib:&lt;span class=&quot;nv&quot;&gt;$DYLD_LIBRARY_PATH&lt;/span&gt;
&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;CUDNN_LIB_DIR&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$HOME&lt;/span&gt;/cudnn/lib
&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;CUDNN_INCLUDE_DIR&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$HOME&lt;/span&gt;/cudnn/include
&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;LD_LIBRARY_PATH&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$HOME&lt;/span&gt;/cudnn/lib
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;pytorch-installation&quot;&gt;Pytorch Installation&lt;/h2&gt;

&lt;p&gt;On MacOS, the only way to install pytorch with CUDA support is to install from source. The pytorch repository has &lt;a href=&quot;https://github.com/pytorch/pytorch#from-source&quot;&gt;instructions&lt;/a&gt;, but they assume you use Anaconda. The following commands can be seen as a proven (be me) alternative:&lt;/p&gt;

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c&quot;&gt;# clone repository&lt;/span&gt;
git clone &lt;span class=&quot;nt&quot;&gt;--recursive&lt;/span&gt; https://github.com/pytorch/pytorch
&lt;span class=&quot;nb&quot;&gt;cd &lt;/span&gt;pytorch

&lt;span class=&quot;c&quot;&gt;# install, I use 10.13 as target because that is the version of MacOS I am running.&lt;/span&gt;
&lt;span class=&quot;nv&quot;&gt;MACOSX_DEPLOYMENT_TARGET&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;10.13 &lt;span class=&quot;nv&quot;&gt;CC&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;clang &lt;span class=&quot;nv&quot;&gt;CXX&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;clang++ python3 setup.py &lt;span class=&quot;nb&quot;&gt;install&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;remove-pytorch-no-longer-supports-this-gpu-because-it-is-too-old-warning&quot;&gt;Remove &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PyTorch no longer supports this GPU because it is too old&lt;/code&gt; warning&lt;/h4&gt;

&lt;p&gt;If you get this message it may be because your GPU is of CUDA compatibility 3.0 (eg. nVidia 750m). Contrary to what appears in the warning, CUDA 3.0 is supported. We can remove these warnings by going to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/usr/local/lib/python3.7/site-packages/torch/cuda/__init__.py&lt;/code&gt; and commenting out lines 118-119. The location and line numbers can vary but the UserWarning raised indicated the file path and line. The commented lines in my distribution of pytorch (1.1.0) are as follows:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# elif capability == (3, 0) or major &amp;lt; 3:
&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# warnings.warn(old_gpu_warn % (d, name, major, capability[1]))
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;testing-installation&quot;&gt;Testing installation&lt;/h2&gt;

&lt;p&gt;First we test importing pytorch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;__version__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We check for available cuda devices and try moving a size 20 tensor to the GPU:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_available&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_cuda&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The following wont produce error messages if cuDNN is installed:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backends&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cudnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;enabled&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;p&gt;And there you go, congratulations!&lt;/p&gt;
</description>
        <pubDate>Tue, 02 Apr 2019 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/2019/04/02/Pytorch-Cuda-Mac.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/2019/04/02/Pytorch-Cuda-Mac.html</guid>
        
        
      </item>
    
      <item>
        <title>Percentage GridMap</title>
        <description>&lt;p&gt;&lt;em&gt;How can we visualize the distribution of 33 categories over the whole of the USA?&lt;/em&gt;
The webpage &lt;a href=&quot;http://meetup.com&quot;&gt;meetup.com&lt;/a&gt; hosts diferent types of events all over the world. 
For a class we wondered if it was posible to observe diferences in the interests between the people of diferent states.
The main dificulty was that there were 33 categories to compare among 50 states, a simple barchart wouldn’t be enough as 33*50 columns is more than any one person can absorb.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-solution&quot;&gt;The solution&lt;/h2&gt;

&lt;p&gt;We compromised. Instead of showing every minor diference among states we chose to observe tendencies. Then, a choropleth would be created to reflect these tendencies and add geographical information to the mix.&lt;/p&gt;

&lt;p&gt;We show tendencies by dividing each state into 100 colored cells we call percentage cells. The amount of cells that are of a certain color represents the percentage of the interest of the inhabitants of the state towards the category represented by the color. By randomizing the positioning of the cels inside the state we obtain a puzle that broadly shows the main categories present in each one of the states.&lt;/p&gt;

&lt;p&gt;We substitute the states geographical shape for one that removes surface area biases in the visualization as this only adds noise to what we want to observe. However, we maintain the general positions of the states in respect to each other so as to facilitate the detection of geographical related relations.&lt;/p&gt;

&lt;p&gt;Finally, since the randomly positioned cells are difficult to count in order to find the exact percentage, we let the user click a state to get an easier to read visualization (a barchart) of the specific area.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;hypothesis&quot;&gt;Hypothesis&lt;/h2&gt;

&lt;p&gt;We hoped that the resulting visualization would enable us to detect patterns between the states by comparing their tendencies.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We found it easier to find outliers and anomalies simply by looking for states that have a diferent “average” color.&lt;/li&gt;
  &lt;li&gt;We found it was easy to find geographical tendencies. For instance, regions of the USA where there was a recognizably larger interest in Tech (shown in blue).&lt;/li&gt;
  &lt;li&gt;It’s generally easy to compare two states interest in a category by comparing the amount of cells of the desired color, and similar percentages can be distinguished after clicking each state to get the broken down percentages in the barchart.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;next-steps&quot;&gt;Next steps&lt;/h2&gt;

&lt;p&gt;We didnt completely finish the project, people looking to build upon or improve should consider the following areas:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The code needs tidying up (D3.js is declaratively writen and can be dificult to read in a big project like this).&lt;/li&gt;
  &lt;li&gt;Percentages are not calculated but proxied by sampling 100 events per state and asuming the categories of these are representative of the interests per state.&lt;/li&gt;
  &lt;li&gt;There’s much need for a way to select some subset of categories to compare because as of now those most common tend to hide the rest. (++ im 99% sure no one can distinguish 33 colors).&lt;/li&gt;
  &lt;li&gt;Responsiveness: the visualization looks horrible on smaller screens.&lt;/li&gt;
  &lt;li&gt;Performance: the transitions lag on slower computers because calculations are repeated for each of many cells (100 per state).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;style&gt;
  /* body {
    font-family:&quot;avenir next&quot;, Arial, sans-serif;
    font-size: 20px;
  } */

  .label {
    pointer-events: none;
  }

  /* overwrite mains max width so vis can use full width */
  #main {
    max-width:100%;
  }
&lt;/style&gt;

</description>
        <pubDate>Thu, 21 Mar 2019 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/2019/03/21/GridMap.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/2019/03/21/GridMap.html</guid>
        
        
      </item>
    
      <item>
        <title>RecSys Semana 6</title>
        <description>&lt;h2 id=&quot;comentario-factorization-machines&quot;&gt;Comentario: &lt;a href=&quot;https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf&quot;&gt;Factorization Machines&lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;resumen&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;Las máquinas de factorización son predictores generales (trabajar con cualquiera los vectores de características posibles) incluso en condiciones de datos muy &lt;em&gt;sparse&lt;/em&gt;, todo esto teniendo complejidad lineal sobre el numero de datos y dimensiones latentes escogidas para escalar eficientemente.&lt;/p&gt;

&lt;p&gt;Logran esto usando descomposición matricial (a un espacio de menos dimensiones) de una matriz construida específicamente para este fin como la mostrada en la siguiente imagen:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/&quot;&gt;&lt;img src=&quot;/images/FM.png&quot; style=&quot;width: 400px;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;La intuición clave acá es considerar los recuadros &lt;em&gt;User&lt;/em&gt;, &lt;em&gt;Movie&lt;/em&gt; y &lt;em&gt;Target&lt;/em&gt;. 
Cada fila representa una interacción entre un usuario y un ítem. 
Por ejemplo, la primera fila muestra que el usuario A (&lt;em&gt;Alice&lt;/em&gt;) interactuó con el ítem TI (&lt;em&gt;Titanic&lt;/em&gt;) y lo calificó con 5 puntos.
La factorización de la matriz llevará columnas con interacciones similares (o cualquier patron reconocible por el modelo) a formar columnas similares en el espacio de dimensiones reducidas.
Luego, el producto punto entre estas columnas similares será alto (ver mi post de la semana 2 para una explicación sobre la relación entre el producto punto de dos vectores y su distancia euclidiana).
Esta relación está implícita en la ecuación del modelo mostrada a continuación donde se ve que al intentar predecir, por ejemplo, el puntaje que dará &lt;em&gt;Alice&lt;/em&gt; al elemento &lt;em&gt;Star Trek&lt;/em&gt; (ST) la multiplicación de $x_i = x_{Alice}$ con $x_j = x_{Star Trek}$ será la única multiplicación entre $x$ con resultado no cero, y luego la unica parte de la tercera componente de la ecuación será la similaridad entre los historiales de &lt;em&gt;Alice&lt;/em&gt; y &lt;em&gt;Star Trek&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/&quot;&gt;&lt;img src=&quot;/images/FMModelEq.png&quot; style=&quot;width: 400px;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;También se pueden agregar otros elementos a la matriz (otra de las ventajas de ser predictores generales) para considerar el historial del usuario, la fecha y hora a la que consumió el elemento, etc.
Incluyo una imagen con estos datos para ilustrar como se incluyen, donde aprovecho de destacar la normalización cuando hay varios elementos dentro del mismo campo (como es el caso de &lt;em&gt;Other Movies Rated&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/&quot;&gt;&lt;img src=&quot;/images/FMComplete.png&quot; style=&quot;width: 400px;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;comentarios&quot;&gt;Comentarios&lt;/h3&gt;

&lt;p&gt;Tengo dos comentarios principales que hacen referencia (en ese orden) a la forma de modelar el tiempo (&lt;em&gt;Time&lt;/em&gt; en la imagen arriba) y a la memoria necesaria para entrenar el modelo.&lt;/p&gt;

&lt;p&gt;Primero consideremos la codificación del tiempo.
EL autor convierte información rica en un contador de meses desde alguna fecha no explicada (presumiblemente la fecha que se tiene para la primera interacción).
Tiene sentido que un usuario prefiera distintas películas a distintas horas o dias de la semana, meses, etc.
Una mejor forma de codificar el tiempo (y compatible con el modelo en discusión) podría ser codificar el año, mes, día de la semana y momento del día.
La consideración del valor que tome $w_i$ para la cada una de las columnas agregadas nos debiera mostrar la relevancia de esta variable para la predicción por lo que resulta deseable la codificación no solo para mejorar el rendimiento del modelo (pasándole información más rica) sino también aumentar su explicabilidad (y quizás hasta la confianza del usuario en el sistema si se le da acceso a esta información).&lt;/p&gt;

&lt;p&gt;Habría sido interesante que el &lt;em&gt;paper&lt;/em&gt; comentara sobre es si es posible paralelizar el modelo en múltiples nodos para reducir la cantidad de memoria necesaria por nodo para almacenar la matriz (que obviamente ocupa mucho mas espacio que la fomulación tradicional $R^{UxI}$).
La versión original de la ecuación de modelo requiere que todos los nodos contengan la matriz $V$ (o que compartan memoria, lo que lleva a necesitar sincronizar y perder la ventaja de paralelizar), sin embargo la versión reformulada admite paralelización distribuyendo $V$ entre tantos nodos como hayan disponibles (!).&lt;/p&gt;

&lt;h3 id=&quot;conclusiones&quot;&gt;Conclusiones&lt;/h3&gt;

&lt;p&gt;Las &lt;em&gt;FM&lt;/em&gt; son modelos potentes que aceptan gran variedad de información (que también puede ser codificada de diferentes maneras). Su flexibilidad permite codificar información de diferentes maneras y aporta algo de explicabilidad a los modelos de factorización tradicionales al incluir en $w$ una métrica de la relevancia de cada columna de $W$.&lt;/p&gt;

</description>
        <pubDate>Sun, 23 Sep 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/recsys/2018/09/23/Semana-6.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/recsys/2018/09/23/Semana-6.html</guid>
        
        
        <category>Recsys</category>
        
      </item>
    
      <item>
        <title>RecSys Semana 5</title>
        <description>&lt;h2 id=&quot;comentario-content-based-recommendation-systems-in-the-adaptive-web&quot;&gt;Comentario: Content-based recommendation systems &lt;a href=&quot;https://pdfs.semanticscholar.org/3444/6adc7d701a2c3a89c2fc5f6d3479eef407b0.pdf&quot;&gt;In The adaptive web&lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;resumen&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;Los recomendadores basados en contenido recomiendan items a usuarios según la descripción del item y lo que saben del usuario. 
Obtener información util del contenido del item es ma fácil de minar en el caso de datos semi-estructurados (algunos campos restringidos) que para casos de datos no-estructurados (como campos de texto sin restricciones). 
Para generar una representación estructurada de estos datos no estructurados pueden usarse técnicas como &lt;em&gt;stemming&lt;/em&gt; (obtener raíces de palabras) o &lt;strong&gt;TF-IDF&lt;/strong&gt; para obtener un termino que indique la importancia relativa de cada termino en el texto. 
TF-IDF no captura el contexto de las palabras porque solo considera el numero de veces que aparece pero obtiene buenos resultados.&lt;/p&gt;

&lt;p&gt;Los perfiles de usuario contienen la representación de los gustos de los usuarios en &lt;em&gt;perfiles&lt;/em&gt;. 
Estos pueden contener un modelo de las preferencias de los usuarios o un historial de interacciones anteriores (que luego pueden ser usadas por un &lt;em&gt;rule-based system&lt;/em&gt;). 
En el primer caso el modelo puede construirse con colaboración del usuario (donde cada uno declara sus preferencias), o pueden aprenderse usando clasificadores binarios (&lt;em&gt;¿gusta o no gusta?&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Entre los clasificadores que sirven para determinar la preferencia de los usuarios por un cierto item estan:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Arboles de decision e inducción de reglas&lt;/li&gt;
  &lt;li&gt;Vecinos Cercanos (basado en similaridad entre elementos y otros puntuados por el usuario)&lt;/li&gt;
  &lt;li&gt;Algoritmo de Rocchio (para refinar las &lt;em&gt;queries&lt;/em&gt; incrementalmente).&lt;/li&gt;
  &lt;li&gt;Clasificadores lineares&lt;/li&gt;
  &lt;li&gt;Naive Bayes (cualquiera de sus variantes)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;comentarios&quot;&gt;Comentarios&lt;/h3&gt;

&lt;p&gt;Encontré que al paper le faltó considerar otros tipos de items para los que TF-IDF no sirve para extraer características suficientes como lo son videos o imágenes.
Como sale en el texto los dos pasos principales para hacer recomendación basado en contenido es obtener representaciones del usuario y &lt;strong&gt;del contenido&lt;/strong&gt;. 
La mayoría del contenido consumido hoy en día no es escrito por lo que se vuelve un poco irrelevante el paper para personas el 2018 (fue escrito en 2007).
Aprovecho de comentar sobre aplicaciones de redes neuronales al area dado que me he informado del tema:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;modelos basados en el paradigma encoder-decoder permiten obtener representaciones vectoriales del contenido independiente de la estructura de este (ej. &lt;em&gt;autoencoder&lt;/em&gt; de imágenes).&lt;/li&gt;
  &lt;li&gt;representaciones de textos que incluyen contexto pueden ser obtenidas usando embeddings de palabras obtenidas usando &lt;em&gt;GloVe&lt;/em&gt;, &lt;strong&gt;W2V&lt;/strong&gt;, &lt;strong&gt;skip-thoughts&lt;/strong&gt; entre otras. Los embeddings pueden luego ser usadas en &lt;strong&gt;Doc2Vec&lt;/strong&gt; o otro modelo que use un encoder del contenido (ej. una &lt;strong&gt;RNN&lt;/strong&gt; que genere resúmenes del texto debiera poder encontrar representaciones útiles de los textos).&lt;/li&gt;
  &lt;li&gt;Las técnicas de modelamiento de secuencias que son validas para texto lo son para videos (u otras secuencias), lo que permite generar representaciones de estos (se puede usar el encoder de &lt;a href=&quot;https://arxiv.org/abs/1804.00819&quot;&gt;esto&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Por ultimo quiero comentar que la razon por la que no importa para este paper que TF-IDF pierda informacion contextual es que todos los algoritmos mencionados asumen independencia entre cada dimension en el espacio de factores.
Una representación que sería compatible con estos modelos sin perder tanta información contextual podría usar &lt;strong&gt;N-Grams&lt;/strong&gt; para generar tokens por pares de palabras.
Luego podríamos filtrar usando el IDF para eliminar las palabras (o n-gramas) que aparecen en todos los documentos.&lt;/p&gt;

</description>
        <pubDate>Sun, 16 Sep 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/recsys/2018/09/16/Semana-5.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/recsys/2018/09/16/Semana-5.html</guid>
        
        
        <category>Recsys</category>
        
      </item>
    
      <item>
        <title>RecSys Semana 3</title>
        <description>&lt;h2 id=&quot;comentario-evaluating-recommendation-systems-pdf&quot;&gt;Comentario: Evaluating Recommendation Systems &lt;a href=&quot;http://www.bgu.ac.il/~shanigu/Publications/EvaluationMetrics.17.pdf&quot;&gt;pdf&lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;resumen&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;El escrito tiene dos partes, la primera se enfoca en como comparar sistemas recomendadores en una variedad de propiedades considerando restricciones (memoria, cpu, datos, etc). 
El exito de un sistema no depende unicamente de su rendimiento en metricas de &lt;em&gt;accuracy&lt;/em&gt; sino que influyen ademas otros factores.
La evaluacion y comparacion de distintos algoritmos dependera en primer lugar de la forma de validar el rendimiento de los sistemas usados de los que se discuten 3 (&lt;em&gt;offline&lt;/em&gt;, &lt;em&gt;user studies&lt;/em&gt; y &lt;em&gt;online experiments&lt;/em&gt;). 
Se discuten primero por lo mismo.&lt;/p&gt;

&lt;p&gt;Independiente de la forma de comparar recomendadores debe siempre comenzarse desde una hipotesis (a la que estan orientados los experimentos), se deben fijar las variables que no se quieren evaluar, la evaluacion debe medir el poder de generalizacion de los sistemas  mas alla de el set de pruebas.
Para los experimentos &lt;strong&gt;offline&lt;/strong&gt; (usando datos recolectados previamente, barato) debemos usar datos lo mas parecidos posibles a lo que esperamos encontrar luego del &lt;em&gt;deployment&lt;/em&gt;.
Una forma de lograr esto es simulando el comportamiento de los usuarios 1) considerando solo datos previos a una fecha para predecir los usando modelos avanzados.
Los &lt;strong&gt;user studies&lt;/strong&gt; (evaluamos reclutando usuarios para probar sistema) permiten recolectar medidas cualitativas pero son caros y facilmente pueden contener &lt;em&gt;biases&lt;/em&gt; debido a la eleccion de usuarios para el test o porque saben que estan siendo evaluados. 
Dentro de los &lt;em&gt;user studies&lt;/em&gt; que comparan software podemos distinguir entre &lt;em&gt;within&lt;/em&gt; (AB testing) y &lt;em&gt;between&lt;/em&gt; (todos prueban todas las versiones).
Finalmente existe la &lt;strong&gt;online evaluation&lt;/strong&gt; (algunos usuarios sin saberlo estan usando version modificada) que nos permite medir directamente el rendimiento conforme los objetivos generales del sistema.&lt;/p&gt;

&lt;!-- falta integrar confianza (intervalos), unpaired results--&gt;

&lt;p&gt;Propiedades importantes a considerar cuando se elige un recomendador:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Preferencia de los usuarios: elegir el que prefieren los usuarios considerando que algunos pueden ser mas importantes.&lt;/li&gt;
  &lt;li&gt;Exactitud en la prediccion: el mas usado pero no por ser mas exacto va a ser prferido por el usuario. Podemos usar metricas como &lt;strong&gt;RMSE&lt;/strong&gt;, &lt;strong&gt;MAE&lt;/strong&gt;. La prediccion apunta a encontrar items que el usuario va a consumir por lo que podemos medir exactitud comparando los items predichos por el sistema por los que sabemos que el usuario consumio y medimos usando &lt;strong&gt;precision (at N)&lt;/strong&gt;, &lt;strong&gt;recall&lt;/strong&gt; y &lt;strong&gt;false positive rate&lt;/strong&gt;. A veces el orden y cantidad de predicciones puede infuir y deben usarse metricas que lo tomen en consideracion como &lt;strong&gt;NDPM&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Cobertura: proporcion de items que sugiere el sistema, diversidad de ventas (medible con metricas de desigualdad), proporcion de usuarios para los que el sistema puede recomendar (segun numero y calidad de interacciones de estos) y &lt;strong&gt;cold start&lt;/strong&gt; (que tan rapido empieza a ser util el sistema).&lt;/li&gt;
  &lt;li&gt;Confianza (del sistema en sus predicciones): sirven al usuario para discriminar entre las alternativas. Pueden compararse dos sistemas diferentes incluso si &lt;strong&gt;tienen distintas metricas de confianza&lt;/strong&gt; comparando los resultados de c/u despues de eliminar los elementos con baja confianza.&lt;/li&gt;
  &lt;li&gt;Confianza (del usuario en el sistema): importante para que el usuario efectivamente utilice las sugerencias.&lt;/li&gt;
  &lt;li&gt;Novedad: si se sugieren elementos desconocidos (para el). Se sugiere un metodo interesante para entrenar sistemas usando &lt;em&gt;offline&lt;/em&gt; evaluation con el fin de hacerlos mas novedosos que comentare luego. Con usuarios es trivial, basta con preguntarles (aunque cuidadose de no introducir bias).&lt;/li&gt;
  &lt;li&gt;Serendipia: que tan sorprendentes son los resultados. Notese que una pesima recomendacion seria sorprendente, por lo que debe balancearse &lt;strong&gt;siempre&lt;/strong&gt; con la precision. El autor sugiere (para evaluacion &lt;em&gt;ofline&lt;/em&gt;) evaluar esta propiedad recompensando aquellos algoritmos que sugieran elementos distintos a los consumidos (donde la distancia se calcula usando los contextos de los &lt;em&gt;items&lt;/em&gt;, ej. distancia cosena de los &lt;strong&gt;tf-idf&lt;/strong&gt;). Nuevamente usando usuarios (&lt;em&gt;user studies&lt;/em&gt;) es trivial preguntandoles.&lt;/li&gt;
  &lt;li&gt;Diversidad: a veces al presentar una lista de elementos queremos que sean variados entre ellos (ej. al sugerir hoteles para vacaciones no queremos que todas sean del mismo lugar). Nuevamente podemos ayudarnos usando metricas de distancia para penalizar aquellos algoritmos que entreguen resultados muy similares entre si.&lt;/li&gt;
  &lt;li&gt;Utilidad(es): maximizar utilidades, sea para la empresa dueña del sistema o para el usuario.&lt;/li&gt;
  &lt;li&gt;Riesgo: en algunos casos una recomendacion puede estar asociada a un cierto riesgo (ej. acciones) y el riesgo puede ser algo positivo o negatvo dependiendo del usuario y la situacion. Se recomienda considerar la varianza al comparar dos sistemas.&lt;/li&gt;
  &lt;li&gt;Robustez: es la estabilidad del sistema a informacion falsa, o a cargas elevadas (muchos &lt;em&gt;requests&lt;/em&gt;). Podemos simular ataques para comparar sistemas en el primer caso.&lt;/li&gt;
  &lt;li&gt;Privacidad: no revelar las preferencias del usuario.&lt;/li&gt;
  &lt;li&gt;Adaptabilidad: en situaciones donde los intereses cambian rapido (ej. noticias de ultimo momento) es importante que el sistema pueda adaptar sus sugerencias rapido. Podemos usar medidas de desigualdad (Gini, entropia) para validar los cambios en las sugerencias al variar un perfil.&lt;/li&gt;
  &lt;li&gt;Escalabilidad: que el sistema pueda trabajar con &lt;em&gt;datasets&lt;/em&gt; grandes, crecientes. Podemos evaluar la complejidad computacional en relacion al tamaño de la BD.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;comentarios&quot;&gt;Comentarios:&lt;/h3&gt;

&lt;p&gt;Mi primer y mas importante comentario es una apreciacion general sobre como el autor enfatiza las diferencias entre los distintos campos de aplicacion de sistemas recomendadores y como no se puede estandarizar una metrica porque para cada uno las necesidades (en terminos de las propiedades arriba) son distintas.
Asi se plantean varios ejemplos diferentes donde podemos notar la importancia de una propiedad por encima de otras (privacidad mas importante que exactitud en algunos casos, utilidad del sistema antes de cobertura en otros, etc).&lt;/p&gt;

&lt;p&gt;Tambien aprovecho de destacar la sub-seccion que trata sobre la significancia de los resultados usando valores p, intervalos de confianza, y como comparar resultados obtenidos &lt;em&gt;paired&lt;/em&gt; o &lt;em&gt;unpaired&lt;/em&gt;.
Me parece relevante dado que la tendencia general es asumir que aquel sistema con mejor resultado usando una metrica es mejor, pero no se considera la probabilidad de que esa metrica favorezca a un sistema por encima de otro.
Aprovecho de conectar esto al articulo de la semana 1 donde usamos el umbral inferior del intervalo de confianza para tener certeza de que la metrica usada representa efectivamente el valor real (ie, la calidad del sistema).&lt;/p&gt;

&lt;p&gt;El &lt;em&gt;paper&lt;/em&gt; cubre un area sorprendentemente amplia de informacion y logra estructurarla bastante bien. 
Por ejemplo para la mayoria de las propiedades presentadas el autor menciona formas de medirla y a veces da mas de una para considerar los distintos metodos de evaluacion.
El autor logra comunicar sutiliezas de cada una de las propiedades que las hacen dificiles de evaluar y conecta estas a las características propias de &lt;em&gt;datasets&lt;/em&gt; de diferentes fuentes (y con distintos enfoques).
Ejemplo de esto es cuando sugiere una forma de construir el &lt;em&gt;test set&lt;/em&gt; para evaluar el orden de las predicciones donde tenemos datos solo sobre si el usuario oyo una cancion entera, la adelanto, o no la oyo.
Otro ejemplo que encuentro notable es la forma de construir el &lt;em&gt;test set&lt;/em&gt; para evaluar la novedad de &lt;em&gt;items&lt;/em&gt; presentados (penalizando por sugerir elementos que el usuario si consumio, pero en el corto plazo).&lt;/p&gt;

&lt;p&gt;Mi unica critica es que el autor no menciona la utilidad de ensamblar modelos con enfoques a distintas propiedades para luego combinar sus resultados.
Esta muy relacionado a la materia que estamos viendo actualmente en clases (modelos hibridos) dado que considera aportes de mas de un modelo.
Ensamblar, por ejemplo, un modelo que maximice la exactitud de las predicciones y devuelva una lista ordenada de resultados con otro modelo que entregue un resultado novedoso seria una excelente forma de incluir un poco de novedad a las predicciones pero sin perder precision.
Justamente esto es lo que hace netflix al sugerir en categorias distintas “parecido a lo que has visto” y “tambien te podria interesar”.&lt;/p&gt;

&lt;p&gt;Se entiende que el autor no se explaye en combinaciones de propiedades (por cantidad exponencial de combinaciones que habrian) pero me habria gustado que se mencionara que para cada aplicacion puede ser importante mas de una, y que se abordara a grandes rasgos la forma de combinar varios modelos o varias metricas en una.&lt;/p&gt;
</description>
        <pubDate>Thu, 30 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/recsys/2018/08/30/Semana-3.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/recsys/2018/08/30/Semana-3.html</guid>
        
        
        <category>Recsys</category>
        
      </item>
    
      <item>
        <title>RecSys Semana 2</title>
        <description>&lt;h2 id=&quot;comentario-collaborative-filtering-for-implicit-feedback-datasets-pdf&quot;&gt;Comentario: Collaborative Filtering for Implicit Feedback Datasets, &lt;a href=&quot;http://yifanhu.net/PUB/cf.pdf&quot;&gt;PDF&lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;resumen&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;Los sistemas recomendadores utilizan distintos tipos de &lt;em&gt;input&lt;/em&gt; para lograr sus objetivos de mejorar la experiencia del usuario. 
La forma mas conveniente para el analisis de esta informacion es el &lt;em&gt;feedback&lt;/em&gt; explicito, por lo que la mayoria de la literatura existente esta concentrada en procesar este tipo de informacion.
Sin embargo, muchas veces este no esta disponible pero podemos intentar inferir las preferencias del usuario usando el mas abundante &lt;em&gt;feedback&lt;/em&gt; implicito (ejs, historial de compras/busquedas, patrones de busqueda, movimientos del &lt;em&gt;mouse&lt;/em&gt;).
La traduccion de algoritmos pensados para que modelos &lt;em&gt;feedback&lt;/em&gt; explicito funcionen con datos de tipo implicito puede no ser directa por varias caracteristicas:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;no hay &lt;em&gt;feedback&lt;/em&gt; negativo&lt;/li&gt;
  &lt;li&gt;el &lt;em&gt;feedback&lt;/em&gt; implicito es inherentemente ruidoso&lt;/li&gt;
  &lt;li&gt;no puede asumirse que el valor numerico exprese preferencia, solo confianza (es mas probable que al usuario le guste algo que ha visto muchas veces).&lt;/li&gt;
  &lt;li&gt;la evaluacion puede tener caracterisiticas que necesiten medidas especiales.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tradicionalmente se han usado modelos de vecindad (&lt;em&gt;heighborhood models&lt;/em&gt;) para filtrado colaborativo (generalmente mejores que los &lt;em&gt;content based&lt;/em&gt;) pero este tipo de modelos tienen una desventaja, no permiten distinguir entre preferencia y confianza (del sistema en la preferencia).
Los autores toman esto en consideracion y eligen usar modelos de factores latentes (descubren caracteristicas latentes que explican los datos) en particular, &lt;strong&gt;SVD&lt;/strong&gt;.
Este descompone la matriz de interacciones usario-item para obtener representaciones de los usuario e items en un espacio conjunto que pueda ser utilizado para predecir si el usuario &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;u&lt;/code&gt; interactura o no con el item &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; (binario, no cuantas veces).&lt;/p&gt;

&lt;p&gt;Por el ruido que probablemente contengan las observaciones obtenidas con &lt;em&gt;feedback&lt;/em&gt; implicito (clicks accidentales, etc) convendría considerar de distinto modo aquellos items en los que tenemos mayor confianza.
Esto lo logran los autores penalizando en mayor medida en la funcion de perdida por errores en la prediccion de aquellos items para los que se tiene mayor confianza &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c_ui&lt;/code&gt;.
Luego, para evitar &lt;em&gt;overfitting&lt;/em&gt; utilizan terminos regularizadores forzando a que las matrices de embedding (tanto para usuarios como items) se complejizen demasiado.
Por ultimo, se propone como alternatica a &lt;em&gt;SGD&lt;/em&gt; el uso de &lt;em&gt;alternating least squares&lt;/em&gt; como tecnica de optimizacion, para lograr que el tiempo de entrenamiento escale linealmente con el tamaño de la libreria.
Efecto secundario de esto es que pueda reescribirse el modelo como uno lineal que predice la preferencia por el item &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; como suma de las confianzas de acciones pasadas (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&apos;&lt;/code&gt;) ponderadas por la similaridad entre los items &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; e &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&apos;&lt;/code&gt;.
Lo anteior nos permite explicar la preferencia por el item &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; considerando los elementos que son similares a este para el usuario &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;u&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;resultados&quot;&gt;Resultados&lt;/h3&gt;

&lt;p&gt;Usaron datos recolectados de cajas de television que contenian 32 millones de pares usuario-item (cuantas veces cada usuario vio cada item).
Luego escalaron logaritmicamente los valores para calcular las confianzas y midieron el rendimiento del modelo usando un set de test recolectado similarmente.
Como metrica para el rendimiento usan &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rank&lt;/code&gt; que considera la diferencia entre el valor observado para un par usuario-item vs. la importancia otorgada al par por el modelo.&lt;/p&gt;

&lt;p&gt;Se comparan 3 modelos: &lt;em&gt;most-popular&lt;/em&gt;, &lt;em&gt;neighborhood based&lt;/em&gt; y el propio con distintas dimensionalidades para la reprenentacion en el espacio latente.
Observan:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;el mejor modelo es el propuesto y este mejora con numeros mayores de factores latentes.&lt;/li&gt;
  &lt;li&gt;el mejor modelo para incluir en el top 1% items que verdaderamente son interesantes para el usuario es el nuevo (incluso eliminando secuelas).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;comentarios&quot;&gt;Comentarios&lt;/h3&gt;

&lt;h4 id=&quot;negativo&quot;&gt;Negativo:&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;los valores de alfa y lambda (usados como ponderadores en la formula de confianza y el termino regularizador respectivamente) deben ser determinados usando prueba y error.&lt;/li&gt;
  &lt;li&gt;la metrica elegida contradice lo afirmado antes en el mismo paper (que el valor numerico indica confianza, no preferencia) diciendo &lt;em&gt;“watching a program is an indication of liking it”&lt;/em&gt;. Sin embargo, se entiende que requieren una metrica para comparar y el par puede servir como &lt;em&gt;proxy&lt;/em&gt; (aunque no optimo).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;positivo&quot;&gt;Positivo:&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;Se valida la eleccion de incluir la confianza en la funcion de perdida probando otras funciones que no la incluyen.&lt;/li&gt;
  &lt;li&gt;Se valida la conversion de pares &lt;em&gt;user-item views&lt;/em&gt; en p_i (booleano que indica si usuario &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;u&lt;/code&gt; vio item &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; sin considerar cuantas veces).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;comentario-matrix-factorization-techniques-for-recommender-systems&quot;&gt;Comentario: Matrix Factorization Techniques For Recommender Systems&lt;/h2&gt;

&lt;h3 id=&quot;resumen-1&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;Se comienza haciendo un resumen de distintos metodos utilizados en sistemas recomendadores que no incluyo dado que se parece bastante al survey en mi post anterior &lt;a href=&quot;https://ceyzaguirre4.github.io/Semana-1/&quot;&gt;(link)&lt;/a&gt;.
A grandes rasgos introduce el concepto y diferencia entre sistemas basados en filtrado por contenido y aquellos que lo hacen con filtrado colaborativo.
Tambien nombra como principales areas en el filtrado colaborativo aquellas que comparan vecindades y la mas enfocada en extraccion de representaciones ricas en un nuevo espacio, enfocandose en esta ultima area, particularmente en metodos de factorizacion de matrices.&lt;/p&gt;

&lt;p&gt;En mapear usuarios e items a espacios conjuntos se buscan matrices de embedding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;q&lt;/code&gt; (para usuarios e items respectivamente) tal que el producto interno \(p_u q_i\) devuelva el rating estimado.
Una forma de obtener estas matrices resulta de obtener la representacion &lt;strong&gt;SVD&lt;/strong&gt; (&lt;em&gt;singular value descomposition&lt;/em&gt;) de la matriz de interacciones usuario-item (preocupandose de imputar los valores faltantes o bien regularizar los embeddings obtenidos para considerar la &lt;em&gt;sparseness&lt;/em&gt; de la conjunta).
El entrenamiento para obtener los valores en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;q&lt;/code&gt; pueden obtenerse usando &lt;strong&gt;SGD&lt;/strong&gt; para minimizar la funcion de perdida regularizada. De otra manera puede usarse &lt;strong&gt;ALS&lt;/strong&gt; (&lt;em&gt;alternating least squares&lt;/em&gt;) alternando entre asumir fijos los \(q_i\) y los \(p_u\).
Esta ultima tecnica ayuda a paralelizar y evita iterar sobre todos los datos en situaciones donde la matriz a descomponer esta mas populada.&lt;/p&gt;

&lt;p&gt;Otras extensiones al modelo son:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;tomar en cuenta los &lt;em&gt;bias&lt;/em&gt; (sea de usuarios o items) mediante un termino regularizador.&lt;/li&gt;
  &lt;li&gt;considerar ademas fuentes implicitas de datos.&lt;/li&gt;
  &lt;li&gt;considerar &lt;em&gt;biases&lt;/em&gt;, preferencias e interacciones como funciones del tiempo para modelar variaciones temporales.&lt;/li&gt;
  &lt;li&gt;añadir metricas de certeza/confianza para reflejar la seguridad del modelo en una prediccion realizada.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;comentarios-1&quot;&gt;Comentarios&lt;/h3&gt;

&lt;p&gt;El escrito hace un excelente trabajo en comunicar la importancia que han tenido los metodos de factorizacion de matrices para mejorar los resultados de sistemas recomendadores. Ademas, lo hace desde la perspectiva de personas que participaron en el netflix prize, aterrizando el tema.
Lo que puedo criticar es no haberse explayado en las ventajas de obtener representaciones conjuntas (mismo espacio vectorial) para aumentar la explicabilidad del modelo como lo hizo &lt;a href=&quot;http://yifanhu.net/PUB/cf.pdf&quot;&gt;Collaborative Filtering for Implicit Feedback Datasets&lt;/a&gt; o para obtener recomendaciones directamente usando distancias entre usuarios/items.
La figura dos explicitamente muestra un usuario (&lt;em&gt;Dave&lt;/em&gt;) y su relacion con distintas peliculas en el espacio compartido, pero no se comenta sobre sus preferencias en relacion a los vecinos mas cercanos.
Un analisis poco profundo de las implicancias de embeber juntos usuarios e items habria ilustrado la relevancia de este tipo de sistemas de factores latentes de mejor manera que simplemente mostrar resultados para justificar su uso.
Además, considerar las distancias entre usuarios e items nos da la intuicion de porque funciona el sistema y hasta explica la formulacion matematica usada en tanto el producto punto en \(\hat r_{ui} = p_u q_i\) puede ser interpretado como el cuadrado de la distancia euclidiana entre los elementos en su espacio conjunto.
&lt;strong&gt;Asi, creo que el autor se equivoca al no incluir estas conclusiones al presentar modelos de factores latentes ya que podria haber servido para ayudar al lector a entender lo que esta pasando y darle la intuicion de por que funciona.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Por ultimo, no puedo criticarlo por no profundizar en las matematicas tras la descomposicion matricial, pero me habria encantado que se elaborara en el calculo de los gradientes a traves de la descomposicion en valores singulares SVD.&lt;/p&gt;
</description>
        <pubDate>Wed, 22 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/recsys/2018/08/22/Semana-2.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/recsys/2018/08/22/Semana-2.html</guid>
        
        
        <category>Recsys</category>
        
      </item>
    
      <item>
        <title>RecSys Semana 1</title>
        <description>&lt;h2 id=&quot;comentario-how-not-to-sort-by-average-rating-evan-miller-blog&quot;&gt;Comentario: How not to sort by Average Rating, &lt;a href=&quot;http://www.evanmiller.org/how-not-to-sort-by-average-rating.html&quot;&gt;Evan Miller Blog&lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;problema&quot;&gt;Problema&lt;/h3&gt;

&lt;p&gt;EL articulo de Blog trata sobre recomendacion de articulos usando opiniones de usuarios en forma de &lt;em&gt;likes&lt;/em&gt; (o &lt;em&gt;dislikes&lt;/em&gt;). 
Se escapa del clasico paradigma de sistemas recomendadores que hemos visto hasta el momento donde las valoraciones existen como rankings.
El autor critica la forma de recomendar que utilizan algunas paginas y las critica, para luego sugerir una forma de recomendar que sea robusta a las faltas de las mencionadas.&lt;/p&gt;

&lt;p&gt;Para ordenar por preferencia (y asi poder recomendar) algunas paginas calculan el &lt;em&gt;puntaje&lt;/em&gt; del &lt;em&gt;item&lt;/em&gt; restando a las valoraciones positivas las negativas. 
El problema que esto tiene es que aquellas paginas con muchas valoraciones pueden tener un gran &lt;em&gt;puntaje&lt;/em&gt; aunque tengan casi igual proporcion de valoraciones positivas vs negativas (ie, ariticulo mediocre).&lt;/p&gt;

&lt;p&gt;Otras paginas evitan el problema calculando el procentaje como la proporcion de valoraciones positivas respecto al total. 
Esta construccion conserva la informacion que nos intersa pero falla cuando un &lt;em&gt;item&lt;/em&gt; tiene pocas valoraciones.
Un ejemplo representativo de esto es un articulo con 100% de aprobacion que solo ha sido puntuado por su autor (el mitico &lt;em&gt;autolike&lt;/em&gt;).
Se entiende por lo mismo que mientras no hayan suficientes valoraciones es poco creible que la proporcion sea un buen aproximador de la calidad del &lt;em&gt;item&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;solucion-propuesta&quot;&gt;Solucion Propuesta&lt;/h3&gt;

&lt;p&gt;Dado que estabamos hablando de la confianza que tenemos en que proporcion estime correctamente la calidad del &lt;em&gt;item&lt;/em&gt; resulta razonable que usemos intervalos de confianza. 
Mas especificamente, en que usemos la cota inferior del intervalo de confianza (el minimo valor que podria tomar la verdadera calidad medido en proporcion de &lt;em&gt;likes&lt;/em&gt;).
Asi, usando una confianza de 0.95 podemos afirmar con 95% de certeza que la puntuacion es mayor o igual a la cota inferior.&lt;/p&gt;

&lt;h3 id=&quot;discusion&quot;&gt;Discusion&lt;/h3&gt;

&lt;h4 id=&quot;negativos&quot;&gt;Negativos&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;En primer lugar, una debilidad de usar este sistema es que esconde los elementos nuevos.
Esto sucede porque mientras menor sea el total de valoraciones mas extremos son los valores de las cotas respecto a la media.
En otras palabras independiente de lo bueno que sea un &lt;em&gt;item&lt;/em&gt;, sera poco recomendado mientras no adquiera una masa critica de valoraciones.
Esto establece un circulo vicioso porque es poco probable que suficientes personas voten por el articulo si este no es recomendado.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Construccion provista no es compatible con otras formas de puntuar (ej, x estrellas de 5) sin conversiones previas entre los formatos.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;positivos&quot;&gt;Positivos&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Usar Wilson Score combina Most popular (usando como proxy de popularidad el numero de valoraciones) con los valores reales de los ratings para sugerir mejor en escenarios donde un item tiene pocas valoraciones.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Usar intervalos de confianza hacen que el sistema sea mas robusto a ataques que serian graves si solo se usara la proporcion como metrica. 
Por ejemplo, si un grupo de personas (o un individuo con bots) deciden puntuar mal el &lt;em&gt;item&lt;/em&gt; injustamente.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;neutral&quot;&gt;Neutral&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;La pagina trabaja siempre con una certeza de 95% para calcular la cota inferior para el umbral de confianza. Alternativamente podemos usar distintos valores para acercar los valores a la proporcion observada (disminuyendo el valor, ej. 0.85 de reddit), o podemos aumentar nuestra certeza aumentando el valor (ej. 0.99).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;extensiones-posibles&quot;&gt;Extensiones posibles&lt;/h3&gt;

&lt;p&gt;El concepto estadistico de intervalos de confianza no esta restringido a &lt;em&gt;likes&lt;/em&gt; o &lt;em&gt;deslikes&lt;/em&gt;. Puede aplicarse el mismo concepto para predecir la cota inferior del umbral de confianza para otras metricas como lo son &lt;em&gt;x estrellas de 5&lt;/em&gt; o un valor cualquiera de un dominio continuo.&lt;/p&gt;

&lt;p&gt;Si asumimos que la distribucion de datos es normal y que los datos son aleatorios e independientes podemos calcular la cota inferior del intervalo de confianza para el promedio de las valoraciones. 
Este valor representara la puntuacion minima que podria tomar la verdadera calidad de un articulo y se calcula usando el promedio de valoraciones como estimador de calidad.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://www.ub.edu/stat/GrupsInnovacio/Statmedia/demo/Temas/Capitulo8/Images/normal5.gif&quot; style=&quot;width: 250px; display:block; margin:auto&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;comentario-collaborative-filtering-recommender-systems-in-the-adaptive-web-&quot;&gt;Comentario: Collaborative filtering recommender systems, &lt;a href=&quot;https://pdfs.semanticscholar.org/d17d/3fa8083c4de1f5545446a1f59da54a1dba21.pdf&quot;&gt;In The adaptive web &lt;/a&gt;&lt;/h2&gt;

&lt;h3 id=&quot;resumen&quot;&gt;Resumen&lt;/h3&gt;

&lt;p&gt;El &lt;em&gt;paper&lt;/em&gt;  es un survey de sistemas colaborativos que definen como el filtrado o evaluacion de &lt;em&gt;items&lt;/em&gt; usando las opiniones de otras personas. 
Al entender de los autores la base para este filtrado tiene sus origenes en el &lt;em&gt;boca a boca&lt;/em&gt; y con el advenimiento de los computadores y la web se abre la posibilidad de analizar fuentes masivas de datos. 
Dado que inteligencias artificiales que automaticen el proceso no existen (al momento de escribirse el &lt;em&gt;paper&lt;/em&gt;) se utilizan jucios humanos en la forma de ratings para avanzar el estado del arte. 
Entendemos que los &lt;em&gt;ratings&lt;/em&gt; pueden tomar una variedad de formas (escalar, binario, unario) y pueden ser recolectados explicitamente o implicitamente.
La importancia de esta forma de filtrado en el contexto de la web (contexto que envuelve el articulo) es obvio, adaptar el contenido a las necesidades de cada usuario.&lt;/p&gt;

&lt;p&gt;Para lograr su objetivo los diseñadores deben primero identificar las tareas que el usuario quiere automatizadas en el sistema (encontrar nuevos &lt;em&gt;item&lt;/em&gt;s para mi/mi grupo, encontrar personas con gustos parecidos, aconsejar sobre un producto especifico, etc.).
En segundo lugar deben identificar las funcionalidades que se ofreceran (recomendar &lt;em&gt;item&lt;/em&gt;s, puntuar un &lt;em&gt;item&lt;/em&gt;, busqueda constreñida) y analizar el dominio para ver si es propicio a tecnicas de este estilo segun los datos (muchos items y puntuaciones, muchos usuarios, usuarios puntuan mucho).
Por ultimo se debe analidar la necesidad/validez de comparar usuarios (&lt;em&gt;items&lt;/em&gt; son distintos en los subjetivo, usuarios tienen gustos agrupables) y la utilidad de las puntuaciones (&lt;em&gt;items&lt;/em&gt; persisten, los gustos de los usuarios se mantienen).&lt;/p&gt;

&lt;p&gt;Una forma alternativa para lograr el mismo objetivo (de realizar recomendaciones) es usar filtrado por contenido.
Los autores comentan sobre la utilidad de estos sistemas para sugerir &lt;em&gt;items&lt;/em&gt; no puntuados, pero destacan que son mas propensos a la sobre-especializacion (perdiendo novedad y/o serendipia). 
Terminan la comparacion mencionando un &lt;em&gt;approach&lt;/em&gt; hibrido (combinacion de ambos sea automatica o manual).&lt;/p&gt;

&lt;p&gt;Para lograr hacer recomendaciones se necesitan modelos que los autores dividen en &lt;em&gt;memory-based&lt;/em&gt; (requieren que todos los &lt;em&gt;ratings&lt;/em&gt;, &lt;em&gt;items&lt;/em&gt; y &lt;em&gt;users&lt;/em&gt; esten almacenados en memoria y por tanto no escalan bien en el mundo real) y &lt;em&gt;model-based&lt;/em&gt; (periodicamente crean un resumen de los patrones existentes). 
El paper tambien explora la distinccion segun si se basan en un modelo probabilistico o no destacando en la primera categoria redes bayesianas.
Para la segunda se resalta &lt;em&gt;nearest neighbors&lt;/em&gt; en el espacio de usuarios (&lt;em&gt;rating&lt;/em&gt; es suma ponderada y normalizada de las puntuaciones de personas similares) o en el espacio de &lt;em&gt;items&lt;/em&gt; (&lt;em&gt;rating&lt;/em&gt; es suma ponderada de puntuaciones que el usuario hizo a elementos similares encontrados observando puntuaciones de otros usuarios).
Las tareas puede hacerse mas eficiente usando tecnicas para no considerar todos los usuarios (considerar los k vecinos mas cercanos, &lt;em&gt;subsampling&lt;/em&gt;, &lt;em&gt;clustering&lt;/em&gt;) para el primero, y pruning y/o reduccion de dimensionalidad para el segundo.
Por ultimo (para los no-probabilisticos) se considera la mineria de reglas asociativas (&lt;em&gt;association rule mining&lt;/em&gt;) pero se desecha por su ineficiencia en el dominio de filtrado colaborativo.&lt;/p&gt;

&lt;p&gt;Independiente del algoritmo elegido los autores nombran problemas generalmente ignorados que los algoritmos tienen que superar como cuando hay pocos ratings (soluciones para estos casos: ignorar, ajustar calculos, incorporar un conocimiento previo), la distinccion entre prediccion y recomendacion (solo para el primer caso el sistema tiene que conocer todos los &lt;em&gt;items&lt;/em&gt;), y hacer explicita la confianza del algoritmo en la decision que tomo.&lt;/p&gt;

&lt;p&gt;Sobre la adquisicion de &lt;em&gt;ratings&lt;/em&gt; se explica que aquellos obtenidos explicitamente ofrecen una descripcion mas precisa de las preferencias de los usuarios, pero son mas dificiles de recolectar (aunque estudios muestran que es mas facil de lo inicialmente esperado por beneficios sociales y practicos). 
Por otro lado, aquellos obtenidos &lt;em&gt;implicitamente&lt;/em&gt; (obsercando el comportamiento del usuario) pueden ser imprecisos pero una vez que se obtienen en cantidades suficientes disminuye la incertidumbre dado que se pueden acumular (por votacion o promedio) y la incertidumbre se reduce por agregacion.&lt;/p&gt;

&lt;p&gt;Los &lt;em&gt;ratings&lt;/em&gt; adquiridos son usualmente usados luego para evaluar el rendimiento del sistema pero no hay una metrica aceptada por todos.
La mas frecuente es &lt;em&gt;accuracy&lt;/em&gt; que mide la capacidad de un sistema de predecir la puntuacion que un usuario dara a un &lt;em&gt;item&lt;/em&gt; (&lt;em&gt;predictive accuracy&lt;/em&gt;) o la utilidad de una lista recomendada para un cierto usuario (&lt;em&gt;rank accuracy&lt;/em&gt;).
Otras metricas usadas miden &lt;em&gt;novelty/serendipity&lt;/em&gt; (capacidad para recomendar &lt;em&gt;items&lt;/em&gt; desconocidos), &lt;em&gt;coverage&lt;/em&gt; (cobertura, porcentaje de &lt;em&gt;items&lt;/em&gt; potencialmente recomendables), &lt;em&gt;learning rate&lt;/em&gt; (cuan rapido se vuelve efectivo), &lt;em&gt;confidence&lt;/em&gt; (seguridad de prediccion), además de otros criterios como la satisfaccion de los usuarios o analisis de trafico/compras del sistema.&lt;/p&gt;

&lt;!--Son importantes estas metricas alternativas porque *accuracy* no considera todas las necesidades reales del usuario como lo son la facilidad de uso, ... social navigation ... explanation --&gt;

&lt;p&gt;Por ultimo es importante reconocer la importancia del uso y almacenamiento de los datos recolectados que aseguren la privacidad del usuario para mantener la integridad de esta informacion.
Tambien es importante resguardar el servicio de aquellos que intenten romperlo usando los &lt;em&gt;ratings&lt;/em&gt; en otro modo que el esperado.&lt;/p&gt;

&lt;h3 id=&quot;comentarios&quot;&gt;Comentarios&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Si bien se nombra el temor del usuario hacia el mal uso de los datos el escrito considera todo desde la confianza del usuario y los costos/beneficios para el sistema.
El uso etico de los datos por el bien del usuario se ha hecho mas relevante en el ultimo año (2018) y aprovecho de destacarlo por lo mismo.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;El &lt;em&gt;paper&lt;/em&gt; no puede seguir siendo considerado un &lt;em&gt;comprehensive survey&lt;/em&gt; del estado del arte por su edad. 
Entre los temas no se tratan destaca el uso de redes neuronales que dirigen el estado del arte actualmente.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;El metodos presentados no hacen uso de metadata que podria ser relevante como fecha en la que se realizo la puntuacion u otras formas menos obvias.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Creo que el enfoque del paper esta concentrado mas de lo necesario en predecir predicciones. El verdadero objetivo es servir al usuario o mantenerlo interesado/usando el servicio. Esto puede ser logrado usando RL.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Wed, 15 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/recsys/2018/08/15/Semana-1.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/recsys/2018/08/15/Semana-1.html</guid>
        
        
        <category>Recsys</category>
        
      </item>
    
      <item>
        <title>Adaptive Computation Time</title>
        <description>&lt;h3 id=&quot;top-down-explanation-of-graves-2015-paper-adaptive-computation-time-for-recurrent-neural-networks&quot;&gt;Top-Down explanation of Graves’ 2015 paper &lt;a href=&quot;https://arxiv.org/abs/1603.08983&quot;&gt;“Adaptive Computation Time for Recurrent Neural Networks”&lt;/a&gt;&lt;/h3&gt;

&lt;h4 id=&quot;1-motivation&quot;&gt;1. Motivation&lt;/h4&gt;

&lt;p&gt;Graves states “evidence that increased depth leads to more performant networks is by now inarguable, and recent results show that increased sequence length can be similarly beneficial”.
The underlying principle seems to imply that putting your under-achieving model inside a recurrent network and have it iterate a fixed number of times (100 if you want) to observe better results.
Of course, in practice the opposite seems to hold.
The resulting model will be much more computationally intensive, will overfit to data easily and you probably wont even see gains in performance.&lt;/p&gt;

&lt;p&gt;So what we need is a way to use these increased sequence lengths when more computation is required but at the same time prevent the network from overfitting.
In other words, we want to increase the sequence length when needed, but limit complexity when it isn’t.
How can we achieve this? By letting the network determine how many iterations it will run and including the number of iterations (or a proxy of this) in the loss function we should achieve a network that will iterate only when it helps to obtain a more accurate answer.&lt;/p&gt;

&lt;p&gt;As we push towards a recurrent network that determines how many times it will iterate a new problem arises.
How will the network determine its number of iterations? And how to make this differentiable? Having the network determine this limit &lt;em&gt;a priori&lt;/em&gt; “would be equivalent to determining the Kolmogorov complexity of the data (and hence solving the halting problem)” (Graves, 2015).
The solution proposed by Graves is to let the network &lt;em&gt;halt&lt;/em&gt; when it is ready instead.&lt;/p&gt;

&lt;p&gt;Pseudo code:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;is_ready&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;answer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# run model to update answer and check if ready
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;answer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_ready&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;run_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_ready&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;2-halting&quot;&gt;2. Halting&lt;/h4&gt;

&lt;p&gt;For each iteration the network outputs an answer and a SIGMOIDAL halting value. The magnitude of the contribution of any iteration to the final answer $y_t$ is equal to the sub answer (the answer given by the iteration) multiplied by its probability of being relevant to the final answer $p_n$.&lt;/p&gt;

\[y = \sum_{n=1}^{\infty} p_n y_n\]

&lt;p&gt;In order to limit computation we want all probabilities to be zero for $n &amp;gt; N$ (so that running for more iterations doesn’t change the answer).&lt;/p&gt;

\[p_n = \begin{cases} R(n) &amp;amp;\text{if } n \geq N\\ h_n &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;A function $N$ is used to determine the first $n’$ for which the sum of all halting probabilities is greater than one minus a small epsilon. This is so that after one iteration the sigmoidal (and therefore never quite $1$) value of $h_n$ can be enough to halt if only one iteration is needed.&lt;/p&gt;

\[N = min\{ n&apos; : \sum_{n=1}^{n&apos;} h_n \geq 1 - \epsilon \}\]

&lt;p&gt;For each iteration $n$ before $n’$ the probability is equal to its halting value.
Since the sum of all probabilities has to be equal to one (and we want to limit computation), for $n = N$ the probability $p_n$ will be equal to the remainder $R = 1 - \text{ the sum of all previous probabilities}$.&lt;/p&gt;

\[R = 1 - \sum_{n=1}^{N-1}p_n\]

&lt;p&gt;This way, for any $n &amp;gt; N$ the probability will be zero ($R = 1 - 1$), so we can get away with not computing them and the answer wont change, so:&lt;/p&gt;

\[y = \sum_{n=1}^{\infty} p_n y_n\]

&lt;p&gt;Finally, we add a proxy of total computation $\rho = N + R$ to the loss to encourage reduced computation and backpropagate through this.&lt;/p&gt;

\[\hat{L} = L(x,y) + \rho\]

&lt;h4 id=&quot;3-how-it-works&quot;&gt;3. How it works&lt;/h4&gt;

&lt;p&gt;The main mechanism through which ACT operates is a non-differentiable piece-wise function.
As such, the backpropagation of gradients through it is non-trivial.&lt;/p&gt;

&lt;p&gt;Looking at the regularization term in the loss function $\rho$ we observe that no gradient can be propagated through $N$ and therefore adding $\rho$ to the loss is functionally equivalent to adding the remainder $R$.
From it’s definition we observe that again no gradient can be propagated through the constant value $1$.
Taken together this means that by adding $\rho$ to the loss function to minimize $text{loss} + \text{computation}$ we are actually minimizing $text{loss}$ while maximizing $\sum_{n=1}^{N-1}p_n$.
By encouraging the network to maximize the halting probabilities of earlier steps we bias the network towards lower computation.
This mechanism can be easily understood by considering that the $N$th step (the last answer-changing step) will be achieved earlier if, for instance, the first step greatly increases it’s halting probability.&lt;/p&gt;

&lt;h4 id=&quot;4-generalizing-towards-recurrent-neural-networks&quot;&gt;4. Generalizing towards recurrent neural networks&lt;/h4&gt;

&lt;p&gt;In Graves’ work the process described above is repeated for each element $t$ in a sequence using an RNN. For each of these besides outputing $y_t$ (the $y$ for element $t$ of the sequence) a hidden state $s_t$ is computed:&lt;/p&gt;

\[y = \sum_{n=1}^{\infty} p_n y_n\]

&lt;p&gt;Where $p_t^n \text{ is } p_n \text{ in timestep } t$.&lt;/p&gt;

&lt;p&gt;And $N(t)$ is the first $n_t$ for which the sum of all $h_t^n$ is greater than one minus small epsilon.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/ACT.png&quot; alt=&quot;unrolled ACT from paper&quot; /&gt;&lt;/p&gt;

&lt;!-- [&lt;img src=&quot;/images/ACT.png&quot; style=&quot;width: 600px;&quot;/&gt;](/) --&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;In blue is the process for one element of the sequence (as described in &lt;a href=&quot;#2.-Halting&quot;&gt;2.&lt;/a&gt;). For each one of these elements $N(t)$ iterations are performed ($n = 1$ marked in red).&lt;/p&gt;

&lt;p&gt;I haven’t talked about how to obtain any of the parameters mentioned (halting_values, sub_answers, sub_hidden_states) because it depends greatly on the implementation. A standard RNN (as shown in the image above) initializes its hidden state $s_t^1$ (when $n = 1$) to $S(s_{t-1}, x_t)$. In other words, for the first iteration of any element in the sequence the hidden state is a function $S$ applied to the COMPLETE hidden state at timestep $t - 1$ and the element of the sequence at index $t$. For any other iteration $s_t^n$ is $S(s_t^{n-1}, x_t)$.&lt;/p&gt;

\[s_t^n = \begin{cases}
S(s_{t-1}, x_t) \text{ if } n = 1 \\
S(s_t^{n-1}, x_t) \text{ otherwise}
\end{cases}\]

&lt;p&gt;Then both $y_t^n$ and $h_t^n$ are calculated by feeding the hidden state $s_t^n$ through feedforward layers $W_y$ and $W_h$ (with bias values) respectively. The output for the halting value $h_t^n$ is then squashed using a Sigmoid.&lt;/p&gt;
</description>
        <pubDate>Sun, 12 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://ceyzaguirre4.github.io/ai/2018/08/12/ACT.html</link>
        <guid isPermaLink="true">https://ceyzaguirre4.github.io/ai/2018/08/12/ACT.html</guid>
        
        
        <category>Ai</category>
        
      </item>
    
  </channel>
</rss>
