<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[BMM Talks Blog]]></title><description><![CDATA[BMM Talks Blog]]></description><link>https://bmmtalks.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 12 Sep 2026 03:28:49 GMT</lastBuildDate><atom:link href="https://bmmtalks.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Beyond ReLU: How the Snake Activation Fixes Neural Networks' Periodic Learning Problem]]></title><description><![CDATA[Introduction: The Curious Case of Periodic Functions
If you've ever trained a neural network on seasonal time series data only to watch it diverge dramatically when forecasting beyond the training period, you've encountered a fundamental limitation o...]]></description><link>https://bmmtalks.hashnode.dev/beyond-relu-how-the-snake-activation-fixes-neural-networks-periodic-learning-problem</link><guid isPermaLink="true">https://bmmtalks.hashnode.dev/beyond-relu-how-the-snake-activation-fixes-neural-networks-periodic-learning-problem</guid><dc:creator><![CDATA[Vladislav Minashkin]]></dc:creator><pubDate>Sun, 05 Oct 2025 12:21:33 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction-the-curious-case-of-periodic-functions">Introduction: The Curious Case of Periodic Functions</h2>
<p>If you've ever trained a neural network on seasonal time series data only to watch it diverge dramatically when forecasting beyond the training period, you've encountered a fundamental limitation of standard deep learning architectures. Despite their reputation as <strong>universal function approximators</strong>, conventional neural networks with activation functions like ReLU, tanh, and sigmoid possess a critical weakness: they <strong>fail to learn periodic functions</strong> effectively, especially when extrapolating beyond the training distribution.</p>
<p>This isn't merely a practical annoyance—it's a theoretical gap with significant implications for fields as diverse as meteorology, finance, and signal processing. In their 2020 NeurIPS paper, Ziyin et al. tackle this problem head-on, identifying the root cause and proposing an elegant solution that challenges our default choices in activation functions .</p>
<p>At first glance, the problem seems counterintuitive. After all, the universal approximation theorem suggests that neural networks should represent any function given sufficient capacity. The catch lies in the word "represent"—while large networks might approximate periodic functions within the training range, their <strong>extrapolation behavior</strong> remains fundamentally ill-suited for periodic patterns. As we'll see, this isn't a simple optimization issue but rather a consequence of the <strong>inductive biases</strong> baked into common activation functions.</p>
<h2 id="heading-the-extrapolation-problem-why-standard-networks-fail">The Extrapolation Problem: Why Standard Networks Fail</h2>
<h3 id="heading-the-theoretical-evidence">The Theoretical Evidence</h3>
<p>Ziyin et al. begin with a rigorous examination of the extrapolation properties of common activation functions . Their findings reveal a consistent pattern:</p>
<ul>
<li><p><strong>ReLU and its variants</strong> extrapolate linearly as inputs move far from the training distribution</p>
</li>
<li><p><strong>Tanh and sigmoid networks</strong> converge to constant values during extrapolation</p>
</li>
<li><p><strong>All standard activations</strong> lack the necessary inductive bias for periodic behavior</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1759666386527/0244d4e2-7612-49d5-862d-49f8c38abc17.png" alt /></p>
<p>Figure 1: Exploration of how different activation functions extrapolate various basic function types: \(y = x\) (first column), \(y = \tanh(x)\) (second column), \(y = \sin(x)\) (third column), and \(y = x^2\) (last column). The red curves represents the median model prediction and the shaded regions show the 90% credibility interval from 21 independent runs. Note that the horizontal range is re-scaled so that the training data lies between -1 and 1.</p>
<p>The mathematics behind this is revealing. The authors prove that for a neural network with ReLU activations, the limiting behavior becomes linear: \(f(z \cdot \mathbf{u}) \approx z \cdot \mathbf{W} \cdot \mathbf{u} + \mathbf{b}\) for large \(z\) . Similarly, bounded functions like tanh and sigmoid lead to constant extrapolation: \(f(z \cdot \mathbf{u}) \approx \text{Const}\). Neither linear nor constant behavior captures the essence of periodic functions, which by definition oscillate indefinitely.</p>
<p>This theoretical analysis explains why—no matter how carefully we train our networks—they default to these simplistic extrapolation patterns. The activation function itself dictates the network's asymptotic behavior, creating a fundamental mismatch with periodic data.</p>
<h3 id="heading-practical-demonstration">Practical Demonstration</h3>
<p>Consider a simple experiment: training a standard feedforward network with ReLU activations to approximate a sine wave. Within the training range, the network appears successful, but venture beyond those bounds, and the truth becomes apparent:</p>
<blockquote>
<p>The output of our ReLU network turns into a line the further we go away from our dataset .</p>
</blockquote>
<p>This isn't an isolated case—it's the expected behavior dictated by the activation function's properties. The same pattern emerges across domains, from financial forecasting to temperature prediction .</p>
<p><em>Table: Extrapolation Behavior of Common Activation Functions</em></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Activation Function</strong></td><td><strong>Extrapolation Behavior</strong></td><td><strong>Suitable for Periodicity?</strong></td></tr>
</thead>
<tbody>
<tr>
<td>ReLU &amp; Variants</td><td>Linear</td><td>❌</td></tr>
<tr>
<td>Tanh &amp; Sigmoid</td><td>Constant</td><td>❌</td></tr>
<tr>
<td>Pure Sine</td><td>Periodic</td><td>⚠️ (Optimization issues)</td></tr>
<tr>
<td><strong>Snake</strong></td><td><strong>Quasi-periodic</strong></td><td><strong>✅</strong></td></tr>
</tbody>
</table>
</div><h2 id="heading-the-snake-activation-function-a-periodic-fix">The Snake Activation Function: A Periodic Fix</h2>
<h3 id="heading-introduction-to-snake">Introduction to Snake</h3>
<p>The core contribution of Ziyin et al. is the <strong>snake activation function</strong>, defined as:</p>
<p>\(f(x) = x + \sin^2(x)\)</p>
<p>A parameterized version is also offered: \(\mathrm{Snake}_a(x) = x + \frac{\sin^2(ax)}{a}\).</p>
<p>At first glance, snake might appear to be a simple modification, but its design is deliberate. The "x" term preserves the <strong>favorable optimization properties</strong> of ReLU-like functions—specifically, avoiding the vanishing gradient problem that plagues pure periodic activations. The \(\sin^2(x)\) term introduces the crucial <strong>periodic inductive bias</strong> that enables learning oscillatory patterns.</p>
<p>This combination creates a clever balance: the linear component ensures the network can still represent non-periodic trends (common in real-world data), while the periodic component captures cyclical patterns. The result is an activation that <strong>learns when to be periodic</strong> rather than forcing periodicity everywhere.</p>
<h3 id="heading-why-x-sinx-and-not-sinx-or-x-sinx">Why x + sin²(x) and not sin(x) or x + sin(x)?</h3>
<p>A natural question is why the authors chose the specific form \(x + \sin^2(x)\) instead of a simpler periodic function like \(\sin(x)\) or a more direct combination like \(x + \sin(x)\).</p>
<p>The pure \(\sin(x)\) activation is problematic for optimization. Its derivative, \(\cos(x)\), is zero at regular intervals (e.g., \(x = \pi/2, 3\pi/2, ...\)), which can lead to vanishing gradients and make training unstable or impossible for deep networks. Furthermore, a network built solely from \(\sin(x)\) units is a bounded function, which prevents it from modeling any underlying trend in the data: real-world time series are rarely purely periodic.</p>
<p>The alternative, \(x + \sin(x)\), seems more promising as it combines a linear trend with a periodic component. However, its derivative is \(1 + \cos(x)\), which can still be zero (specifically, when \(\cos(x) = -1\)). These points of zero gradient can again stall learning.</p>
<p>The \(\sin^2(x)\) term in the Snake function is the key innovation. Using the trigonometric identity \(\sin^2(x) = (1 - \cos(2x))/2\), we can see that its derivative is \(\sin(2x)\). Therefore, the derivative of the full Snake function is:
\[f'(x) = 1 + \sin(2x)\]</p>
<p>This derivative is always non-negative and, crucially, never zero for long stretches. Its value oscillates between 0 and 2, but the constant 1 from the linear term ensures that the gradient has a persistent, non-vanishing component. This provides the stable, ReLU-like gradient flow needed for reliable optimization while simultaneously injecting the periodic inductive bias. This careful balance is what makes Snake both trainable and powerful for periodic tasks.</p>
<p>By the law of large numbers, preactivations are roughly normally distributed, making values near 0 common. The activation \(x + \sin(x)\) is inferior to \(x + \sin^2(x)\) around 0 because its Taylor expansion,</p>
<p>\[
x + \sin(x) = 2x - \frac{x^3}{6} + \cdots
\]</p><p>\[
x + \sin^2(x) = x + x^2 - \frac{x^4}{3} + \cdots,
\]</p><p>shows that its first non-linear term is only third-order. In contrast, \(x + \sin^2(x)\) has a non-vanishing second-order term, which more effectively drives non-linear learning.</p>
<h3 id="heading-why-snake-works-where-others-fail">Why Snake Works Where Others Fail</h3>
<p>The genius of snake lies in how it addresses the optimization challenges that made pure periodic activations impractical:</p>
<ol>
<li><p><strong>Non-zero derivatives</strong>: Unlike pure sine functions which can have zero gradients across entire regions, snake's derivative \(f'(x) = 1 + \sin(2x)\) always maintains a non-zero component, ensuring continuous gradient flow during training .</p>
</li>
<li><p><strong>Progressive periodicity</strong>: The parameter \(a\) in \(\mathrm{Snake}_a(x)\) controls the frequency, allowing networks to learn the appropriate periodicity for the data rather than requiring this to be pre-specified .</p>
</li>
<li><p><strong>Compatible optimization</strong>: Snake networks optimize similarly to ReLU networks on standard benchmarks like MNIST and CIFAR-10, demonstrating they don't sacrifice general performance for periodic capability .</p>
</li>
</ol>
<p>As the authors note, snake provides the "periodic inductive bias to learn a periodic function while maintaining a favorable optimization property of the ReLU-based activations" .</p>
<h2 id="heading-theoretical-foundations-the-why-behind-the-what">Theoretical Foundations: The Why Behind the What</h2>
<h3 id="heading-the-extrapolation-theorem">The Extrapolation Theorem</h3>
<p>The paper establishes a formal foundation through what we might call the <strong>Extrapolation Theorem</strong>: the asymptotic behavior of a neural network is determined by its activation function . This isn't merely an empirical observation but a provable mathematical property.</p>
<p>For activation functions with linear asymptotes (like ReLU), the network itself behaves linearly far from the training data. For bounded functions (like tanh), the network approaches a constant. Snake's particular functional form—specifically its periodic component—ensures it can maintain oscillatory behavior during extrapolation.</p>
<h3 id="heading-universal-approximation-with-periodic-bias">Universal Approximation with Periodic Bias</h3>
<p>Snake activation doesn't compromise the fundamental approximation capabilities of neural networks. The authors demonstrate that snake networks maintain the <strong>universal approximation property</strong>, similar to conventional activation functions .</p>
<p>However, they gain an additional advantage: a <strong>Fourier-like flexibility</strong> in representing periodic functions without requiring exponentially large networks. This makes them particularly parameter-efficient for domains with inherent periodicity.</p>
<h2 id="heading-experimental-evidence-snake-in-action">Experimental Evidence: Snake in Action</h2>
<h3 id="heading-synthetic-data-validation">Synthetic Data Validation</h3>
<p>The paper first validates snake on controlled synthetic experiments, demonstrating its capability to learn simple periodic functions like sine waves where conventional activations fail . These experiments cleanly isolate the periodic learning problem from other confounding factors.</p>
<h3 id="heading-real-world-applications">Real-World Applications</h3>
<p>Beyond synthetic tests, snake demonstrates compelling performance on practical problems:</p>
<ul>
<li><p><strong>Financial data prediction</strong>: Snake networks effectively capture market seasonality and cyclical trends</p>
</li>
<li><p><strong>Temperature forecasting</strong>: Meteorological data with daily and yearly cycles represents an ideal use case</p>
</li>
<li><p><strong>Time series with trends</strong>: The additive structure of snake naturally handles series with both trend and seasonal components</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1759666400076/81ddf8ed-0163-4729-9d1e-0e169738e734.png" alt /></p>
<p>Figure 2: Experiment on the atmospheric data. (a) Regressing the mean weekly temperature evolution of Minamitorishima with different activation functions. For Snake, \(a\)is treated as a learnable parameter and the red contour shows the 90% credibility interval. (b) Comparison of tanh, ReLU, and Snake on a regression task with learnable \(a\).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1759666408165/8efd62eb-ce1a-4071-98fb-b03b493fc99b.png" alt /></p>
<p>Figure 3: Prediction of Wilshire 5000 index, an indicator of the US and global economy.</p>
<p>In one striking example, the authors show that fitting "a superposition of two periodic signals (blue) with a simple recurrent neural network" yields dramatically better predictions with snake compared to other activations .</p>
<h3 id="heading-performance-on-standard-benchmarks">Performance on Standard Benchmarks</h3>
<p>Critically, snake doesn't sacrifice general capability for periodic specialization. The authors validate that snake-based networks achieve competitive performance on standard benchmarks like MNIST and CIFAR-10 . This addresses an important practical concern: snake can serve as a general-purpose activation while excelling on periodic problems.</p>
<h2 id="heading-practical-implementation-and-considerations">Practical Implementation and Considerations</h2>
<h3 id="heading-implementing-snake">Implementing Snake</h3>
<p>For practitioners eager to experiment with snake, the implementation is straightforward:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Snake</span>(<span class="hljs-params">nn.Module</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, a=<span class="hljs-number">1.0</span></span>):</span>
        super().__init__()
        self.a = a

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">forward</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> x + torch.sin(self.a * x)**<span class="hljs-number">2</span> / self.a
</code></pre>
<p>The parameter \(a\) controls the frequency of the periodic component and can be fixed or learned during training .</p>
<h3 id="heading-architectural-patterns">Architectural Patterns</h3>
<p>The paper explores several architectural strategies:</p>
<ol>
<li><p><strong>Full conversion</strong>: Replacing all activations with snake in a network</p>
</li>
<li><p><strong>Hybrid approach</strong>: Using snake only in specific layers or components</p>
</li>
<li><p><strong>Additive decomposition</strong>: Separating trend and seasonality components explicitly</p>
</li>
</ol>
<p>For time series forecasting, the additive trend-seasonality model proves particularly effective:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdditiveTrendAndSeasonalityModel</span>(<span class="hljs-params">nn.Module</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        super().__init__()

        self.trend_model = nn.Sequential(
            nn.Linear(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>),
            nn.ReLU(),
            nn.Linear(<span class="hljs-number">5</span>, <span class="hljs-number">1</span>)
        )

        <span class="hljs-comment"># Seasonality model with snake activation</span>
        self.seasonality_model = nn.Sequential(
            nn.Linear(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>),
            Snake(a=<span class="hljs-number">1.0</span>),
            nn.Linear(<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, bias=<span class="hljs-literal">False</span>)
        )

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">forward</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> self.trend_model(x) + self.seasonality_model(x)
</code></pre>
<p>This architecture explicitly separates trend learning (handled by ReLU) from seasonality learning (handled by snake), providing both modeling clarity and performance benefits .</p>
<h3 id="heading-practical-considerations">Practical Considerations</h3>
<p>Successful application of snake requires attention to several factors:</p>
<ul>
<li><p><strong>Initialization matters</strong>: Sine-based networks can be sensitive to weight initialization</p>
</li>
<li><p><strong>Frequency parameter</strong>: The \(a\) parameter in \(\mathrm{Snake}_a(x)\) may need tuning for specific applications. This parameter directly controls the frequency of the periodic component. For data with a known dominant frequency (e.g., daily cycles in temperature), \(a\) can be initialized to a value that reflects this prior knowledge. In the absence of such knowledge, a common and effective strategy is to <em>make \(a\) a learnable parameter</em>. By treating \(a\) as a trainable weight (often initialized to 1.0), the network can automatically discover the most relevant frequency for the task during training, as demonstrated in the paper's experiments on real-world data like the Wilshire 5000 index (fig. 3).</p>
</li>
<li><p><strong>Overfitting risk</strong>: As with any flexible model, snake networks can overfit to spurious periodicities if not properly regularized</p>
</li>
</ul>
<p>For the activation \(x + \frac{\sin^2(ax)}{a}\) under a standard normal distribution, the variance is maximized at \(a_{max} \approx 0.56045\).</p>
<p>To counteract the bias from the non-linear term, authors divide the post-activation by \(\sigma_a\). This correction improves training speed and final accuracy in deep networks like ResNet-101. For standard tasks (e.g., image classification), they recommend \(0.2 \leq a \leq a_{max}\) (default \(a=0.5\)). For tasks with expected periodicity, larger values (\(a=5\) to \(50\)) are more effective.</p>
<h2 id="heading-broader-implications-and-future-directions">Broader Implications and Future Directions</h2>
<h3 id="heading-rethinking-activation-functions">Rethinking Activation Functions</h3>
<p>The snake activation challenges the conventional wisdom that activation functions should be chosen primarily for their optimization properties. Instead, it demonstrates the value of <strong>domain-aware inductive biases</strong> in activation design.</p>
<p>This suggests a future where activation functions might be selected or even learned based on the specific characteristics of the problem domain—periodic biases for seasonal data, sparse activations for feature selection, etc.</p>
<h3 id="heading-applications-beyond-forecasting">Applications Beyond Forecasting</h3>
<p>While the paper focuses on forecasting applications, the implications extend to numerous domains:</p>
<ul>
<li><p><strong>Signal processing</strong>: Periodic patterns abound in audio, communications, and biomedical signals</p>
</li>
<li><p><strong>Scientific computing</strong>: Physical simulations often involve oscillatory phenomena</p>
</li>
<li><p><strong>Anomaly detection</strong>: Deviations from expected periodic patterns can signal problems in cyclical processes</p>
</li>
</ul>
<h3 id="heading-open-questions-and-reproduction">Open Questions and Reproduction</h3>
<p>The machine learning community has begun building on this work. A reproducibility study confirmed the paper's central claims, successfully replicating experiments showing that "the proposed snake nonlinearity can learn periodic functions" . However, they noted challenges with certain experiments and initialization details, highlighting opportunities for further refinement.</p>
<p>Independent implementations have emerged across frameworks , making snake more accessible to practitioners.</p>
<h2 id="heading-conclusion-embracing-domain-aware-architectures">Conclusion: Embracing Domain-Aware Architectures</h2>
<p>The story of snake activation represents more than just a technical improvement—it signals a maturation in deep learning methodology. As the field progresses beyond one-size-fits-all architectures, we're seeing the value of <strong>domain-informed inductive biases</strong> carefully designed into network components.</p>
<p>Ziyin et al. have identified a genuine limitation in standard neural networks and provided an elegant, practical solution that doesn't compromise general performance. For practitioners working with seasonal data, periodic patterns, or any oscillatory phenomenon, snake deserves a place in your toolkit alongside ReLU and tanh.</p>
<p>Perhaps most importantly, this work reminds us that even in the age of apparently universal function approximators, <strong>thoughtful architectural choices</strong> based on mathematical understanding and domain knowledge still matter profoundly. The next breakthrough in your application might come not from a larger model, but from a better alignment between your architecture and your problem's fundamental nature.</p>
<p><em>The paper "Neural Networks Fail to Learn Periodic Functions and How to Fix It" was published at NeurIPS 2020 by Liu Ziyin and colleagues. Code implementations are available in PyTorch and TensorFlow through various community repositories .</em></p>
]]></content:encoded></item></channel></rss>