<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by NeuroLace on Medium]]></title>
        <description><![CDATA[Stories by NeuroLace on Medium]]></description>
        <link>https://medium.com/@mirandorexes?source=rss-9ebacfcfa438------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DbSr5iAofblGyvo4MS54Ag.jpeg</url>
            <title>Stories by NeuroLace on Medium</title>
            <link>https://medium.com/@mirandorexes?source=rss-9ebacfcfa438------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:26:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mirandorexes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[All You Need Is Butterflies and Crepes: A Low-Level Deep Dive Into Fourier Transform and…]]></title>
            <link>https://medium.com/@mirandorexes/all-you-need-is-butterflies-and-crepes-a-low-level-deep-dive-into-fourier-transform-and-9db3304bce9a?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/9db3304bce9a</guid>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[convolution]]></category>
            <category><![CDATA[dft-algorithm]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 13:57:46 GMT</pubDate>
            <atom:updated>2026-10-29T16:43:03.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>All You Need Is Butterflies and Crepes: A Low-Level Deep Dive Into Fourier Transform and Cooley-Tukey rabbit hole</h3><p>In almost all articles about Fourier Analysis and Fourier Transform I saw only parts of the explanation: in one article full explanation of FFT without its usage in CV frameworks, in another, a good explanation of Radix without fully understanding why we use Fourier in the first place. In this article I gather all topics needed to fully understand FFT and DFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*EsE0stfCRy9POcNjPArh5Q.png" /></figure><h3>Convolution is not what you think</h3><p>In most tutorials convolution described as a multiplication — like operation that with some magic is essential for CV and CNN — like models. This explanation also works but it does not give an understanding of what you can do with it and how it works on low level. With more and more engineers trying to learn math only using AI and not math books, makes my heart bleed. This illusion of “easy math” without truly understanding of backbone and basis of all technology — math.</p><p>The most beautiful and genius explanation of why humankind need convolution not only in CV domain you can <a href="https://betterexplained.com/articles/intuitive-convolution/#The_integral_of_the_convolution">read here</a>, I reuse this explanation in short form.</p><p>The central thing is to understand that convolution is not basic multiplication — its new form that created from two another form, two functions.</p><h4>Intuitive understanding</h4><p>Imagine yourself in a doctor’s chair: you have 5 different patients and 3 day plan for each one.Your colleague asks you to find how much medicine you need for this 5 days at all.</p><p>You feel that the next day accumulates more and more usage. Patients arrive every day (1 on Mon, 2 on Tue, 3 on Wed, 4 on Thu, 5 on Fri). On any given day, your waiting room is a mix of new arrivals, second-day patients, and final-day patients. Calculating total daily medicine gets messy fast if you try to track each person individually.</p><ol><li><strong>Today’s new arrivals</strong> get Day 1 medicine (3 doses).</li><li><strong>Yesterday’s arrivals</strong> get Day 2 medicine (2 doses).</li><li><strong>The day-before-yesterday’s arrivals</strong> get Day 3 medicine (1 dose).</li></ol><p>Notice the pattern? You are matching your treatment plan <strong>backwards in time</strong> against your patient arrival history. You can use backward list to slide it through your patients list to see accumulated sum of all dosage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*VDVgowNkfU00IumElZHIXg.png" /><figcaption>from BetterExplained</figcaption></figure><h4>Math behind convolution</h4><p>I used term “accumulate” in the doctor example not just for world. Math operation that can find volume, sum or accumulation of function is integration, and you can see it in the convolution formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*4EJHJXbF5c1F0l3FnxloSA.png" /></figure><ul><li>f(x) — is your patients list</li><li>g(-x+t) — is the list of inputs (flipped and slid to the right day).</li></ul><p>G(x+t) — is how dosage change from time, and after flipped (you need this to slide through patients list) you get g(-x+t).</p><p>Some tips about how to not misread convolution to multiplication:</p><ul><li>The result of a convolution is a new <em>function</em> that gives the total usage for any day (“What was the total usage on day ?”). We can graph the convolution over time to see the day-by-day totals.</li><li>Riemann sum vs convolution: Riemann <strong>calculate volume of single figure, while convolution calculate volume of new blended shape by 2 functions</strong></li><li>It describes how the shape of one is modified by the other.</li><li><strong>Fancy multiplication in the regular world is regular multiplication in the fancy world.</strong></li><li>Convolution is “bigger” term than multiplication, more like engine.</li><li>Regular multiplication gives you a single scaled copy of an input. Convolution creates multiple overlapping copies that follow a pattern you’ve specified.</li></ul><p>If you , like I myself, looking for more graphical representation,<a href="https://mahfuz.design/2018/12/11/convolution-and-its-physical-meaning/"> here it is</a>.</p><h4>Properties that build word on</h4><p>On this properties CV field is based, especially property 2, because of it in convolution fourier transform (DFT) is used, and not another.</p><ol><li><strong>Convolution is commutative</strong></li></ol><p>Like in the integral theory of multiplication of 2 integral, here is the same principle. Recalling example about sliding patients list in the medicine list, at first it can be not logical, but inside “slide” operation is multiplication, so if inner operation can be commulative, also outter operation also.</p><p>2. <strong>Integral of the convolution of two functions equals the product of their individual integrals</strong></p><p>Looking at the convolution from function prospective, it consist of two integral: first function and second function. Accumulative number can be find by integration of this two function. But in this way convolution is just multiplication of two integral separately, and not as one. So, only one way around is place convolution inside integration to find accumulation by two functions as union of two function. This property not working for multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*LhvVrj0JDawzdyIQyT_5ww.png" /><figcaption>Convolution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*QwaC5fZdLb3PRzTzTnUicw.png" /><figcaption>integral of multiplication of 2 function is not multiplicate of 2 integral from this function</figcaption></figure><p>Hope this explanation works for you, if you want to deepth in, here is <a href="https://www-structmed.cimr.cam.ac.uk/Course/Convolution/convolution.html">greate proof</a>.</p><h4>Convolution Theorem</h4><p>This theorem based on second property of convolution. For me “aha!” moment is this sentence from <a href="https://betterexplained.com/articles/intuitive-convolution/#The_integral_of_the_convolution">betterExplained</a>:</p><blockquote><strong><em>Fancy multiplication in the regular world is regular multiplication in the fancy world</em></strong></blockquote><p>Theorem stays that convolution in the time domain is multiplication in the Fourier domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*VqLQJOmFSoI6VXc2WyZ5ZA.png" /><figcaption>How convolution converts to multiplication in Fourier domain</figcaption></figure><p>Why this works. If we apply fourier transfor to the hospital example, fourier will create pairs of patiant x dosage, similar as “slide through”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*VvxOsM0TBLvJK8z1wzF7VQ.png" /><figcaption>Principle behind fourier transform</figcaption></figure><p>I will explain fourier transform in the next chapter.</p><p>Now you have basic knowledge of convolution and we can move to the main theme — Fourier transform.</p><h3>Basics of Fourier: The Holy Trinity</h3><p>Fourier as field consist of Fourier series, Fourier analysis and Fourier transform (FT and DFT):</p><ul><li><strong>Fourier Analysis (The Field):</strong> This discipline began with the study of physical phenomena like the vibrating string and heat diffusion. The foundational concept, proposed by Joseph Fourier, is that an “arbitrary” function can be represented by adding together a series of basic trigonometric waves.</li><li><strong>Fourier Series (For Periodic Functions):</strong> The original tool of Fourier analysis applies to periodic functions or functions defined on a bounded interval, such as a circle. It represents a function using a <em>discrete</em> sequence of numbers called Fourier coefficients. The math here relies on infinite sums evaluated over integers.</li><li><strong>Fourier Transform (For Non-Periodic Functions):</strong> The Fourier transform was developed as an analogous theory to handle non-periodic functions defined over the entire real line. It acts as a continuous version of the Fourier coefficients. Instead of discrete integer sums, the transform uses a continuous frequency variable, and evaluates the function using integrals.</li><li><strong>Discrete Fourier Transform (DFT):</strong> subfield of transform for discrete objects. Used for <strong>discrete finite data</strong> (like matrices of pixels in an image). CV field based on DFT in the most of application.</li></ul><p>I will shortly explain Fourier analysis for basic understanding of what and why used it, with a deeper explanation of Discrete Fourier Transform.</p><h4>Basics of Fourier Analysis</h4><p>I highly recommended this books if you want to fully understand power of Fourier:</p><ol><li><a href="https://kryakin.site/am2/Stein-Shakarchi-1-Fourier_Analysis.pdf"><strong>Fourier analysis by Stein, Princeton</strong></a></li><li><a href="https://see.stanford.edu/materials/lsoftaee261/book-fall-07.pdf"><strong>The Fourier Transform and its Applications, Lecture notes</strong></a> (for beginners)</li></ol><p>The main goal of Fourier Analysis is understand, explain, transform and search of frequency or group of frequencis. Imagine you have a radio, for now type of radio is not important, and you want to see what frequencis is stable, range. You give signals from radio to Fourier transform and in result it give back list of all frequencis and properties. In short, it divide complex signal to group of basic frequencis.</p><p>Fourier transform is analog of Fourier Series, but for non periodic continuous function. It converts the function into a continuous continuum of frequencies е є R.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*oHGalXa8Eb2AuNLR2tGNMQ.png" /><figcaption>Fourier analysis</figcaption></figure><p>Euler number is very important in Fourier fields, becauce it consist sin (non-symmetrical wave) and cos (symmetrical wave). It make calculation more compact, as we do not need to check signal against cos and sin separately.</p><h4>The holy grail: I, Euler number and Euler Identity</h4><p>How can we mathematically describe image? Like matrix? Or like sets of changes of axis? Maybe dont think about it at all, but not here.</p><p>I like to think of image like a coin. Coin has two sides, and imge has 2 sides: matrix representation and function representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFiX12F253FIF3VLXGHahQ.png" /></figure><p>Matrix has rows and columns, each element has its own pixel brightness. If we take brightness of each row and draw, it looks like a function with ups and downs parts. But how it write in math? Ups and downs looks like parts of sine and cos functions and move ahead is exponent function e, cool, but how can we rotate it? And here comes imaginery number i, which brings rotation term: without it function will only rise.</p><p>Euler formula connects all it together — sine, cosine, Euler number(e) and i. It eliminates tons of hard and heavy computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*2mGiSLpO1JdZb0YFzFAiww.png" /><figcaption>Euler`s formula</figcaption></figure><p>Euler identity works for cases with half circle (pi) rotation — swaps O (any angle) with pi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*vWRcKbDnphbSJg9LCj9RWQ.png" /><figcaption>Euler identity</figcaption></figure><p>Fourier transform in classic view uses only Euler formula, but optimized algorithms, like Coolye — Tukey also uses Euler identity for speed up. More about this in the next chapters.</p><p><em>(I will use screenshots from notebook because medium hate LATEX)</em></p><h4>Checking frequency with Fourier Transform</h4><p>Besides its name Fourier Transfor can not only transform, but also check and search for frequency.</p><p>The main task of Fourier Transform is to translate one complex thing into set of components. For classical FT basic components is frequency. You can check if frequency present or not using integral distilation — negative area cancels positive and negative area accelerate negative.<br> Integral can be use as locator of components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*Vhp-xs46U4H6U5aPgUxe3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*XeEsMTBCRSZWWrXLnNz2rw.png" /></figure><p>Discrete Fourier Transform works on the same principles, but with another set of tools. Recall that Riemann sum is foundation for integral — its sum of very small squeres under curve, their width goes to 0, sum of this little squeres is approximation of area under curve — integral. DFT follow this trick — we cant get integral of image or another discrete object, but we can find the sum of its components.</p><h4>How to search frequency</h4><p>Fourier transform can check if frequence is presented in signal or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*N6wHNrkQKCmAAUlI1FYccQ.png" /><figcaption>Search for channel (frequency) 88</figcaption></figure><p>This integral acts exactly like locking a radio tuner onto channel 88. It filters out every other frequency in the signal and outputs a single complex number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*oglxggA37ubBVutxpDVzxw.png" /><figcaption>Parts of result after Fourier Transform</figcaption></figure><h3>Discrete Fourier Transform</h3><p>Now lets dive deep in rabbit hole of DFT: how it works on paper and in RAM/CPU. When I first study DFT I dont think of it like of something that can be intrested to me. While writing this article i had dozens of “aha!” momets, I am completely facsinating by it and now i can say that i understand DFT. I hope you will understand it too, and if you fear DFT before reading, after you will have your own idea how to implement it in the best way.</p><p>As I said before, DFT is Fourier transform for discrete objects. Here is restricted area for integral, and summation is rule here. Most of attention I give to DFT of images, 2D especially, but the same rules also can be apply to signals of phone radio, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*i4zkWyvQGumW-bubNMqC7Q.png" /></figure><p>It can be scare at first, but not for long. Lets see what each parts of formula means:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*hWnFHj8sasISEyJzaXWiOQ.png" /></figure><p>In short: double sum over multiplication of pixel intensity and exponential basis function, which is euler formula. Notice that here euler formula has another form: in FT it used frequency, but here frequency (something that changes) role play spatial frequencies (cycles per dimension) u and v.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*YDE-05H-NC-mk45zKDKzCw.png" /><figcaption>Euler formula form in the DFT</figcaption></figure><h3>How image became frequencies</h3><p>Image has pixel position, pixel intensity, width and height.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*9GJPDECCcawkD7WZ" /><figcaption>Pixel intensity</figcaption></figure><p>If we draw pixel intensity as dots on paper and connect with line, it will be some sort of function, or precisely histogram. Image contains not one, but multiple pixels intensity sets that can be draw as functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*VVZjVYIqGXZoeAUj" /><figcaption>Pixel intensity histogram</figcaption></figure><p>In the picture (b) most of pixels are 0, black color, and you can see on histogram that most values belong around zero. Very cool, now lets take derivative from pixel intensity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*IXhFG_PUoD-nbpfo" /><figcaption>from:Stanford</figcaption></figure><p>Lets go from left to right: you go on the white pixels, under you feet you see 255, its pixel intensity of white color, you go and go and then suddenly you see that you stand on pixels with number zero, this drastically downfall from 255 to 0 you can see on the middle picture, pixel intensity function goes down, and first derivitive also. Now you step on white pixels again and see similar picture — now function goes up.</p><p>The resulting coefficient F(u, v) is a complex number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*PER6sdzKqMMiUiwz_U1_cA.png" /><figcaption>Components of complex number</figcaption></figure><h3>How to read u and v</h3><p>Using euler formula we can expand to DFT to more readible way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*cjZX9UG5YPjtUzl9waFE3Q.png" /><figcaption>Expanding using euler formula</figcaption></figure><p>In 1D, a sine/cosine wave is a vector of numbers oscillating up and down. In 2D, this waves is an N * M <strong>matrix of numbers</strong> where pixel values oscillate smoothly across rows and columns.</p><p>Understanding what each components contribute and mean is very important for understanding.</p><ul><li><strong>Vertical Frequency (u):</strong> Controls how many full wave cycles occur from the top row to the bottom row.</li><li><strong>Horizontal Frequency (v):</strong> Controls how many full wave cycles occur from the left column to the right column.</li><li><strong>Orientation/Angle:</strong> The ratio of u to v determines the diagonal angle of the stripes. For instance, if u=0 and v=5, the wave only oscillates horizontally, creating vertical stripes. If u=5 and v=5, the wave oscillates diagonally.</li></ul><h3>Why sin have i, but cos not?</h3><p>It one of the tricky questions, coze life will be easier if we do not need i in CV computation, right? Not exactly.</p><p>Sine and cos waves bring to the table repetable, but what if image is gray? I can handle this. I is necessary because arbitrary spatial signals (including 2D grayscale images) are generally asymmetric across rows or columns. The i attaches to the sine basis function, creating a 90 phase shift relative to cosine. This allows DFT to capture anti-symmetric (odd) spatial variations alongside symmetric (even) ones.</p><ul><li>90* rotation to the real number. Putting i in the exponent changes linear growth into a <strong>perpendicular (90-degree) rotation</strong>.</li><li>Connects exponential properties and sin/cosine propetties together — new “united” axis.</li><li>Circular changes for -1. Signal on the opposite of trigonometric circle is identical but with oppisite signs. Its very important for computational speed up</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*mxcxXYZevSYhB0bA.png" /><figcaption>need for i (from: BetterExplained)</figcaption></figure><p>Using euler formula we have cos part as Real number, but why sin part is imaginery? Its due to Taylor series properties of Euler identity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*0y5I-QeVkhh6qJJciBdheQ.png" /></figure><h4>Finding frequence correlation with cosine matrix only</h4><p>Okay, but what we lost if used only cosine matrix, without i computation will decrease. It can sounds as plan B, but with i computation speed up is possible. Lets see what happened if dont use Euler formula.</p><p>Given an image matrix f of size N * M:</p><ol><li><strong>Generate the 2D Wave Matrix:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*7leqvjL1wltfHjoQGn-jhg.png" /></figure><p><strong>2. Element-Wise Multiplication:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*fCYpWAWFZXlVO3khu2aG4w.png" /></figure><p><strong>3. Sum All Matrix Entries:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Dr6MbhYa5Jp-dWZOL2K5ew.png" /></figure><ul><li><strong>When the pattern IS present:</strong> The bright pixels in your image (f(x,y) &gt; 0) align with the positive stripes in W{(u,v)}, giving positive products. The dark pixels in your image (f(x,y)&lt;0) align with the negative stripes, so the negative numbers in W{(u,v)} multiply to give positive results. When you sum the matrix, all terms accumulate into a <strong>large total sum</strong>.</li><li><strong>When the pattern IS NOT present:</strong> The bright and dark pixels in your image hit the positive and negative stripes of W{(u,v)} randomly. Positive products and negative products cancel each other out completely during the matrix sum, yielding a <strong>result near zero</strong>.</li></ul><p>This method of correlation work with cosine matrix only, so can detect only symmetrical pattern, but image consists of symmetrical and non-symmetrical patterns and non — symmetrical parts just vanished.</p><h3>Solving symmetrical correlation problem with Euler formula</h3><p>Euler formula combine symmetrical cosine wave and non-symmetrical sine wave. So, to check not only symmetrical pattern, but also assymetrical we need matrix with cosine and sine wave.<br> By euler identity we can swap sign:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*uSfXgLs8FLZhEkEJlp9QbA.png" /></figure><p>After swaps cosine matrix with euler formula we got the same formula as in the beginning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*0cd0BshbACDphw5G6wZPlw.png" /></figure><ul><li>A <strong>2D Cosine Matrix</strong> to get the Real component R(u, v).</li><li>A <strong>2D Sine Matrix</strong> to get the Imaginary component I(u, v).</li></ul><p>In the result now we can see symmetrical and non — symmetrical waves, but also all numbers is complex.</p><p>By running this element-wise matrix multiplication and sum for every valid frequency pair (u, v), converts the entire spatial pixel matrix into a 2D <strong>frequency spectrum matrix</strong> — it represents how an image or spatial pattern behaves across different spatial frequency coordinates (e.g., horizontal and vertical frequency variations. Each component of matrix is complex number and contains phase and magnitude components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9rygY4ymRa_B0IiTco_Fg.png" /><figcaption>Spectrum matrix in the middle</figcaption></figure><h3>How imaginary numbers computes on machines</h3><p>Lets quick discuss how it works in theory and then in RAM/CPU.</p><p>Modern systems cant process imaginary numbers in the same way as in classical calculus.<br> Imaginary number is z =a+bi, where a and b is Real number.<br> In computer its structured as set z={A, B}:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*j3vL9K1PmO5jaKLjKdYvvw.png" /></figure><p>The best way is see imaginery slot as router: it gives -1, i and 1 according to the power of i.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*fijdFEltAHxYcRtt2xyavg.png" /></figure><p>For computes DFT modern frameworks used Euler identity to separate real and imaginary parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*mDx70nXg7e4AJ5QKnPnWWw.png" /></figure><ul><li><strong>The Cosine Matrix :</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*KgiOG9i6gXb_kWZttQl2qA.png" /></figure><ul><li><strong>The Sine Matrix:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*fppQW-Z8SzLVr286rYgTWw.png" /></figure><h3>Imaginary numbers in RAM</h3><p>A classical computer represents a complex number z = a + bi by allocating two consecutive real floating-point values side-by-side in memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*ywGJzh4vVcclK7dmN-59gg.png" /></figure><ul><li>Offset +0 stores the real part a.</li><li>Offset +8 stores the imaginary part b.</li></ul><h3>In the CPU:</h3><p>i² = -1 becomes a Subtraction Instruction (router):<br> When you multiply two complex numbers (a + bi) and (c + di), the algebraic expansion is:</p><p>(a + bi)(c + di) = ac + bci + adi + bd * i² = (ac — bd) + (ad + bc)i</p><p>When compiling this for a CPU or GPU, compiler translates i into six real hardware operations:</p><ol><li>MUL: Compute a * c</li><li>MUL: Compute b * d</li><li>SUB: Compute ac - bd <em>(This subtraction is where i^2 = -1 physically goes in)</em></li><li>MUL: Compute a * d</li><li>MUL: Compute b * c</li><li>ADD: Compute ad + bc</li></ol><p>The CPU/GPU does not know i exists(good for it) — it executes a standard real SUB instruction that the compiler emitted to enforce the rule i^2 = -1.</p><h4>Euler exponent in modern systems as triginometry</h4><p>When your code evaluates euler formula, CPU never processes a complex exponent. Instead, the hardware or low-level C library executes trigonometric algorithms (such as CORDIC or Taylor polynomial approximations) to compute two real numbers:</p><ol><li>Compute real floating-point value R = cos(o).</li><li>Compute real floating-point value I = sin(o).</li><li>Store the two-element array [R, I] in memory. i is an abstract software convention. The hardware processes real numbers, while the software maintains the imaginary behavior through how it orders real additions, multiplications, and subtractions.</li></ol><h3>How DFT computes in real world</h3><p>Recall that DFT is (I will use A notation to explain 1D and 2D DFT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*w5FFv_stttvdT1S3RjBNBA.png" /><figcaption>2D DFT</figcaption></figure><p>We can assume that in practice to compute it we need compute sine and cosine 2D matrix, the multiply with image matrix, repeat this with every row and column to find sum.<br> This will take compexity of N * N = N² operations for 1D, and N* M * N * M = O(N² M²) operations for 2D.</p><p>Thanks to optimization techniwues as Cooley-Tukey Radix-2 (divide and conquer) complexity go down to O(N \log N)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*ApQe1bHYdhutgMk5VlxNCw.png" /><figcaption>Complexity of different algorithms</figcaption></figure><h3>Compute Cooley-Tukey on 1D matrix</h3><p>When I first read about this algorithm I dont understand a lot of things, so I will try to explain simple for 1D case and then with details for 2D.</p><p>Cooley-Tukey Radix-2 divide 1D array into 2 parts: odd and even indexes:<br> When length N = 2^n, the full summation is split recursively into even-indexed terms F(2r) and odd-indexed terms F(2r+1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*t_pHqkifpw2gx_s1oa2GnA.png" /><figcaption>Odd and Even indexes parts</figcaption></figure><p>Let E be even indexes and O odd indexes, two halves are computed using a single <strong>butterfly operation</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*4UTFXgndIuMmjWsnX0DRdw.png" /></figure><p>I like to imagine this as buttefly wings: left wing is even and right wing is odd. With it instead of two sum operation we have two reusable parts.</p><p>This reuse of intermediate terms reduces computation from O(N²) to O(N * log2 N).</p><h3>Compute FFTin 2D</h3><p>Now, to details. In almost all frameworks DFT named FFT (Fast Fourier Transform). It still use discrete version of Fourier transform. The most common steps in frameworks like Numpy is:</p><ol><li>Split the Input into Evens and Odds</li><li>Simplify the Exponentials (i)</li><li>Twiddle factor to cut operations in half due to symmetry nature</li><li>Hermition symmetry for mirroring<br> This is all parts of Cooley-Tukey algorithm that is the base of FFT in all modern frameworks.<br> This reduces 2D image complexity from O(N² M²) to O(NM \log(NM)).</li></ol><h3>Cooley-Tukey and symmetries</h3><p>Cooley — Tukey uses 3 types of symmetry: twiddle, separability (Euler) and Hermitian. Shortly about each.</p><h4>Twiddle factor and rotation symmetry</h4><p><em>Compute and reuse</em></p><p>Twiddle factor is matrix of euler formula value for each pixels. Dimensionality is the same as image, in practice computes two 1D twiddle matrix for row and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*2mqgL4LUWb9SKF3k8CNDpw.png" /></figure><p>For 1D FFT only one half computation is needed, and to compute the other half using the same twiddle factor.</p><pre>// Complex multiply twiddle factor with odd element <br>std::complex&lt;float&gt; temp = twiddle_table[k] * O; <br>// Upper bin (Addition) <br>out[upper_idx] = E + temp;<br>// Lower bin (Subtraction applies the -1 rotational symmetry automatically) <br>out[lower_idx] = E - temp;</pre><p>Because both outputs (out[upper_idx] and out[lower_idx]) share the same temp value, <strong>1 complex multiplication computes 2 spectrum output points</strong>.</p><p><strong>Rotation symmetry</strong> is based on i in power property.<br> Sine and cosine waves are circular. If you move <strong>halfway around a wave cycle</strong> ( 180), the wave value flips its algebraic sign: i² =-1, i³ =-i, i⁴ =1.<br> Its important to not think of this symmetry as about f(x) = -f(x).</p><p>But why we cant just use matrix? In linear algebra its possible to calculate is one operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*Te7TagFbmtDulXS58oz0JQ.png" /></figure><p>Its logical to assime that using matrix multiplication engines like Numpy can boots up speed, but If an engine worked this way, it would be performing full 2D matrix multiplication without symmetries properties. Doing this requires O(N² M²) operations, which is extremely slow for large images.</p><h4>Separabillity symmetry</h4><p><em>Break 2D into 1D — divide </em><br> Why do thousands and thousands operation if it posiible to compute rows and columns separatly. In FT its much harder becose of nature of continuous functions, but with discrete its much easier.</p><p>With it 2D twiddle factor matrix breaks into two 1D matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*RUJmuC2a54KUXVCg_SZEwg.png" /></figure><h4>Hermitian or Conjugate Symmetry</h4><p><em>Positive half = negative part</em><br>One of the most facsinationg and difficult symetry here.<br>Conjugation operation was founded by Charles Hermite, while he explored propertries of complex numbers, where conjugate thanspose matrix equils to complex matrix.</p><p>Conjugation as operation can be undersood as symmetry propertie at first, like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*Bf4t_VC92B0KGMUgruDK9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*LMqyawZOPof3GtVLy1_iYw.png" /><figcaption>Conjugation</figcaption></figure><p>In FFT this symmetrical properties adopts in magnitude and phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*tvEUzUhwHcn8qUk998YYTQ.png" /></figure><p>Its very important to not mistake twiddle symmetry with hermitian: twiddle gives as factor with what we can compute even and odds indexes without multiplication and with hermitian we can compute only one half, and the other is identical with opposite sign.<br> This gives <strong>50% Compute Reduction:</strong> Frequency bins for n &gt; N/2 are skipped entirely during execution because their magnitudes are fully redundant.</p><h3>Example of computation on 4x4 matrix</h3><p>This example based on computation of FFT from math prospective in most modern frameworks, more technical expanation in the next chapter.<br> Okay this part is a little bit akward at first and I spend a couple of hours to understand how explain it right.<br> Imagine you want to make crepes and you have a list of product that you need to buy:<br> (step 1) What you need to buy</p><p>1. egg<br> 2. flour<br> 3. milk<br> 4. sugar<br> In most countries eggs is in cold places, as near milk refregeretor, and flour and sugar is in places with wheat etc. So most optimized way is go for egg and milk and then for flour and sugar or vice verse, but not go staight for the grocery list.<br> Now, you have all needed components and you can start to cook.<br> ( step 2):</p><ul><li>combine egg +milk</li><li>combine sugar+flour<br> You can combine egg+flour, but result will be bad.<br> (step 3) combine all together<br> (step 4) fry on pan</li></ul><p>As you can see I separate each step for optimization, beside some steps are not logical at first, lets try to make crepe sfrom imaginary numbers.<br> In Cooley-Tukey method even and odd indexes used separatly, lets asume that the result of Cooley-Tukey method is our shopping cart and shopping list is odds and evens groups. Assume original matrix looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*bg0LWZzwvIVA6c4SQPZKHQ.png" /><figcaption>Original matrix</figcaption></figure><p>Step 1: Separate indexes by evens and odds. The fastest way is bit reversing:<br> [p0, p1, p2, p3] is first row in matrix N, similarly to egg and milk, we need to separate like this:<br> Odds = p1, p3<br> Evens = p0, p2<br> In RAM this operation computes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*VLKyxbQoiFF2t-6wFkNjNw.png" /><figcaption>Bit reversed operation</figcaption></figure><p><strong>Resulting memory layout:</strong> [p_0, p_2, p_1, p_3]. We can take first half as evens and the second as odds.<br> The same operation is repeated for all rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*f5uvOtOR8zmGw9YGHbBviA.png" /><figcaption>Bit reversed matrix</figcaption></figure><p>Step 2: Compute small butterflies from Cooley — Tukey.</p><p>One wing is even, other is odd. Now we need to find odd and even branches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*5Y6JXAdKY2iAit-LXbTGkg.png" /></figure><p>Step 3: 4 Small butterflies for rows<br>We have odd and even branches and now we can calculate twiddle factor, we need only N/2 and swap sighn for other half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*rZJVtbeDGJnFVTQtqUJ99g.png" /><figcaption>Twiddle symmetry in action</figcaption></figure><p>Cool! Lets calculate A0, A1, A2, A3 for the first row:v</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*PNxVqsyokFuoDP7TyWfGlw.png" /></figure><p>Now we finally can see first row — connects branches and twiddle factor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*7mEoQ9WDiFSc_OkgJUf65w.png" /></figure><p>See where magic lies: we need only 2 pairs to calculate 4!<br> Notice that X0 and X2 is real numbers and X1, X3 is complex and the difference between them is just sign! This is the main property of Hermitian symmetry:<br> X3 = Hermitian{X_1} (complex conjugate). Basically we even dont need to compute X3 to find it.</p><p>Repeating with the rest rows and we get complex matrix G (butter for crepes):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*9zGrE2FUdJ2dXQ04rqIeuQ.png" /></figure><p>Step 4: Repeat all over again for columns<br> For now we have multiplication between original matrix and 1D twiddle matrix, with sum over all row components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*BGU-TMVduFTxdLD7k_tQvw.png" /></figure><p>Using exponential rule we separate row and column 1D twiddle matrces for speed up and the next step repeating all steps before it, except transposing.</p><p>Phase 1: Transpose G and repeat bit-reversing<br>Using the same bit reversing method we get this matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*XYYqn2iKLYbe5MkrXnramA.png" /></figure><p>Phase 2: Compute Twiddle matrix for column, that now are rows. Create similar 1D twiddle factor matrix for transposing components.<br> Phase 3: Small butterflies<br> Similar to the small butterflies in row DFT.<br> For first row even and odd branches are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*0dY3zb5ySoEkQiewFKnq6A.png" /></figure><p>Phase 4: Multiplicate small butterflies and twiddle factor matrix<br> Calculate Tn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*VGDH3ObrMCc_EQP1t6wclw.png" /></figure><p>T1 has non-symmetrical wave.<br>Repeating with the rest of rows we get this 4x4 matrix, after transposing again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*fa99uksgLd8sKgv3QaFsJg.png" /><figcaption>Final DFT matrix</figcaption></figure><p>Hope this explanation helps to understand underlying mechanics of DFT. Lets move to the frameworks and low level details.</p><h3>How DFT computing in modern frameworks</h3><p>In frameworks like Numpy, Scipy and similar computing DFT follows the same pattern with some additional steps. In hardware, C++ and CUDA runtimes cannot store abstract complex symbols like i in processor registers. Complex arrays are stored as contiguous pairs of floating-point numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*KokeyTVKQ5E1oqtbIj0zXA.png" /></figure><p>Because of this and from the fact that memory allocating in the pipeline much more expansive, that before it, the first step is allocating memory for all matrices that we need in process.</p><h4>Step 0: Initial Buffer Allocation (Done Once Upfront!)</h4><p>Before running any Fourier calculations, the engine inspects the input shape (N, M) and allocates memory buffers once for matrix and two 1D matrices for twiddle factor.</p><p>FFT (DFT named FFT in frameworks) has 2 types — standart and real — valued. The only difference between them, except types of data, is usage of Hermitian symmetry. RFFT uses it in full potential, so final matrix is smaller then in FFT. More about RFFT in the next chapter.</p><p>Allocating for matrix:</p><ol><li><strong>For Standard Complex FFT (</strong><strong>fft2):</strong></li></ol><ul><li>Allocates an N * M complex output matrix (64-bit or 128-bit complex floats) in contiguous memory.</li></ul><p><strong>2. For Real-Valued FFT (</strong><strong>rfft2):</strong></p><ul><li>Leverages Hermitian conjugate symmetry to allocate a reduced output buffer of shape N * M/2 + 1, cutting memory overhead by 50%.</li></ul><p><strong>3. Scratchpad Memory:</strong></p><ul><li>Allocates a tiny 1D temporary work array ((N, M)) or reuses L1 cache lines to store intermediate 1D Cooley-Tukey butterfly computations.</li></ul><p><strong>4. Allocating for twiddle factor matrices:</strong></p><ul><li><strong>Row 1D twiddle matrix(</strong><strong>twiddle_row):</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*FKkFrcWApqbgYhjsYa3Xrw.png" /></figure><ul><li><strong>Column 1D twiddle matrix(</strong><strong>twiddle_col):</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ssvxyEMebwMc3qzC4wZbfQ.png" /></figure><h3>Step 1: Row 1D DFT</h3><p>All next steps repeating the same steps as in the 4x4 example, so I focus on the RAM and CPU.</p><p>In C-contiguous memory layout (row), elements of the same row sit right next to each other in physical RAM bytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*L7DOg792PuPmSQl4pVvo1A.png" /></figure><p><strong>What the CPU/GPU does:</strong> The engine loops through each row and executes a standard 1D Cooley-Tukey FFT of size M:</p><ol><li>Bit reversing to place even and odds pairs.</li><li>Calculate small butterflies — find E and O branches.</li><li>Calculate Tn the same as before, first T0 is:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*u5yUL1moG8iJKi6b0ddtlg.png" /></figure><p>4. Calculate all elements of the rows (even and odds elements):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Vy-J9C0t2x-oGFJmfiJ0Kg.png" /></figure><ul><li><strong>Hardware Speedup:</strong> Because adjacent row elements sit sequentially in physical RAM, CPU L1/L2 cache prefetchers load full rows into cache lines instantly, allowing vector instructions (SIMD / AVX-512 / GPU warp threads) to compute row butterflies at maximum speed.</li></ul><p>Result after Step 1: Intermediate matrix G of shape (N, M).</p><h3>Step 2: Transpose matrix G</h3><p>Recall that the easier way to do outter summation is transpose matrix G and repeat all steps for transposed columns, that now are rows.</p><p>Why can’t the engine just run 1D FFTs straight down the columns?</p><p>If you access column elements G{0,0}, G{1,0}, G{2,0}, directly, each step skips M elements forward in physical RAM bytes. This causes severe <strong>cache misses</strong> (cache thrashing), forcing the CPU to constantly wait for RAM reads. Its like doing for loop on massive matrix, very slow and boring.</p><p>Transposing in RAM follows this steps:</p><ul><li>The framework performs a <strong>Blocked Matrix Transposition</strong> (G * G^T) directly in memory.</li><li>It breaks the matrix into small 8 * 8 or 16 * 16 tile blocks that fit entirely inside L1 cache registers before swapping rows and columns.</li><li>Shape after Step 2: (M, N). Column data is now laid out horizontally in contiguous memory.</li></ul><h3>Step 3: Column-Wise 1D DFT Pass (Executed Horizontally on Transposed Matrix G)</h3><p>Now that former vertical columns are laid out horizontally in physical RAM, the engine runs row 1D DFT across all new rows.</p><h3>Step 4: Final Re-Transposition</h3><p>All rows and columns have their time of glory in Fourier field, its time to transpose final matrix back.</p><ul><li>The engine performs a final matrix transposition back to its original orientation: (M, N) to (N, M).</li></ul><h3>Step-by-Step Memory Execution Pipeline</h3><p>Graphically all steps is:</p><pre>[Phase 0: Pre-allocation]<br> ├── Allocate output buffer ONCE (Shape: N x M)<br> ├── Precompute twiddle_row array (Size: M / 2 complex numbers)<br> └── Precompute twiddle_col array (Size: N / 2 complex numbers)</pre><pre>[Phase 1: Row Pass]<br> └── Loop row = 0 to N-1:<br>      └── Compute 1D FFT on Row[row] using twiddle_row (reused N times!)</pre><pre>[Phase 2: Cache-Friendly Transpose]<br> └── Swap matrix layout in RAM (Shape becomes: M x N)</pre><pre>[Phase 3: Column Pass]<br> └── Loop col_row = 0 to M-1:<br>      └── Compute 1D FFT on Transposed_Row[col_row] using twiddle_col (reused M times!)</pre><pre>[Phase 4: Final Transpose]<br> └── Swap matrix layout back to original orientation (Shape: N x M)</pre><h3>DFT vs RFFT</h3><p>In the previous chapter you saw how truly beautiful can be used 3 types of symmetry. DFT is really powerful tool, but it keeps matrix size and all operations also done on full size matrix. RFFT is analog to DFT, but works only on real numbers and use hermitian symmetry to full potential. Lets see how on 4x4 matrix for simplicity.</p><p><strong>Step 0: Allocate memory for all needed matrices</strong></p><ol><li><strong>Output Memory Buffer:</strong></li></ol><p>For example 4x4 matrix in RFFT is:</p><ul><li>Shape: 4 * 3 complex float numbers (4 rows, (4/2) + 1 = 3 columns).</li><li>Total size: 12 complex numbers = 24 real floating-point numbers.</li></ul><p><strong>2. 1D Twiddle factor matrices:</strong></p><ul><li><strong>Row twiddle matrix(</strong><strong>twiddle_row):</strong> Size of 2 complex numbers (W4,0 and W4, 1) for horizontal length-4 transforms.</li><li><strong>Column twiddle matrix (</strong><strong>twiddle_col):</strong> Size 2 complex numbers (W4,0 and W4, 1) for vertical length-4 transforms.</li></ul><h3>Step 1: 1D row RFFT</h3><p>Perform the same classic row DFT as before on every row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*OOdvsK1gZWC7mOKhQyjxXA.png" /></figure><p><strong>Hermitian Dropping:</strong> Because the input pixels are real, the 1D output [X0, X1, X2, X3] has conjugate symmetry (X3 = conjugation{X_1}), so we need to calculate only 3 real values, it drops 4th column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*FNDFfTNuSSKWxhxI8kivEQ.png" /></figure><p>Resulting matrix G has shape 4x3, and not 4x4 like in previous FFT example.</p><h3>Step 2: Matrix G transposition (4x3 to 3x4)</h3><p>Transposes matrix G in memory:</p><ul><li>Shape transforms from <strong>(4, 3)</strong> to <strong>(3, 4)</strong>.</li><li>Matrix G now consists of <strong>3 contiguous rows</strong>, where each row is a column of length 4 from the previous step.</li></ul><h3>Step 3: Repeat 1D row RFFT on columns</h3><p><strong>Crucial Distinction:</strong> The values in transposed G are <strong>already complex numbers</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*RFtFUPiqQT7e-gW57mSZ8Q.png" /></figure><p>Because the of this, Hermitian symmetry no longer applies along this axis:</p><ol><li><strong>Execution:</strong> The engine runs a <strong>standard 1D Complex FFT (</strong><strong>fft)</strong> of length 4 using twiddle_col.</li><li><strong>Output Size:</strong> It keeps all 4 vertical frequency outputs [A{0,m}, A{1,m}, A{2,m}, A{3,m}].</li></ol><p>After processing all 3 transposed rows, matrix shape is <strong>(3, 4)</strong> complex numbers.</p><h3>Step 4: Transposing matrix G back</h3><p>Smaller matrix = optimized execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*KVCAc44nisWGCKfxgRr1pA.png" /></figure><p>Fow this I love math — a little bit this and a little bit that and I have optimized way for CNN layers without digging in low level C.</p><h3>FFT Frameworks list</h3><p>Small list of DFT frameworks for diffirent case scenarious.</p><h4>Backend Engines (the goats)</h4><ul><li><strong>NumPy (</strong><strong>np.fft):</strong> Uses <strong>PocketFFT</strong> (a C99/C++ library derived from FFTPACK). It supports mixed-radix decomposition, arbitrary dimensions, SIMD vectorization, and thread safety.</li><li><strong>SciPy (</strong><strong>scipy.fft):</strong> Built on PocketFFT and FFTW (Fastest Fourier Transform in the West) bindings, featuring auto-tuning planner algorithms that analyze hardware cache sizes.</li><li><strong>PyTorch (</strong><strong>torch.fft) / TensorFlow:</strong> Delegates CPU execution to PocketFFT or Intel MKL, and GPU execution to NVIDIA <strong>cuFFT</strong> (which utilizes shared memory architectures and warp-level SIMD shuffle instructions).</li></ul><h4>Multidimensional DFTs (fft2, fftn)</h4><p>Because 2D DFT basis functions are separable frameworks compute 2D/ND FFTs as sequence passes:</p><ol><li>Compute 1D FFT on every row x across columns y.</li><li>Transpose matrix or adjust memory strides to align column memory contiguous with CPU L1/L2 cache lines.</li><li>Compute 1D FFT down every column y.</li></ol><h4>Real-Valued Optimizations (rfft / irfft)</h4><p>When input data is purely real (x[k]∈R), the frequency domain output exhibits Hermitian symmetry: X[n]=X∗[N−n]. Frameworks exploit this property by:</p><ul><li>Packing an N-point real sequence into an 2N​-point complex array.</li><li>Computing a single 2N​-point complex FFT.</li><li>Unpacking the result using a final butterfly pass, halving both execution time and memory footprint (N/2+1 complex outputs returned).</li></ul><h3>Best books of Fourier Analysis</h3><p>Fourier Analysis is really hard topic and I very thankful for this books in getting me on track:</p><ul><li><a href="https://see.stanford.edu/materials/lsoftaee261/book-fall-07.pdf"><strong>The Fourier Transform and its Applications, Stanford lecture notes</strong></a></li><li><a href="https://kryakin.site/am2/Stein-Shakarchi-1-Fourier_Analysis.pdf"><strong>Fourier Analysis (Stein, Shakarchi)</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9db3304bce9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classification 101: Low Quality, Ensemble, and Unbalanced Classes]]></title>
            <link>https://medium.com/@mirandorexes/classification-101-low-quality-ensemble-and-unbalanced-classes-8a3420b88cf7?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a3420b88cf7</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 16:18:32 GMT</pubDate>
            <atom:updated>2026-09-29T16:18:32.500Z</atom:updated>
            <content:encoded><![CDATA[<p>Classification often called a simple ML problem, that can be solved with 10 minutes training. I want to tell and show that classification in real world scenarious can be difficult.</p><p><em>As an example, I will use my project from a bowling competition, which was in the top 45%.</em></p><h3>Dividing plane (hyperplane)</h3><p>As the name suggests, the main goal of a classification problem is to assign specific data to a specific class, but how exactly can this be done, and why don’t even the most sophisticated neural networks have 99% accuracy?</p><p>Imagine you have to sort 10 books of different genres into 5 categories. Most likely, you will read a short description of each book, visually evaluate the cover, maybe read about the author. The description, cover and author are the features by which the sorting will be done.</p><p>The classification problem in machine learning has a similar, but more mathematical implementation. The main goal of which is to construct a separating plane with the minimum value of the error function. It still sounds pretty simple, right? But let’s look at what the training data actually is.</p><p>To train a neural network, you need to have a dataset consisting of n-number of features. Together, the features form a feature space, the number of dimensions of which is the main challenge, the number of dimensions = the number of features. Let’s consider an example: we have a dataset with 2 features: gender 1 and gender 2, the task is to classify data into classes. This dataset is two-dimensional, since it has 2 features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*HQlgSK7xM9ddzDIrtUy-MA.png" /><figcaption>Hyperplane for binary classification</figcaption></figure><p>The given problem is a binary classification problem, more about it later. The separating function (red dotted line), according to which the algorithm will classify, is linear, that is, to solve this problem you can use the simplest algorithm — logistic regression. At first glance, everything is simple, but datasets for real problems can have 50, 100, 500 dimensions.</p><h3>Big size — big problems</h3><p>The two main problems in data that cause an algorithm or neural network to have low accuracy are the number of dimensions and the shape.</p><p>Let’s start with the first problem — multidimensionality. Imagine you are lost in a cave, what are the chances of getting out of the cave with 2 or 200 moves? Multidimensionality leads to longer training time, overtraining of the model, and the curse of multidimensionality (Hughes phenomenon):</p><ul><li>The higher the dimensionality of matrices, the <strong>more resources are required</strong> to operate with them.</li><li>The model<strong> cannot be generalized</strong> (generalization)</li><li>In multidimensional planes, it is <strong>incredibly difficult to find the distance from one data point to another</strong>, in the case of classification this is the Hughes phenomenon: the more dimensions, the easier it is to find the dividing surface during training, but at the same time, the harder it is for the model to generalize.</li></ul><p>For optimization and visualization, Dimensionality reduction methods are used, such as PCA, MDS, etc. The basic principle of their work is to transfer each instance, each data point, to a space of lower dimension, usually 2–3 dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*EDvBlIgLIWjOan_tUvn02A.png" /><figcaption>Dimensionality reduction using UMAP</figcaption></figure><p>Dimensionality reduction methods are a very important part of feature engineering, and a separate long read will be devoted to them.</p><p>The second problem is the form of the data, depending on it the engineer chooses the Dimensionality Reduction method: linear or nonlinear. To separate data in multidimensional spaces, you need to construct a dividing plane. Can this plane be nonlinear, for example, to separate the data in the figure on the left? Theoretically — yes, but this is already beyond the scope of the concept of a dividing plane and is not used in machine learning.</p><p>In the example, the 2-dimensional data on the left is translated into a 3-dimensional space in which a dividing plane can be constructed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*P6pLIAZdoTQP-bpYTkDpiw.png" /><figcaption>Constructing a dividing plane in nonlinear data</figcaption></figure><p>It is worth noting that Dimensionality Reduction algorithms are part of feature engineering, that is, if you have unnecessary features that can be removed or feature cross-referenced, then you should do so.</p><h3>Model — driven vs data — driven approach</h3><p>There are two approaches to building a model: spend more time processing and transforming data, or do minimal data processing and instead focus all your efforts on developing a powerful and optimized model. Each approach has its advantages and disadvantages, depending on the task at hand. Personally, I am a fan of data-driven and here is why:</p><ul><li><strong>Lack of capacity</strong>: to build a complex and accurate model that can process large-dimensional datasets requires a huge amount of data, more training time, more complex tuning and optimization, even when using quantization and other efficient methods.</li><li>The <strong>problem of generalization</strong>: even the best models, for example, the same ChatGPT, have biases on individual topics — biases regarding nationality, race, etc.</li><li>Creating a high-accuracy model for raw data is in most cases much more difficult and resource-intensive than processing the data.</li></ul><h3>Entropy</h3><p>The entropy of a random variable X is the level of uncertainty inherent in the possible outcome of the variable.</p><p>It sounds abstract, but it will become clearer now. First, let’s look at an example: determine the probability of drawing different types of figures from a container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*zkEgzUDPZ38bHnNQf4g87Q.png" /><figcaption>You can read the full article <a href="https://towardsdatascience.com/cross-entropy-loss-function-f38c4ec8643e">here</a></figcaption></figure><ul><li><strong>Container 1</strong>: The probability of drawing a triangle is <strong>26/30</strong>, and the probability of drawing a circle is<strong> 4/30</strong>.</li><li><strong>Container 2</strong>: The probability of drawing a triangle is <strong>14/30</strong> and <strong>16/30</strong> for a circle. The probability of choosing a particular shape is almost 50/50. The confidence in choosing a shape is less than in case 1.</li><li><strong>Container 3</strong>: The probability of drawing a circle is <strong>29/30</strong>, and the probability of drawing a triangle is <strong>1/30</strong>. It is highly likely that the chosen shape will be a circle.</li></ul><p>In which of these three cases can you be most confident in predicting which figure you will draw? Intuitively in case 3, which is confirmed by entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*u175GMHadSkmdCggKnfPXA.png" /><figcaption>Entropy calculation</figcaption></figure><p>In simple terms, entropy is a measure of predictability. The lower the entropy, the more confident you can be.</p><h3>Entropy as a loss function</h3><p><em>This part is dedicated to classification using neural networks only; machine learning methods used for classification work on different principles.</em></p><p>It is important to remember the difference between a loss function and an optimizer. A loss function estimates the difference between a class (<strong>label</strong>) and the value predicted by the neural network, while an optimizer changes the weights (<strong>W matrix</strong>) during Backpropagation to find the minimum of the loss function. All activation functions for classification return the probability of a particular class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*41uinSp-KfznFSgCTzcuNQ.png" /><figcaption>Activation functions on the example of Softmax</figcaption></figure><p>But how can we evaluate the accuracy of a neural network’s prediction if it is a probability? Can we simply subtract the probability from the label? First of all, if we simply subtract, the probability becomes an ordinary number that does not evaluate anything. If we evaluate the predicted probability using the entropy formula, we get an indicator of “prediction confidence”. For greater understanding, let’s calculate the entropy for this predicted probability and the true class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*FETG7jDP4qyxqxqGgV0vEg.png" /><figcaption>On the left is the class probability predicted by the neural network. On the right are the actual classes of the dataset.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*_xbIzVf35hvA8df69Q-jKA.png" /><figcaption>Calculated probability</figcaption></figure><p>An entropy of<strong> 0.3677</strong> is an indicator that the neural network <strong>is not very “confident”</strong> in its own prediction. Let’s check the probability for the next epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*xw6728vy_kwczQ-SNUbBdA.png" /><figcaption>The entropy value has decreased</figcaption></figure><p>The entropy value has decreased (the probability of the correct class, the first, has become higher) — the neural network is learning.</p><h4>Categorical Cross-Entropy vs Sparse Categorical Cross-Entropy</h4><p>The choice of entropy function is based on the form in which the classes (labels) are presented to the neural network. Both categorical and sparse entropy use the same entropy formula.</p><ul><li><strong>Categorical Cross-Entropy</strong>: if the labels are in the form of a one-hot vector, i.e. the true class is labeled 1, all other classes are labeled 0. For example, your dataset consists of 3 classes: dogs, cats, parrots. A photo where there is a dog will have the vector [class dog, class cat, class parrot] = [1,0,0].</li><li><strong>Sparse Categorical Cross-Entropy</strong>: if the labels are class number, 1,2,3…, etc.</li></ul><p>In practice, it is still <strong>recommended to use labels in the form of a one-hot vector</strong>, because there is<strong> no connection between the vectors</strong>. For example, if your labels were numbered in a random order, class “1“ is bread, class “2“ is dog, the neural network may “think” that there is a connection between dog and bread.</p><h3>Ensemble</h3><p>Remember the school game “What? Where? When?”? My team often went to competitions, and it was there that I realized the value of teamwork. Ensemble works on a similar principle — by combining the results of several models, you can improve the quality of predictions, reduce variance, bias, and increase the level of generalization even on noisy data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*EaoWpksd6gfGiW-cJd2OdQ.png" /><figcaption>The principle of operation of ensemble models</figcaption></figure><h4>How to choose models for ensemble?</h4><p>There are two approaches: Homogeneous — ensemble of models of the same type, and heterogeneous — ensemble of models of different types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*RZFnv8bW8Xl7XbyTIm6Oyw.png" /><figcaption>Types of ensemble</figcaption></figure><p>Homogeneous ensemble is implemented in two algorithms: Bagging and Boosting.</p><h4>Bagging</h4><p><strong><em>Homogeneous ensemble, reduces variance</em></strong></p><p><strong><em>Training: Parallel training</em></strong></p><p><strong><em>Example: Random Forest</em></strong></p><p>This method involves training multiple instances of the model on different subsets of training data created using bootstrapping (random sampling with replacement).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*jOe2pejk70A1Rqh3YsSOmQ.png" /><figcaption>Bootstrapping</figcaption></figure><p>Bootstrapping allows you <strong>to train a model on independent subsets (samples</strong>) of a dataset without knowing the true distribution of the data, thereby increasing generalizability. Bootstrapping is often used to estimate the variance or confidence intervals of statistical estimates, since each sample is independent.</p><p>It can be conditionally divided into two parts: Bootstrapping and Aggregating (which is essentially ensemble).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*jQ_LY6rB80DuSvU_hWof7w.png" /><figcaption>Bagging Ingredients</figcaption></figure><p>There are two types of final function (Aggregating part), which summarizes the prediction result of all models: <strong>for regression problem</strong> — this is the <strong>weighted average</strong>, for <strong>classification — voting</strong>, <strong>hard — voting</strong>, when the predicted class is the class that was predicted by most models, soft — voting, the predicted class is the class with the highest average probability.</p><h4>Boosting</h4><p><strong><em>Homogeneous ensemble, reduces bias</em></strong></p><p><strong><em>Training: Consistent training.</em></strong></p><p><strong><em>Example: XGBoost, LightGBM</em></strong></p><p>Models are trained sequentially, with each new model focusing on the errors of the previous ones. The idea is to iteratively select models in such a way that the training of the model at a given step depends on the models selected at previous steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*1dbHRBWk_u1n41Dfxp4QWw.png" /><figcaption>Boosting</figcaption></figure><p><strong>Each data poin</strong>t in the dataset is <strong>assigned a weight</strong>, with incorrectly classified points receiving a higher weight in subsequent iterations. Since boosting is an iterative method, it is best used on shallow models rather than large, complex ones. Unlike bagging, the prediction is made by the last model, there is no final function.</p><h4>Stacking</h4><p><strong><em>Heterogeneous ensemble, reduces bias</em></strong></p><p><strong><em>Training: each model is trained independently</em></strong></p><p>For Stacking, models can be trained both in parallel and sequentially. It is considered the most powerful algorithm because it allows for the use of different types of models, and instead of a final function, a meta-model is used that processes the predictions of already trained models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*yDFZuJwjkZFLzKgS9b1SgA.png" /><figcaption>Stacking</figcaption></figure><p>An important point about ensemble is that the <strong>choice of models should be consistent with the way in which these models are combined</strong>. If low-bias but high-variance base models are chosen, then the ensemble method should be one that tends to reduce variance, while if low-bias but high-bias models are chosen, then the ensemble method should be one that tends to reduce bias. Low-variance machine learning algorithms include linear regression, logistic regression, and linear discriminant analysis (LDA). High-variance algorithms include Random Forest, SVM, and KNN.</p><h3>Unbalanced classes</h3><p><strong>Imbalanced datasets have an uneven number of elements in classes</strong> and without proper processing (or using methods that can handle unbalanced classes — Random Forest) can lead to overfitting or underfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*77ppPdJQawekCIFThzNeOQ.png" /><figcaption>Balanced and unbalanced datasets</figcaption></figure><p>Let’s imagine that we have an unbalanced dataset on which we need to train a classifier for tumor recognition. The dataset contains 90% of photos of patients without tumors and 10% with tumors. When using the original dataset for training, the model will most likely classify, or rather simply output the result “no tumor”, without processing patterns in the data. Roughly speaking, instead of a neural network, we will get a program that will output “no tumor” to the console.</p><p>For training a robust classifier, the most popular methods are adding data to small classes (<strong>OverSampling</strong>) or reducing the number of elements of all classes to the number of elements of the smallest class (<strong>Undersampling</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*bRLFaNse7bbdPI7t3vmZ8g.png" /></figure><p>The choice of which method to use depends on the specific situation, but in most cases <strong>Undersampling is not chosen because it leads to data loss</strong>.</p><h3>Steel Plate Defect Prediction Competition</h3><p>My full code can be found here<a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling#Weighted-Average-Ensembling-NN"> here</a>.</p><h4>Data processing</h4><p>The goal of the competition is to develop a classifier for classifying scratches into 7 classes. The original dataset has 34 features, it is not 200, but not 3 either, you need to try to reduce the number of features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*1Fej36Dfq047nDG3D5NldQ.png" /><figcaption>Original dataset</figcaption></figure><h4><strong><em>Correlation</em></strong></h4><p>Some features have high correlation — one feature can be expressed through another. Correlation does not allow us to understand how important the features are, thereby reducing the interpretability of the model — it is difficult for the developer to understand which features make the model have low accuracy and how to improve it. Interpretability is an incredibly important and interesting topic, which I will talk about in the next long-form readings dedicated to MLOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*h7pYfCo4R9JNZzRIkkk2eA.png" /><figcaption>Correlation between traits</figcaption></figure><p>Some samples (data units of the dataset) have multiple class labels, and some have no labels at all, which effectively turns multiclass classification into multilabel classification. Some developers have decided to build a multilabel model, but I have decided to stay with multiclass classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*fNKfRZdm_7J8qPuPkunt6A.png" /><figcaption>Number of samples with 0, 1 and 2 class labels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*TJ0wQ4hFZPhL90lJEfdBLg.png" /><figcaption>Samples with 2 class labels at the same time</figcaption></figure><p>To solve this problem with 2 labels, I did the following:</p><ul><li><strong>Leave only one label </strong>— Other_faults for samples that have multiple labels.</li><li>I <strong>removed samples</strong> that did not have scratches. It can be assumed that they were included in the dataset by mistake.</li></ul><h4><strong><em>Feature Engineering</em></strong></h4><p>The dataset has 13 features, which can be transformed to reduce the dimensionality of the data. For example, by subtracting Y_minimum from X_maximun, a ranking is found, that is, a common feature is created from two features, thereby eliminating correlation.</p><pre>def calculate_coordinate_range_features():<br>data[&#39;X_Range&#39;] = (data[&#39;X_Maximum&#39;] - data[&#39;X_Minimum&#39;])<br>data[&#39;Y_Range&#39;] =( data[&#39;Y_Maximum&#39;] - data[&#39;Y_Minimum&#39;])<br>data.drop([&quot;X_Maximum&quot;,&quot;Y_Minimum&quot;,&quot;X_Minimum&quot;,&quot;Y_Maximum&quot;], axis=1, inplace=True)</pre><p>Function<a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling?scriptVersionId=169428218&amp;cellId=24"> def feature_engineering(data)</a> is an example of a nested function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*7g1e5-XIYVbkbUquQLSJWA.png" /><figcaption>Dataset after feature transformation</figcaption></figure><p>After application, 22 signs remained.</p><p>Ghosting features to a single range (scaling) is a necessary procedure for some algorithms, but is almost always not superfluous, as it helps speed up learning. I did it using RobustScaler, separately for the test and training sets.</p><pre>from sklearn.preprocessing import RobustScaler<br>train = train_x_featENG.astype(np.float64)<br>test = test.astype(np.float64)<br>test=feature_engineering(test)<br>scaler = RobustScaler()<br>train_scaling = scaler.fit_transform(train)<br>test_scaling = scaler.transform(test)</pre><p>The choice of this particular scaler is due to the fact that the data has outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*B0BKY_TCSacB9rn7z3yVdQ.png" /><figcaption>Almost all signs have emissions</figcaption></figure><h3>Unbalanced classes</h3><p>To balance the classes, I chose the technique of increasing small classes — OverSample, since the amount of data is already small enough to further reduce it through UnderSample.</p><pre>from imblearn.over_sampling import RandomOverSampler<br>ros = RandomOverSampler(sampling_strategy=&#39;auto&#39;, random_state=42)<br>sampling_y=train_y.to_numpy()<br>X_res, y_res = ros.fit_resample(train_scaling, sampling_y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OhoncpQICHIQ6SErlw541w.png" /><figcaption>Left — before RandomOverSampler, right — after</figcaption></figure><h4>Visualization and dimensionality reduction</h4><p>Hypertools is a library for geometric visualization of multidimensional data, unlike PCA, which is a Dimensionality Reduction technique. Both the first and second algorithms show that constructing a dividing plane is not so simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*oHULPfXxAQXmnS3G1ZzRgA.png" /><figcaption>Hypertools (left), PCA (right)</figcaption></figure><p>I decided not to use the data on which I built the PCA for the sake of the purity of the ensemble experiment.</p><h3>Ensemble</h3><p>I made the ensemble option:</p><ul><li><strong>Combining the results of two boosting methods</strong>, XGBoost and LightGBM, using VotingClassifier, which is almost a bagging method</li><li><strong>Weighted Average ensemble of two neural networks</strong> using a meta-model, simplified Stacking, because I like to experiment.</li></ul><p><strong>VotingClassifier</strong></p><p>For this implementation, I previously tuned the XGBoost model, but left the LightGBM model with manual parameters (I did not tune LightGBM, since I had already used all possible GPUs in Keggle, and without them, tuning would be incredibly long).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*5mp5YBdURbqxGFMuzBHNYw.png" /><figcaption>Left — LightGBM, right — XGBoost</figcaption></figure><p>For VotingClassifier, the <strong>required parameter is the weights</strong>, which in my case is the <strong>ROC-AUC score</strong> of the two models: the lower the accuracy of the model, the less influence it has on the predictions.</p><pre>def evaluate_models(models, X_train, X_val, y_train, y_val):<br> # fit and evaluate the models<br>     scores = list()<br>     for model in models:<br> # fit the model<br>         model.fit(X_train, y_train)<br> # evaluate the model<br>yhat = model.predict_proba(X_val)<br>acc = roc_auc_score(y_val, yhat)<br> # store the performance<br>         scores.append(acc)<br> # report model performance<br>     return scores<br>from sklearn.ensemble import VotingClassifier<br>models=[LGBMClassifier(**parameters_dict),XGBClassifier(**c)]<br>scores = evaluate_models(models, X_train, X_test, y_train, y_test)<br># create the ensemble<br>ensemble = VotingClassifier(estimators=[(&#39;lr&#39;, LGBMClassifier(**parameters_dict)), (&#39;rf&#39;, XGBClassifier(**c))], voting=&#39;soft&#39;, weights=scores)</pre><p>I chose soft-voting, since I’m only assembling two models. The accuracy on the test set is quite high, the accuracy on the validation set, by which the competition participants are evaluated, is lower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*YR040ZIhOSCjbokSD4f1dQ.png" /><figcaption>Accuracy on the test set</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QDrm5AL2yM-M9Nfo3NXAtQ.png" /><figcaption>Accuracy on validation</figcaption></figure><p>PCA and almost all dimensionality reduction methods took much time, but based on results i can say that model is overfitting, especially if look at complexity.</p><p><strong>WeightedAverage Ensembling + skip — connections NN</strong></p><p>WeightedAverage is a simple ensemble method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ulltrhjchz_mE5Mv48G-OQ.png" /><figcaption>Ensemble methods</figcaption></figure><p>Yes, anticipating questions, I added the very famous skip — connections to one of the two ensemble neural networks, such connections help the gradient not to fade. The full scheme is very large, you can see<a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling?scriptVersionId=169428218&amp;cellId=74"> here</a> . The skip — connections block looks like this:</p><pre>def skip_connection(previous_layer):<br>def skip():<br>        start = layers.Dense(256, activation=&quot;leaky_relu&quot;)(previous_layer)<br>        dense_0 = layers.Dense(256, activation=&quot;leaky_relu&quot;)(start)<br>        dense_1 = layers.Dense(256, activation=&quot;leaky_relu&quot;)(dense_0)<br>        dense_2 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_1)<br>        dense_3 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_2)<br>        batch_norm = layers.BatchNormalization()(dense_3)<br>        dense_4 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(batch_norm)<br>        concat = keras.layers.Concatenate(axis=1)([start, dense_4])<br>        #batch_norm_1 = layers.BatchNormalization()(concat)<br>        outputs = layers.Dense(128, activation=&quot;leaky_relu&quot;)(concat)<br>        return outputs<br>    return skip()</pre><p>The full structure of the first neural network:</p><pre>inputs = keras.Input(shape=(X.shape[1],))<br>dense_1=layers.Dense(256, activation=&quot;leaky_relu&quot;)(inputs)<br>dense_2=layers.Dense(512, activation=&quot;leaky_relu&quot;)(dense_1)<br>#batchNorm_1=layers.BatchNormalization()(dense_2)<br>s=skip_connection(dense_2)<br>dropout=tf.keras.layers.Dropout(0.2)(s)<br>s2=skip_connection(dropout)<br>dropout_2=tf.keras.layers.Dropout(0.3)(s2)<br>s3=skip_connection(dropout_2)<br>dropout_3=tf.keras.layers.Dropout(0.2)(s3)<br>#s4=skip_connection(dropout_3)<br>#dropout_4=tf.keras.layers.Dropout(0.3)(s4)<br>dense_3=layers.Dense(256, activation=&quot;leaky_relu&quot;)(dropout_3)<br>dense_3_1=layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_3)<br>dense_4=layers.Dense(7, activation=&quot;softmax&quot;)(dense_3_1)<br><br>model = keras.Model(inputs=inputs, outputs=dense_4,name=&quot;skip_conn_model&quot;)</pre><p>For faster learning, the second model has a very simple architecture, without skip — connections:</p><pre>inputs = keras.Input(shape=(X.shape[1],))<br>dense_1=layers.Dense(256, activation=&quot;elu&quot;)(inputs)<br>dense_2=layers.Dense(512, activation=&quot;elu&quot;)(dense_1)<br>batchNorm_1=tf.keras.layers.Dropout(0.4)(dense_2)<br>#s=skip_connection(batchNorm_1)<br>#dropout_2=tf.keras.layers.Dropout(0.4)(s)<br>dense_3=layers.Dense(512, activation=&quot;elu&quot;)(batchNorm_1)<br>dense_3_1=layers.Dense(256, activation=&quot;elu&quot;)(dense_3)<br>dropout_2=tf.keras.layers.Dropout(0.2)(dense_3_1)<br>dense_3_2=layers.Dense(128, activation=&quot;elu&quot;)(dropout_2)<br>dense_4=layers.Dense(7, activation=&quot;softplus&quot;)(dense_3_2)<br><br>model1 = keras.Model(inputs=inputs, outputs=dense_4,name=&quot;light_model&quot;)</pre><p>The optimizer for both models is Adam, the metric is AUC.</p><p>Retraining models that take a long time to learn is a very unpleasant thing, so I store the best weights using checkpoints in the model after training. In some articles you can see storing the best weights via EarlyStopping, but this is wrong.</p><pre>def checheckpoints(model):<br>    path=&#39;/kaggle/working/Weights_&#39;+model.name+&#39;.weights.h5.keras&#39;<br>    checkpoint = tf.keras.callbacks.ModelCheckpoint(path, <br>                    monitor=&quot;val_loss&quot;, mode=&quot;min&quot;, <br>                    save_best_only=True, verbose=10)<br>    return checkpoint,path<br>callback =  tf.keras.callbacks.EarlyStopping(<br>    monitor=&quot;val_loss&quot;,<br>    patience=10<br>)</pre><h3><strong>Learning outcomes</strong></h3><ul><li>First model (skip-connections):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*9zUvrzunLZRRi5tCglCd0A.png" /><figcaption>On the right is the loss function, on the left is the accuracy function</figcaption></figure><ul><li>The second, simpler model, to my surprise, showed much better results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*WS_Hg048HrABX0ypM6l2XQ.png" /></figure><p>Retraining began at epoch 40, before which the error function had been decreasing uniformly.</p><p>Such <strong>results clearly show that the first model needs to be simplified, or regularization added</strong>. In real projects, models usually need to be tuned. Similarly to the first option, ROC — AUC was used as the weights for ensemble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*V-qbzs7kT9HK7SXnpK41qA.png" /><figcaption>Search for scales</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*r_O4rZUDclzNOY6t9NphSw.png" /><figcaption>Converting weights to a matrix</figcaption></figure><p>A block for averaging predictions between two models:</p><pre>class WeightedAverage(Layer):<br><br>    def __init__(self):<br>        super(WeightedAverage, self).__init__()<br>        <br>    def build(self, input_shape):<br>        <br>        self.W = self.add_weight(<br>                    shape=(len(input_shape),),<br>                    initializer=weight_init,<br>                    dtype=tf.float32,<br>                    trainable=True)<br>    def call(self, inputs):<br>    <br>        inputs = [tf.expand_dims(i, -1) for i in inputs]<br>        inputs = Concatenate(axis=-1)(inputs) <br>        weights = tf.nn.softmax(self.W, axis=-1)<br><br>        return tf.reduce_mean(weights*inputs, axis=-1)</pre><p>The meta model has the following form:</p><pre>inputs = Input(shape=(X.shape[1],), name=&#39;inputs&#39;)  # input layer<br># get output for each input model<br>outputs = [model(inputs) for model in models] <br># take average of the outputs<br>x = WeightedAverage()(outputs) <br><br>x = layers.Dense(512, activation=&#39;leaky_relu&#39;)(x)<br>x = tf.keras.layers.Dropout(0.4)(x) <br>x = layers.Dense(256, activation=&#39;leaky_relu&#39;)(x) <br>x = layers.Dense(128, activation=&#39;leaky_relu&#39;)(x) <br>x = tf.keras.layers.Dropout(0.4)(x) <br>x = layers.Dense(128, activation=&#39;leaky_relu&#39;)(x) <br>x = layers.Dense(64, activation=&#39;leaky_relu&#39;)(x) <br>output = layers.Dense(7, activation=&#39;softmax&#39;, name=&#39;output&#39;)(x) # output layer<br><br># create average ensembled model<br>avg_model = keras.Model(inputs, output)</pre><p>Well, the experiment is not very successful so far, but I plan to continue trying to improve the accuracy with other methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xyFROy7OHvEFCDLkSRYLjQ.png" /><figcaption>Result of neural network ensemble</figcaption></figure><p>A possible explanation is a problem in the dataset itself, meaning you need to change your feature engineering tactics and try synthetic data.</p><p><strong><em>Thanks for reading! I would be happy to answer any questions.</em></strong></p><h3>Useful links</h3><ul><li><a href="https://semaphoreci.medium.com/how-to-handle-imbalanced-data-for-machine-learning-in-python-b6d56c9a0489">How to handle unbalanced classes?</a></li><li><a href="https://pub.aimind.so/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">How to properly store the best model weights?</a></li><li><a href="https://towardsdatascience.com/bias-and-variance-for-model-assessment-a2edb69d097f">Bias Variance Decompositional</a></li><li><a href="https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205">Ensemble methods</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a3420b88cf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to time series]]></title>
            <link>https://medium.com/@mirandorexes/introduction-to-time-series-31789eaab67c?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/31789eaab67c</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 14:50:37 GMT</pubDate>
            <atom:updated>2026-09-29T14:50:37.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Most tutorials on this topic contain very little or no theory and use 1–2 of the most popular models. This article is devoted to the theory, simple and more complex methods of time series analysis and forecasting. I divided the material into three conditional parts — easy, medium and difficult, because the key to understanding is to start with the basics.</p><h3>Understanding Time Series with human brain</h3><p>What is a time series? It is the change in the amount of food your cat or dog eats over time. It is the fluctuation in the price of a corporation’s stock, the temperature readings over the course of a day, the change in the taste of tea over time. How do you understand and process a time series correctly?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Q4-SEUsNe735GD3z0zHdfg.png" /><figcaption>Difference between experiment and time series</figcaption></figure><p>The main difference between a time series and individual experiments, which can be depicted using a histogram, is that<strong><em> each point (variable) in the time series is equidistant from the next point and may depend on the previous one</em></strong> (autocorrelation).</p><h4><strong>What can you do with a time series and why is it so useful?</strong></h4><p>Time series makes it possible to <strong>predict the value of the next (future) point (variable)</strong>, for example, to predict the price of a stock in an hour, a day, a week, based on the dimensionality of the data. But regression does the same thing, doesn’t it? This is where the main difference lies. The result of regression is a quantitative assessment of the influence of independent variables on the process, while a time series can be reproduced by decomposition without calculating the influence of each variable, that is, without “looking under the hood”. The series consists of two parts — signal and noise. Signal is mathematically dependent variables that can be analyzed and removed from the time series. Noise, on the other hand, <strong>consists of random values</strong>, most often normally distributed, and visually similar to audio noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*9_1L-7aeiE2uyePt0XzwDw.png" /><figcaption>How noise affect signal</figcaption></figure><p>Real data is a combination of noise and signal, and most often the low quality of the model depends precisely on the inability to reproduce (predict) noise.</p><p>Signal patterns and how to see them:</p><ol><li>Seasonality — cyclical fluctuations of a variable over time. For example, a decrease in temperature in winter.</li></ol><p>2. Trend (trend/level) is the slope of the series relative to the horizontal axis. The trend can be increasing or decreasing; if the trend is unchanged, the time series is horizontal.</p><p>3. Autocorrelation is the “memory” of a series, the value of a variable at a specific time directly depends on the previous values ​​of the variable.</p><p>If a series does not contain a pattern, it is called stationary. Stationary is a series without trend and seasonality, the mean and standard deviation of which are constants. A separate pattern is a time series that cannot be made stationary by removing the trend and/or seasonality. Such series are called difference — stationary.</p><p><strong><em>In </em></strong><a href="https://www.youtube.com/watch?v=Prpu_U5tKkE&amp;t=276s"><strong><em>this video</em></strong></a><strong><em> you can listen to more details about time series.</em></strong></p><p>Training a high-quality model for modeling and forecasting time series is a long and laborious process. The algorithm for training the series depends on the choice of model, dataset and may include basic data cleaning (normalization), feature extraction and algorithms for bringing the series to a stationary state. In the following paragraphs, I will describe in detail the training of the series for different algorithms. For some models, high quality can be achieved without cleaning the time series, for others, all of the cleaning methods listed above must be performed.</p><h3>Time series forecasting in ML</h3><p>First of all, collect, clean and understand data. I will use rolling mean and ARIMA/SARIMA for basic understanding and then more advance model for actual prediction.</p><h4><strong>Dataset and preface</strong></h4><p>The article turned out to be larger than expected, so the entire code can be found at <a href="https://www.kaggle.com/code/annack/tsa-and-forecasting-from-a-to-z-tutorial">this laptop</a>, contains comments in English, but I plan to translate it into Ukrainian. I will use this as training data <a href="https://www.kaggle.com/datasets/rakannimer/air-passengers">dataset</a>, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*XFJDweVoXAsXYJh4IDigmQ.png" /><figcaption>The dataset shows the number of passengers during 1949–1960, monthly</figcaption></figure><h3><strong>Time series analysis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*LntX80AVBrlJpQ_2RsyunA.png" /><figcaption>visualized time series</figcaption></figure><p>I’ll start with the methods used to analyze many types of data.</p><h4><strong>Definition of distribution</strong></h4><p>The first step of almost all kind of analys — distribution.</p><p>To determine the distribution, a histogram is used. Dataframe has a built-in hist() method.</p><pre>df.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Ji0p0DCq61OnEBAHcto-cQ.png" /><figcaption>Histogram of dataset</figcaption></figure><p>The time series <strong>has a non-normal distribution</strong>, which <strong>narrows the range of methods</strong> that can be used to normalize the data to one, namely MinMaxScaler. From a mathematical perspective, such a distribution signals that the time series is likely <strong>not stationary — means, hard to predict</strong>.</p><h4><strong>Outliers</strong></h4><p>Outliers are data that “stand out” from the general heap, can be either very small or very large, compared to the nearest point. They affect the quality of most machine learning models and the choice of loss function.</p><p>The easiest way, but not always effective, to check for outliers is to look at the histogram. For example, if the column between 500 and 600 contained no data (would be white), one could assume that column 600 was an outlier. A more effective visual way is to use sns.boxplot:</p><pre>sns.boxplot(df.Passengers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*z-sh7faTIUv4B7qSC5Bcbg.png" /><figcaption>Boxplot</figcaption></figure><p>I like boxplot with all my heart, but its visual method.</p><p>The boxplot view confirms that the data is free of outliers — the vertical axis contains no black dots that indicate outliers.</p><h4>NAN check</h4><p>NAN is an unidentified data type that does not appear in the boxplot and pollutes the data. Values ​​of this type should be removed, as most machine learning algorithms cannot handle them. I will output statistics along with the number of NAN values.</p><pre>print(df.describe())<br>print(&quot;NAN values:&quot;,df.isna().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*csSsLkDyhZRlzJKQZskiAQ.png" /><figcaption>Series statistics and number of NAN values</figcaption></figure><p>Well, great! The array has no NAN values ​​- one less problem.</p><h4><strong>Seasonality, trend and noise</strong></h4><p>Or the three stones of forecasting.</p><p>Look at the illustration below, how quickly will you find the trend and seasonality? I’m sure it will be in a couple of seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*rAnsMb0Yp7Y4aJ1sXcHnZg.png" /><figcaption>On the left is the full time series, on the right is the series without a linear trend</figcaption></figure><p>A stationary time series is easier to predict because the trend is constant, unlike a non-stationary time series whose trend can be changed by an event (for example, Twitter shares fell due to Elon Musk’s statement), which is very difficult to predict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*5uG-eIIsrTUrrr6JSAdMsQ.png" /></figure><p>Understanding trend, seasonality, and noise are key to understanding time series. The easiest way to find them is statsmodels.tsa.seasonal.</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose<br>decomposed = seasonal_decompose(df[&#39;Passengers&#39;]) <br>decomposed.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*_dbfrVk6KXMeNWWwIQOHWA.png" /><figcaption>Bottom up: full series, trend, seasonality, noise</figcaption></figure><p>The trend is almost linear and increasing. This is good because a linear trend is easier to predict than a nonlinear one. The seasonality is the same and repeats every year. The noise (resid) is the time series after removing the trend and seasonality from it. For this time series, the noise from is quite strong, which can reduce the quality of the forecast. Let’s consider seasonality on the example of one year.</p><pre>df_month=df.copy()<br>df_month[&quot;Month&quot;]=[d.strftime(&#39;%b&#39;) for d in df_month.index]<br>plt.figure(figsize=(20,10))<br>sns.boxplot(x=df_month[&quot;Month&quot;],y=df_month[&quot;Passengers&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*QRy8muSDPVH-9CXgJABLTw.png" /><figcaption>Bottom up: full series, trend, seasonality, noise</figcaption></figure><p>The trend is almost linear and increasing. This is good because a linear trend is easier to predict than a nonlinear one. The seasonality is the same and repeats every year. The noise (resid) is the time series after removing the trend and seasonality from it. For this time series, the noise from is quite strong, which can reduce the quality of the forecast. Let’s consider seasonality on the example of one year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*GHAuShq9pEH3jurNVdWx3g.png" /><figcaption>Seasonality</figcaption></figure><p>Passenger numbers increase during the two summer months and decline after August. One reason is that people fly on vacation in the summer.</p><p>The following checks are performed only for time series.</p><h4><strong>Augmented Dickey-Fuller (ADF) test</strong></h4><p>The ADF test is a test for checking the stationarity of a time series based on <a href="https://medium.com/codex/unit-root-in-time-series-38d451d742ce">unit root </a>— is a process that determines whether a time series is stationary through differentiation. The test works on the principle of accepting or rejecting the null hypothesis, which is that the series is not stationary. Accepting or rejecting the null hypothesis is decided by the p-value (the probability of the null hypothesis being incorrect): if the value is greater than a certain constant, then the null hypothesis is accepted (the series is not stationary), if less, the hypothesis is rejected (the series is stationary). Traditionally, the constant = 0.05 (5%), but it can be different, depending on the data and model. It is also important to look at the value of the statistic, if it is greater than any critical value, then the time series is not stationary.</p><p>Implementation of the function below in cell 13.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*IeNQgPrXv2MVc3p6H1-vQA.png" /><figcaption>Test result on the full time series</figcaption></figure><p>Rolling mean is the average value of the points of the time series, and yes, it repeats the trend line. Rolling std is the value of the dispersion of the points of the series. In simple words — the greater the dispersion, the greater the “dispersion of the data”. The smaller the “waves” (see 1950) — the smaller the dispersion, the larger the waves — the greater the dispersion (see 1960). It can immediately be assumed that over the years the dispersion will become more and more.</p><p>And the last point</p><h4><strong>Autocorrelation</strong></h4><p>Correlation is the relationship between variables, autocorrelation is the relationship between a variable and its own previous values. Since the series has only one variable — the number of passengers, we only need to analyze the autocorrelation. Before the autocorrelation graph is revealed in all its glory, I will talk about the concept of lags — this is the value of the variable n — the amount of time back, since the dimension of my time series is a month, then lag -1 means the value 1 month ago for the current variable, -2 — two months ago, etc. In the graph below, the number of lags is 4.</p><pre>from statsmodels.graphics.tsaplots import plot_acf<br>plot_acf(df,lags=4)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*nlCk1Gup6nypdNv1d7tdVA.png" /><figcaption>Autocorrelation at 4 month lags</figcaption></figure><p>Column 1 (0) is the autocorrelation of the value with itself and will always be equal to 1, column 2 (1) is the autocorrelation of the current value with the value a month ago, etc. The blue cone is the 95% interval, meaning that everything outside the cone is most likely a correlation, not a statistical error. The time series has a strong correlation, which can lead to increased bias. If the model has high bias, it is an undertrained model, if the model has high variance, it is an overtrained model.</p><p>That’s it, statistics are over, let’s move on to simple methods of time series decomposition to make the series stationary.</p><h4><strong>Time series decomposition</strong></h4><p>Decomposition is the process of transforming a non-stationary time series into a stationary one by removing seasonality and trend from it. I will note right away that decomposition is only necessary for some models, for example, regression models such as ARIMA/SARIMA, models such as LSTM/GRU, XGBoost, Prophet are so powerful that they process non-stationary series. There are libraries that can decompose a series into a single line, but do not have an inverse function for reconstruction. Reconstruction of a time series is the process of adding the trend and seasonality back to the series, if this is not done, the series will be parallel to the x-axis and will be of little use as a forecast.</p><ol><li><strong>Deseasonality (seasonality modeling)</strong><br>In order to remove seasonality, the difference (differentiation) between a specific value of a variable (Y) at a specific time (t) is most often used according to the following formula:<br>Yt = Yt — Yt-n, <em>n </em>is an indicator of seasonality. For example, if seasonality is present every year, then<em>n</em>= 12, 12 months — 1 year, etc.</li></ol><p>The function def deseasonality(df,seasonality) subtracts the value of the previous year from each value in the dataframe and returns dataframe[seasonality:], thus losing the first year. Its inverse is def add_seasonality(df,diff,seasonality), which adds the seasonality from the original dataframe and adds the resulting seasonality to the dataframe without seasonality. I will use this function to reconstruct the series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*I4H5G4ZKlqvxwHRBokSnoQ.png" /><figcaption>Time series after seasonality removal</figcaption></figure><p>After removing seasonality, the time series is already stationary, most likely due to a linear trend, but for more accurate forecasting, I will also remove the trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Jmjfh8V9Uq96x8eeG8Y0jw.png" /></figure><p>2.<strong> Detrending</strong><br>The trend is the rolling mean of the time series, so to detrend you need to subtract the mean from the series you got in the previous step. The easiest way to do this is with the rolling mean algorithm. I made two variations, but I will only show the first one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*CNSnaWJXJ8Rclh6fgsVZjg.png" /><figcaption>Decomposed time series (blue) and series without seasonality (orange)</figcaption></figure><p>You can see that the average value of the series has become close to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*mmv3PWKpqVTJ0ozsUFgjNA.png" /><figcaption>ADF test</figcaption></figure><h4>Loss functions</h4><p>Indicators of the quality of models and forecasting for time series are loss functions and error metrics. The most commonly used loss functions are MAE (L1 norm) — “Mean Square Error”, MSE (L2 norm) — “Mean Absolute Error”.</p><p><strong>MAE </strong>gives each error the same “weight”, that is, it is a robust function to outliers and noise, but at the same time it underestimates the “impact” of large errors.</p><p><strong>MSE</strong>, on the other hand, gives greater weight to larger errors, making the function more sensitive to outliers. If the model needs to be sensitive to errors, this is the function to choose.</p><p>I will use both functions as metrics and one of them as a loss function. What does the comparison of MAE and MSE show? For example, I will take the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*c0aWaWhPnaAuXkK8bKm_SA.png" /><figcaption>MAE MSE for comparison</figcaption></figure><p>MSE of 1856 means that the mean squared error is 1856, which is 43.081². MAE is 33.44, which means the mean error is 33.44.</p><p>In this example, the MSE is larger than the MAE squared, indicating that there are large errors that increase the MSE. Outliers, nonlinearity, or noise are the cause of this, since there is a lot of noise in this time series, we can assume that it is the cause. If the MSE is smaller than the MAE squared, the model has small errors that increase the MAE. The reason for this is randomness or imprecision in the data.</p><p>The accuracy of a time series cannot be found by a standard accuracy function, so I use the following metric to evaluate the accuracy of the forecast and reconstruction. MAPE is a relative error value that can be used as an accuracy function according to the following formula: 100-(MAPE*100). The function to calculate MAPE is in cell 16.</p><h4>Naive Forecasting</h4><p>Naive forecasting is the simplest method for forecasting a time series, the accuracy of which is high only in the case of a constant (horizontal) trend.</p><p>The formula for naive forecasting is: <strong><em>Yt = Yt-1</em></strong>: the future value of the time series is its previous value. Okay, not very impressive, but let’s try it anyway. I split the original time series into a test and training set (the last two years). The first forecast for the test set is the last value of the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*ZnueWuW2STdmeww7cNuIAA.png" /><figcaption>Naive forecasting</figcaption></figure><p>Since the 1st value of the test sample is 317, all subsequent values ​​will also be 317, resulting in a horizontal line. Let’s move on to more precise methods.</p><h4><strong>Time series reconstruction with rolling mean</strong></h4><p>I haven’t come across such an algorithm, but it nicely illustrates the plasticity of a time series and what can be done with it. First, let’s look at the graph of the time series without seasonality and the graph of the resulting rolling mean array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*-8Us4wgzJIV4DiPFSExAvw.png" /><figcaption>Moving average and seasonally neutral time series</figcaption></figure><p>Since the data is not seasonal, the rolling mean values ​​themselves are average values, as I said above. What happens if we add seasonality to the average values? Yes, we get a reconstructed time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*AbkAFlbEkcwXJbvkHyZthw.png" /><figcaption>Reconstructed row</figcaption></figure><p>Well, the result is quite impressive, let’s take a look at the accuracy.</p><p>The accuracy of 97% is impressive, so why can’t we use this method in real projects? This time series has a <strong>low dimensionality</strong>, which is why the “naive” reconstruction worked, and remember how much work had to be done to get the result. For data with higher dimensionality, it would be necessary to find the average value over all variables, and the subtraction operation in multidimensional matrices would quickly be overtaken by the curse of multidimensionality. In addition, processing such a time series would require much more resources.</p><p>In the cells below you can find the decomposition of the time series using libraries<strong>scipy.signal та fracdiff. </strong>These libraries do not have inverse functions, so I will not use them, but they are very useful for more complex series.</p><h4><strong>Decomposition using logarithms</strong></h4><p>Logarithmization is a popular technique for working with time series. Let’s do it and see the result. It is important to use np.log1p instead of the usual np.log to prevent zeros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*NalwQ8_tlodIjKwlW0c-Nw.png" /><figcaption>Logarithmic time series</figcaption></figure><p>The logarithmic time series differs from the original only in scale. Such a series will not be stationary, since it still has a trend. We use the rolling mean algorithm again to transform the series into a stationary one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*b33hZFGKNH-8i_fNz1t5AQ.png" /><figcaption>Logarithmic series without trend</figcaption></figure><p>Now the series is stationary with a value of p = 0.02.</p><p>The second way to transform a logarithmic time series into a stationary one is to subtract the previous month’s value from the current month. This method is less precise and results in a p-value of 0.07, which exceeds the limit, but for the sake of interest I will also make a forecast on this time series.</p><h4><strong>Forecasting using ARIMA</strong></h4><p>ARIMA is one of the veteran time series models. Its forecasting quality is often inferior to more powerful models, but it is worth knowing about its existence.</p><p>The model consists of three parts: autoregressive (AR), integrated (I) and moving average (MA). Each of these parts has a hyperparameter that needs to be found: <strong>p,d,q</strong>. There are two ways to find p,q, d, most often from 1 to 4:</p><ol><li>Using autocorrelation (acf) and partial correlation (pacf) graphs. On the example of a stationary logarithmic series without a trend datasetLogScaleMinusMovingAverage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*XDQOWzM9mCajhXik5WhbkA.png" /><figcaption>ACF PACF</figcaption></figure><p>To find the value of p on the pacf graph, you need to find the point on the x-axis where y=0 for the first time: p=2.<br>Similarly, q is found from the acf graph: q=3.</p><p>2. Using arma_order_select_ic — auto-selection function. This method is more accurate because it gives exact values, unlike the first method, where the values ​​can only be found by eye. The function for finding parameters is in cell 17. And its result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*BvFtcAoGFNDreqAHqDepIg.png" /><figcaption>p and q selected by arma_order_select_ic</figcaption></figure><p>In ARIMA, I did not use the exact values ​​I found, but instead they served as a starting point.</p><p>The error function for ARIMA is RSS: the smaller the value, the better the model. For example, I will take the previous logarithmic series datasetLogScaleMinusMovingAverage, from which the moving average was subtracted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*pQEsobh6q18Od9beY0rE-g.png" /><figcaption>RSS for datasetLogScaleMinusMovingAverage</figcaption></figure><p>After the model has trained on the data and produced a forecast based on the last 2 years of the series, the result needs to be reconstructed into a time series with seasonality and trend. datasetLogScaleMinusMovingAverage is a logarithmic time series from which the moving average has been subtracted. The simplest way to reconstruct is to add the moving average to the logarithmic series and exponentiate the result to get the reconstructed time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*WZQpW5Uectc9TJH3w29Eyg.png" /><figcaption>Reconstructed from forecast time series and original</figcaption></figure><p>Accuracy: 93.25%, which is pretty good.</p><p>This method of reconstruction is more suitable for a deeper understanding of working with time series than for use in real projects.</p><h4><strong>SSA (Singular -Spectrum Analysis)</strong></h4><p>It sounds more interesting than scary, believe me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*2ahArnDQBTww2j782FsO-w.png" /></figure><p>It sounds more interesting than scary, believe me.</p><p>SSA is one of those methods that for some reason no one talks about, despite its high efficiency. The essence of the method is simple — to do all the same steps that I did before, but much faster and using more complex mathematics. It can be divided into 3 parts: time series decomposition, reconstruction and forecasting. The method is quite simple to understand, but uses quite complex methods, such as SVD, so I will leave<a href="https://ssa.cf.ac.uk/ssa2010/a_brief_introduction_to_ssa.pdf">theory</a>for your own consideration. In short: transform the time series into a multidimensional Henkel matrix, then, using SVD, divide the resulting matrix into signals, select the most “influential” signals from the resulting signals and reconstruct the matrix using them, and predict future values ​​based on the reconstructed matrix.</p><p>SSA implemented in the repository <a href="https://github.com/aj-cloete/pssa">Stop</a>, which I will use.</p><p>After the matrix obtained from the time series is decomposed via <strong>ssa.decompose(verbose=True)</strong> into signals, let’s take a closer look at them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*RQxtCmrNxkaSIse2FRZpfg.png" /><figcaption>Time series signals</figcaption></figure><p>The first 5 signals have the greatest impact on the series, and I will use them to begin with for reconstruction and forecasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*P3aGVXli9xc6frSy131e8A.png" /><figcaption>Original and reconstructed row</figcaption></figure><p>The reconstruction is quite accurate, let’s see how SSA predicts the values. To do this, I will use ssa.forecast_recurrent with return_df=True to return a dataframe and calculate the prediction accuracy.</p><pre>ssa_forecast_5=ssa.forecast_recurrent(steps_ahead=48, singular_values=streams5, plot=True,return_df=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*HNVXzexGqyvY_2402DA8EA.png" /><figcaption>Forecasting and original series</figcaption></figure><p>At first you might think that the prediction is only marked in blue and starts from 1961, but in fact the prediction starts from 1949, meaning the graphs of the original time series and the predicted one match perfectly. The accuracy is an impressive 100%, which is anyway not good to the <a href="https://medium.com/@ravikumar46931/why-human-level-performance-is-crucial-for-evaluating-deep-learning-models-in-computer-vision-aea3c07ba00a">theorem of human level error</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*XelVQDV5fJxCbZNI2C4aRw.png" /><figcaption>Precision</figcaption></figure><p>If we reconstruct and predict the series based on 10 signals instead of 5, the accuracy will not change. Let’s look at the forecasting for 10 years ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*JhyKSVwvC-JOyWd4Q2GMDg.png" /><figcaption>10-year forecast</figcaption></figure><p>As predicted in the previous part, the variance will increase. This prediction is even partially true, because the air travel “boom” began in the 1970s.</p><h4><strong>Exponential Smoothing</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*xNOoKtZb9yA9Ou1Sa3jNNQ.png" /></figure><p>For the time series used, Prophet’s accuracy is 0.03 higher</p><p>Exponential smoothing is a time series forecasting method for one-dimensional data.</p><p>Forecasts generated using exponential smoothing methods are weighted averages of past observations, with weights decreasing exponentially the further the observation is from the starting date. In other words, the later the observation, the higher the corresponding weight.</p><p>Exponential smoothing is similar to ARIMA, but in addition to the weighted sum of past observations, it also uses exponentially decreasing weights of past observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*S1vibqn_l8Zc4WpV2TqiNw.gif" /><figcaption><a href="https://medium.com/@jodancker/a-brief-introduction-to-time-series-smoothing-4f7ed61f78e1">GIF author</a></figcaption></figure><p>I will use the already implemented model from statsmodels.tsa.holtwinters. There are three types of exponential smoothing models: simple, double and triple. The simple model can only work with stationary time series, the double model works with a series with a trend but without seasonality, and the third works with a completely non-stationary series. It is the last model that I will use.</p><pre>from statsmodels.tsa.holtwinters import ExponentialSmoothing<br># prepare data<br>data = pd.read_csv(&#39;/kaggle/input/air-passengers/AirPassengers.csv&#39;)<br>data[&#39;Month&#39;] = pd.to_datetime(data[&#39;Month&#39;])<br>split=120<br>train_exp=data[:split]<br>val_exp=data[split:]<br><br># create class<br>model_exp_sm = ExponentialSmoothing(train_exp[&#39;#Passengers&#39;], seasonal_periods=12,<br>    trend=&quot;add&quot;,<br>    seasonal=&quot;add&quot;,<br>    initialization_method=&quot;estimated&quot;).fit()<br><br># make prediction for 4 years: 2 years for val set and another 2 years for forecasting<br>y = pd.DataFrame(model_exp_sm.forecast(48), columns=[&quot;pred&quot;])</pre><p>First, I split the dataset into training and validation. Note that in data the indices are numbers, not dates, unlike the dataframe that I use for all other models. Next, I create a class, the trend is linear, and the seasonality repeats exactly every year, so I give them the value “add”, if the trend is exponential it will be “mul”. For forecasting and testing on the validation set, I create a common dataframe: the first two years for testing, the other two years for forecasting future values.</p><p>You can view the model parameters in the following way:</p><pre>model_exp_sm.model.params</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*xJvlIWsLotodAg5oHKBKSA.png" /><figcaption>Forecasting visualization</figcaption></figure><p>The accuracy on the validation set is 93.36% which can be really true good results with acumulated noises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*0hrmjduIA_fOmZQYnFdFrg.png" /><figcaption>Precision</figcaption></figure><h4><strong>Forecasting via FFT</strong></h4><p>Personally I really love FFT and think that in modern tech world its very underhyped.</p><p>The Fourier transform is a transformation of a complex variable into another with specific parameters. Such transforms are most often used for working with signals, but they can also be used for decomposition and forecasting of time series. Discrete Fourier transforms are used for working with time series, since the values ​​of the time series are measured in a specific interval.</p><p>The Fourier transform involves many methods of mathematical analysis, so if you are interested in learning more, I suggest you check out this <a href="https://towardsdatascience.com/the-fourier-transform-1-ca31adbfb9ef">article</a><strong>.</strong></p><p>Numpy has an optimized implementation of the Fast Fourier Transform (FFT). I found a ready-made implementation and got the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*jQdrEpok0J4AY12-PuSj6A.png" /><figcaption>Predicted and original series</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*iI41DJMXY6P1ax9PcaeCEQ.png" /><figcaption>Precision</figcaption></figure><p>The forecasts for the existing series are quite accurate, but the forecast of future values ​​does not have the necessary seasonality.</p><h4><strong>GRU</strong></h4><p>GRU and its generic models show speed, precision and stability.</p><p>For all subsequent models, I will use the original non-stationary dataset. Traditionally, LSTM is considered to be more accurate than GRU, but for this time series, GRU showed the best results. In this section, I will talk about data preparation, model tuning, and forecasting future values.</p><ol><li><strong>Preparing the time series</strong>. The neural network is fed two types of data: variables (x) and target value (y), since the original time series has only one variable, the number of passengers, it needs to be converted into a dataframe that can be divided into x and y. To do this, I create a matrix with the original variable and lags for 3 months:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*c3dsEKB7F4ZQ2grB2ZlFDw.png" /><figcaption>Formed matrix</figcaption></figure><p>Target -3: the value of the variable 3 months ago, Target -2: two months ago, and Target -1: one month ago. Thus, a matrix was formed where the first 4 columns are x and the last column is y. Due to such manipulations, the time series lost the first three months.</p><p>2. <strong>Normalization</strong>. To speed up training and get better results, the resulting matrix needs to be normalized. MinMaxScaler() is the only normalizer option, since the distribution of the time series is not normal. An important nuance in normalization is the order in which it is performed: the fit_transform method is called on the training set, transform is called on the test and validation sets. First, I will divide the matrix into train, test, and validation sets. The def scaling(df,train) function normalizes each set separately, the bool variable train determines whether the set is training (train=True) or not. An interesting feature is that if you divide the data by full seasonality cycles, that is, by years, the accuracy will increase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*uVZ1Zv0egQBa1NqYaHERmg.png" /></figure><p>This method of dividing into train/test/val gives less accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*vjXHmVg--IBg9_Tk-E67eQ.png" /></figure><p>And this one is bigger.</p><h4>Tuning</h4><p>Tuning is a way to find a model with the highest accuracy as quickly as possible. As with most machine learning methods, there is an important detail here: a good model can only be obtained if the hyperparameters are correctly selected and ranked. As a tuner, I use keras-tuner and the MyHyperModel(HyperModel) class to create the model. You can also search for hyperparameters using older optimizers, such as Random Search, but it is better to use Hyperband, which is faster and more qualitative. I keep the best model.</p><pre>best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]</pre><h4>Training</h4><p>Next, the resulting model should be trained on the prepared data. To avoid overtraining, I used<strong><em> EarlyStopping()</em></strong> and <strong><em>ModelCheckpoint()</em></strong> to save the best weights. Do this via <strong><em>restore_best_weight = True EarlyStopping()</em></strong> <a href="https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">not always a good idea</a> because the weights will only be saved if <strong><em>EarlyStopping()</em></strong> stopped due to the limit set in patience, not when it reached the last epoch, which happens quite often.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*ZuU4FD7UddjRp9QYar1yPA.png" /><figcaption>A visual example</figcaption></figure><p>After successful training, I load the best weights into the model</p><pre>#load best weights to the model<br>model.load_weights(&quot;/kaggle/working/checkpoint.model.h5&quot;)</pre><p>A slight overfitting can be seen in the loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*sGm9LZ6ioer1PVGEk7paRA.png" /><figcaption>Loss function</figcaption></figure><p>To test the accuracy of the model on validation data, we need to predict values ​​via model.predict() and denormalize the data again via scaler.inverse_transform(). The model accuracy is 90%, which is not very impressive for such a powerful model and such light data.</p><h4><strong>Forecasting future values</strong></h4><p>First, I create an array containing every month from 1961 to 1962.</p><pre>first_year=pd.date_range(&quot;1961-01-01&quot;,&quot;1961-12-01&quot;, freq=&#39;MS&#39;)</pre><p>Next, you need to create 3 monthly lags. Since the validation set is one year shorter than the dates for which I will predict values, you can take the lags from the validation set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*WCh4ze3nFhk54VptQRrGkw.png" /><figcaption>Lags from the validation set to predict future values</figcaption></figure><p>Next, similar to the validation set, values ​​are predicted via model.predict() and returned to the unnormalized state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*89BRjJTzdZks88phS00R2g.png" /><figcaption>Forecasting for next year</figcaption></figure><h4>XGBoost Regressor</h4><p>This is another model that is often encountered in time series forecasting tasks. Data preparation for this model is even simpler, as it is based on Random Forest, which does not require data normalization. All that needs to be done with the data is to create a matrix similar to the one used for GRU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*SAFSIFagsUml-UJYOij76A.png" /><figcaption>The formed matrix</figcaption></figure><p>Added an additional fourth lag and divided the date into month, quarter, and year.</p><h4>Tuning</h4><p>For tuning I use HyperOpt, the peculiarity of this tuner is that it saves all the training results, including the best model in Trials(). I save the best model and prepare the data for training.</p><pre>def getBestModelfromTrials(trials):<br>    valid_trial_list = [trial for trial in trials<br>                            if STATUS_OK == trial[&#39;result&#39;][&#39;status&#39;]]<br>    losses = [ float(trial[&#39;result&#39;][&#39;loss&#39;]) for trial in valid_trial_list]<br>    index_having_minumum_loss = np.argmin(losses)<br>    best_trial_obj = valid_trial_list[index_having_minumum_loss]<br>    return best_trial_obj[&#39;result&#39;][&#39;Trained_Model&#39;]</pre><p><strong>Preparing data for training</strong></p><p>Before splitting the data into a test and training set, I created a validation set with df_w_lags, since cross-validation only creates a test and training set. Cross-validation is often used with XGBoost, which splits the data into test and training sets as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*0Qt7XYWtv4jxtlRFdSZs0A.png" /><figcaption>Data separation by cross-validation</figcaption></figure><p>Blue indicates test data, orange indicates test data. This algorithm allows for better data processing, as the training and test sets are changed.</p><p>Why not use the data separated by cross-validation for tuning? The speed of tuning directly depends on the amount of data and the size of the search field, i.e. cross-validation would only slow down tuning.</p><p><strong>Training</strong></p><p>The<strong> cross_val_fit </strong>function returns the model quality for each validation split and the model itself. The loss function was chosen as MAE to reduce the value of large errors.</p><pre>xgb_reg,scores=cross_val_fit(xgb_reg_tun,df_w_lags)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*qCUFlUNJSsmWoS5k5Vl5kQ.png" /><figcaption>Loss function</figcaption></figure><p>From the graph, you can see that the model is a bit overtrained, training could have been stopped after epoch 90. You can also see which variable had the biggest impact on the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*hkAU8FKnbBmy86_NdaLPxg.png" /><figcaption>The impact of each variable on the model</figcaption></figure><p>In this case, it’s a 1-month lag.</p><p><strong>Forecasting future values</strong></p><p>Similar to predicting future values ​​for GRU, I create a matrix of previous years’ lags for forecasting using concatenation. The pred column contains the forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*jd4xbzvwPTIxyAfuqYVvhA.png" /><figcaption>Matrix of predicted values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ZTvEuykkML5MFaqyFtgvJA.png" /><figcaption>Future forecasting</figcaption></figure><p>XGBoost also captures the overall seasonality, but the peak value is reached in September, not August.</p><h4><strong>Prophet</strong></h4><p>The latest and easiest model to create. Prophet was created by a team of scientists from Facebook, the main feature is that Prophet decomposes the model during training, unlike other models.</p><p>For training, data should only be received in the following form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*b2pPd5huWI_L3f2hffrU_w.png" /><figcaption>Matrix for Prophet</figcaption></figure><p>And so, that’s all the training needed for this model. Next, I split the resulting dataframe into a training and validation (last year) dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*aQ3IEdJxXFa5-hJkNKh_og.png" /><figcaption>Forecasting</figcaption></figure><p>The series reaches its peak value in the 7th month, July, instead of August.</p><p>Accuracy is the highest among all models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*tNRY4N93eYmqFtJNlIKhwQ.png" /><figcaption>Precision</figcaption></figure><h3><strong>Human Error vs Bayes (Perfect ) Error</strong></h3><p>Accuracy and error metrics are a great way to understand the true quality of a model, but what if after optimization the quality has improved a little and is still less than the desired 100%?</p><p>Should an ideal model have 100% accuracy? In Machine Learning, there are two types of errors to understand this. The first error is “Human Error”. It represents the accuracy of human conclusions on the same data on which the model is trained. Of course, no one will recruit a focus group to find an indicator of this estimate, but this is not necessary, the estimate can be predicted approximately. I could not find the exact percentage by which financiers and mathematicians can be mistaken when predicting a time series, but let’s assume that the error is 8%. To find it, make the following table (I also assumed these values). Imagine 3–4 groups of people with different knowledge in the field to which the data belongs. Depending on the use case (how the model will be used), the lowest error can be the “ideal” error, the human error is the average error or the average between the average error and the largest. If high accuracy of the model is a critical indicator, for example, the model recognizes cancer tumors, then the “ideal” error should be higher than the smallest error from the table, the human error should be higher than the average error from the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*hBJ9W951QUyTmR4kFTbO6Q.png" /><figcaption>Different errors different meanings</figcaption></figure><p>The model loss function, after passing through the value of human error, “falls” onto a plateau where it cannot find a minimum, and accordingly the quality of the model remains constant. A model is considered good if its <strong><em>accuracy above human error</em></strong>.</p><p>The second type of error is “Bayes Error” or “ideal/unattainable error”. This is the error that a model can theoretically achieve with an ideal data distribution, hyperparameter tuning, etc. The model’s loss function will always be lower and will never exceed the ideal error limit.</p><p>Intuitively, this can be explained as follows: a person can predict which side a coin will land on (probability theory), but if hundreds of coins are being flipped, predicting becomes much more difficult.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*ZK7dFZHrNeDbp4G6dCrtGA.png" /><figcaption><a href="https://bardhrushiti.medium.com/human-level-performance-and-bayesian-optimal-error-fadf4f55cd48">Visualization of error types</a></figcaption></figure><h3><strong>Comparison of the accuracy of all methods</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*-OBq8F2ElK19Ut0hGJtofA.png" /></figure><p>The loss functions of almost all models lie between the horizontal axes of human and ideal error.</p><p>It can be said that SSA has the highest accuracy, but this accuracy is for small data with one variable. The last three models show the highest quality for more complex data.</p><h3><strong>Epilogue</strong></h3><p>Thanks for reading, I hope it was useful and interesting!</p><p><strong>Sources used</strong></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.kdnuggets.com/2023/08/leveraging-xgboost-timeseries-forecasting.html</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.datadriveninvestor.com/mastering-advanced-time-series-techniques-7b1080cef853</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.linkedin.com/pulse/how-use-machine-learning-time-series-forecasting-vegard-flovik-phd-1f?utm_source=share&amp;utm_medium=member_ios&amp;utm_campaign=share_via</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.databricks.com/blog/2021/04/15/how-not-to-tune-your-model-with-hyperopt.html</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.linkedin.com/advice/0/what-difference-between-mean-squared-error-tz1mc</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/@rithpansanga/optimizing-xgboost-a-guide-to-hyperparameter-tuning-77b6e48e289d</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/kaggle-blog/chucking-everything-into-a-random-forest-ben-hamner-on-winning-the-air-quality-prediction-788be7620e69</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://hyperopt.github.io/hyperopt/getting-started/search_spaces/</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.machinelearningplus.com/time-series/augmented-dickey-fuller-test/</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/stationarity-in-time-series-a-comprehensive-guide-8beabe20d68</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/seasonality-of-time-series-5b45b4809acd</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/analytics-vidhya/singular-spectrum-analysis-kernel-pca-for-time-series-regression-64679c155c80</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/the-fourier-transform-1-ca31adbfb9ef</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">Differencing Time Series In Python With Pandas, Numpy, and Polars | Forecastegy</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">When working with time series data, differencing is a common technique used to make the data stationary.Stationary data</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">forecastegy.com</a></p><p><a href="https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31789eaab67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Аналіз та прогнозування часових рядів]]></title>
            <link>https://medium.com/@mirandorexes/%D0%B0%D0%BD%D0%B0%D0%BB%D1%96%D0%B7-%D1%82%D0%B0-%D0%BF%D1%80%D0%BE%D0%B3%D0%BD%D0%BE%D0%B7%D1%83%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F-%D1%87%D0%B0%D1%81%D0%BE%D0%B2%D0%B8%D1%85-%D1%80%D1%8F%D0%B4%D1%96%D0%B2-74c27293e7b9?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c27293e7b9</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:55:57 GMT</pubDate>
            <atom:updated>2025-09-14T17:55:57.242Z</atom:updated>
            <content:encoded><![CDATA[<p>Більшість туторіалів по даній темі містять дуже мало теорії, або не містять її взагалі та використовують 1–2 найпопулярніші моделі. Ця стаття присвячена теорії, простим та більш складним методам аналізу та прогнозування часових рядів. Я розділила матеріал на умовні три частини — легку, середню та складну, бо ключ до розуміння — це починати з основ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLZ4cNOCl-MljwFOZJLZSg.jpeg" /></figure><h3>Введення до часових рядів</h3><p>Що таке часовий ряд? Це зміна кількості корму, який їсть ваша кішка або собака, від часу. Це коливання ціни акцій корпорацій, показання температури на весь день, зміна смаку чаю з часом. Як зрозуміти та правильно обробити часовий ряд?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*gCOGX_5dkWyf8lqu.jpeg" /></figure><p>Основна відмінність між часовим рядом і окремими експериментами, які можна зобразити за допомогою гістограми в тому, що кожна точка (змінна) у часовому ряді віддалена від наступної точки на однакову відстань та може залежати від попередньої (автокореляція).</p><h3>Що можна зробити з часовим рядом та чому він такий корисний?</h3><p>Часовий ряд дає можливість передбачити значення наступної (майбутньої) точки (змінної), наприклад, передбачити ціну акції через годину, день, тиждень, базуючись на розмірності даних. Але регресія робить теж саме, хіба ні? Саме в цьому аспекті і лежить основна відмінність. Результатом регресії є кількісна оцінка впливу незалежних змінних на процеc, тоді як часовий ряд можна відтворити шляхом розкладання, не розраховуючи вплив кожної змінної, тобто не “заглядаючи під капот”. Ряд складається з двох частин — сигналу та шуму. Сигнал — це математично залежні змінні, які можна проаналізувати та прибрати з часового ряду. Шум навпаки складається з рандомних значень, частіше за все нормального розподілу, та візуально схожий на звуковий шум.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*ioMXLf6WdgK0gEjK.jpeg" /></figure><p>Реальні дані є поєднанням шуму та сигналу і найчастіше за все низька якість моделі залежить саме від неможливості відтворити (передбачити) шум.</p><p>Патерни сигналу:</p><ol><li>Сезонність (seasonality) — циклічні коливання змінної в залежності від часу. Наприклад, зниження температури взимку.</li><li>Тренд (trend/level) — це наклон ряду до горизонтальної осі. Тренд може бути зростаючим або спадаючим, якщо тренд не змінюється, то часовий ряд розташований горизонтально.</li><li>Автокореляція — це “пам’ять” ряду, значення змінної в конкретний час напряму залежить від попередніх значень змінної .</li></ol><p>Якщо ряд не містить патерни, його називають стаціонарним. Стаціонарним (Stationary) є ряд без тренду та сезонності, середнє та стандартне відхилення якого є константами. Окремим патерном є часові ряди, які не можна зробити стаціонарними, прибравши тренд та/або сезонність. Такі ряди називають difference — stationary.</p><p>У<a href="https://www.youtube.com/watch?v=Prpu_U5tKkE&amp;t=276s"> цьому відео</a> більш детально можна послухати про часові ряди.</p><p>Навчання якісної моделі для моделювання та прогнозування часового ряду це довгий та кропіткий процес. Алгоритм підготовки ряду залежить від вибору моделі, датасету та може містити базову очистку даних (нормалізацію), feature extraction та алгоритми приведення ряду до стаціонарного. У наступних пунктах я детально розповім про підготовку ряду для різних алгоритмів. Для деяких моделей високу якість можна досягти і без очистки часового ряду, для інших треба робити всі перелічені вище методи очистки.</p><h3>Датасет та передмова</h3><p>Стаття вийшла більша за розмірами, ніж очікувала, тому весь код можна знайти у <a href="https://www.kaggle.com/code/annack/tsa-and-forecasting-from-a-to-z-tutorial">цьому ноутбуці</a>, містить коментарі англійською, але планую перекласти на українську. Як навчальні дані буду використовувати цей <a href="https://www.kaggle.com/datasets/rakannimer/air-passengers">датасет</a>, який виглядає наступним чином:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*qBEoH9N_sZBZcXoN.jpeg" /></figure><p>Датасет показує кількість пасажирів впродовж 1949–1960 років, щомісяця.</p><h3>Аналіз часового ряду</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q1J4JIHfzBlkwC70.jpeg" /></figure><p>Почну з тих методів, які використовуються для аналізу багатьох видів даних.</p><h3>Визначення розподілу</h3><p>Для визначення розподілу використовують гістограму, Dataframe має вбудований метод hist().</p><pre>df.hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*A38bOnEPx-g8PPdS.jpeg" /></figure><p>Часовий ряд має розподіл, відмінний від нормально, що звужує коло методів, які можна використати для нормалізації даних до одного, а саме до MinMaxScaler. З математичної точки зору такий розподіл сигналізує про те, що часовий ряд, скоріш за все, не є стаціонарним.</p><h3>Викиди (Outliers)</h3><p>Викиди — це дані, які “виділяються” з загальної купи, можуть бути або дуже маленькими, або дуже великими, порівняно з найближчою точкою. Вони впливають на якість більшості моделей машинного навчання та на вибір функції втрат.</p><p>Найпростіший спосіб, але не завжди дієвий, перевірити, чи є викиди — це подивитися на гістограму. Наприклад, якщо б стовпчик між 500 та 600 не містив даних (був би білим), можна було б припустити, що стовпчик 600 це викиди. Більш дієвий візуальний спосіб — це використати sns.boxplot:</p><pre>sns.boxplot(df.Passengers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*MBqaevfwh5Rtzx4u.jpeg" /></figure><p>Вигляд boxplot підтверджує, що дані не мають викидів — вертикальна ось не містить чорних точок, які позначають викиди.</p><h3>Перевірка на NAN</h3><p>NAN — це неідентифікований тип даних, який не відображається на boxplot та забруднює дані. Значення такого типу потрібно видаляти, оскільки більшість алгоритмів машинного навчання не вміють працювати з ними. Разом з кількістю NAN значень виведу статистичні дані.</p><pre>print(df.describe())<br>print(&quot;NAN values:&quot;,df.isna().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*kYFo_iM7HygTTquY.jpeg" /></figure><p>Що ж, прекрасно! Ряд не має NAN значень — однією проблемою менше.</p><h3>Сезонність, тренд та шум</h3><p>Подивіться на ілюстрацію знизу, як швидко ви знайдете тренд та сезонність? Я впевнена, що за пару секунд.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*lE8XeGJFQEj4RKJw.jpeg" /></figure><p>Стаціонарний часовий ряд легше передбачити, оскільки тренд є константою, на відміну від нестаціонарного часового ряду, чий тренд може змінити подія (наприклад, акції Твіттера впали через висловлювання Ілона Маска), передбачити яку дуже складно.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VpdYDVJhCMFa0zWB.jpeg" /></figure><p>Розуміння тренду, сезонності та шуму є ключовим для розуміння часового ряду. Найпростішим способом знайти їх є statsmodels.tsa.seasonal.</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose<br>decomposed = seasonal_decompose(df[&#39;Passengers&#39;]) <br>decomposed.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*YKJDA-Skd8pEm3ea.jpeg" /></figure><p>Тренд є майже лінійним та зростаючим. Це добре, бо лінійний тренд простіше передбачити, ніж нелінійний. Сезонність є однаковою та повторюється кожного року. Шум (resid) — це часовий ряд після прибирання з нього тренду та сезонності. Для цього часового ряду від доволі сильний, що може знизити якість прогнозування . Розглянемо сезонність на прикладі одного року.</p><pre>df_month=df.copy()<br>df_month[&quot;Month&quot;]=[d.strftime(&#39;%b&#39;) for d in df_month.index]<br>plt.figure(figsize=(20,10))<br>sns.boxplot(x=df_month[&quot;Month&quot;],y=df_month[&quot;Passengers&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*oVGW7i_PSM3bgJET.jpeg" /></figure><p>Кількість пасажирів збільшується впродовж двох літніх місяців та спадає після серпня. Одна з причин — люди летять на відпочинок влітку.</p><p>Наступні перевірки роблять тільки для часових рядів.</p><h3>Доповнений тест Дікі — Фуллера (ADF)</h3><p>Тест ADF — це тест для перевірки стаціонарності часового ряду на основі <a href="https://medium.com/codex/unit-root-in-time-series-38d451d742ce">unit root </a>— це процес, який через диференціювання визначає чи є часовий ряд стаціонарним. Тест працює за принципом приймання або відкидання нульової гіпотези, яка полягає у тому, що ряд не є стаціонарним. Приймати чи відкидати нульову гіпотезу вирішується за значенням p (вірогідність неправильності нульової гіпотези): якщо значення є більшим за визначену константу, то нульова гіпотеза приймається (ряд не є стаціонарним), якщо меншим — гіпотеза відкидається (ряд є стаціонарним). Традиційно, константа = 0.05 (5%), але може бути іншою, в залежності від даних та моделі. Також важливо дивитися і на значення статистики, якщо воно більше за будь-яке критичне значення, то часовий ряд не є стаціонарним.</p><p>Реалізація наведеної нижче функції у 13 ячейці.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*rAUgVwOf0pO0gCIZ.jpeg" /></figure><p>Rolling mean — це середнє значення точок часового ряду, і так, воно повторює лінію тренду. Rolling std — це значення дисперсії точок ряду. Простими словами — чим більша дисперсія, тим більше “розпилення даних”. Чим менші “хвилі” (див. на 1950 рік) — тим менше дисперсія, чим більші хвилі — тим більша дисперсія (див. на 1960 рік). Одразу можна припустити, що з роками дисперсія буде ставати все більше.</p><p>І останній пункт</p><h3>Автокореляція</h3><p>Кореляція — це зв’язок змінних між собою, автокореляція — зв’язок змінної з власними попередніми значенням. Оскільки ряд має тільки одну змінну — кількість пасажирів, аналізувати потрібно тільки автокореляцію. Перед тим, як графік автокореляції розкриється у всій красі, розкажу про поняття lags (лаги) — це значення змінної n — кількість часу назад, оскільки розмірністю мого часового ряду є місяць, то lag -1 означає значення 1 місяць тому для поточної змінної, -2 — два місяці тому, тощо. На наведеному нижче графіку кількість лагів дорівнює 4.</p><pre>from statsmodels.graphics.tsaplots import plot_acf<br>plot_acf(df,lags=4)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*txqcWP-MOgiU-4pa.jpeg" /></figure><p>1 стовпчик (0) — це автокореляція значення з самим собою та завжди буде дорівнювати 1, 2 стовпчик (1) — це автокореляція поточного значення зі значенням місяць назад, тощо. Блакитний конус — це 95% інтервал, тобто все за межами конусу є скоріш за все кореляцією, а не статистичною помилкою. Часовий ряд має сильну кореляцію, що може призвести до збільшення bias. Якщо модель має high bias — це недонавчена модель, якщо модель має high variance — це перенавчена модель.</p><p>Все, зі статистикою покінчено, переходимо до простих методів декомпозиції часового ряду, щоб зробити ряд стаціонарним.</p><h3>Декомпозиція часового ряду</h3><p>Декомпозиція — це процес перетворення нестаціонарного часового ряду у стаціонарний шляхом прибирання з нього сезонності та тренду. Одразу зазначу, декомпозицію потрібно робити тільки для деяких моделей, наприклад регресійних, таких як ARIMA/SARIMA, моделі як LSTM/GRU, XGBoost, Prophet настільки потужні, що обробляють нестаціонарний ряд. Існують бібліотеки, які можуть декомпозувати ряд в одну строку, але не мають зворотньої функції для реконструкції. Реконструкція часового ряду — це процес зворотнього додавання до ряду тренду та сезонності, якщо цього не зробити, ряд буде паралельним осі х та буде мало корисним як прогнозування.</p><ol><li>Deseasonality (моделювання сезонності)</li><li>Для того, щоб прибрати сезонність, найчастіше використовують різницю (differencing) між конкретним значенням змінної (Y) у конкретний час (t) за наступною формулою:</li><li>Yt = Yt — Yt-n, <em>n </em>— це показник сезонності. Наприклад, якщо сезонність є кожного року, то <em>n</em> = 12, 12 місяців — 1 рік, тощо</li></ol><p>Функція def deseasonality(df,seasonality) віднімає від кожного значення у датафреймі значення, що було рік тому та повертає датафрейм[сезонність:], таким чином втрачається перший рік. Зворотньої до неї є def add_seasonality(df,diff,seasonality), яка додає сезонність з оригінального датафрейму та додає отриману сезонність до датафрейму без сезонності. Цю функцію буду використовувати для реконструкції ряду.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*h3n6A_hnZjWkJPpd.jpeg" /></figure><p>Після видалення сезонності часовий ряд вже є стаціонарним, скоріш за все через лінійний тренд, але для більш точного прогнозування я приберу ще й тренд.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*7gdFO-cW5utui-dU.jpeg" /></figure><ol><li>Detrending</li></ol><p>Тренд є середнім значенням (rolling mean) часового ряду, тому для детрендінгу потрібно відняти середнє значення від ряду, який отримала у попередньому пункті. Найпростіший спосіб зробити це алгоритм rolling mean. Я зробила дві варіації, але покажу тільки першу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*0Yn37JgoA0cbfywL.jpeg" /></figure><p>Можна побачити, що середнє значення ряду стало близько нуля.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*bin9fsl0JDeCQfXn.jpeg" /></figure><h3>Функції втрати</h3><p>Показниками якості моделей та прогнозування для часових рядів є функції втрати та метрики похибки. Найчастіше використовують такі функції втрати як MAE (L1 norm) — “Mean Square Error”, MSE(L2 norm) — “Mean Absolute Error”.</p><p>MAE надає кожній помилці однакову “вагу”, тобто є робастною до викидів та шуму функцією, але одночасно з цим занижує “вплив” великих помилок.</p><p>MSE в свою чергу навпаки, дає більшим помилкам більшу вагу, що робить функцію більш чутливою до викидів. Якщо модель повинна бути чутлива до помилок, обирають саме цю функцію.</p><p>Я буду використовувати обидві функції як метрики та одну з них як функцію втрати (loss function). Що показує порівняння MAE та MSE? Для прикладу візьму наступні значення:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*Y3WzqS3n97UpeyuS.jpeg" /></figure><p>MSE у 1856 означає, що середнє значення помилки це квадрат помилки становить 1856, тобто 43.081² .MAE становить 33.44, тобто середнє значення помилки становить 33.44.</p><p>У цьому прикладі MSE більше за MAE у квадраті, що свідчить про наявність великих помилок, які збільшують MSE. Викиди, нелінійність або шум є причиною цьому, оскільки в цьому часовому ряді сильний шум, можна припустити, що він і є причиною. Якщо MSE менша за MAE у квадраті — модель має маленькі помилки, які і збільшують MAE . Причиною цьому є рандомність або неточність даних.</p><p>Точність часового ряду не можна знайти за стандартною функцією точності, тому для оцінки точності прогнозування та реконструкції використовую наступну метрику. MAPE є відносним значенням помилки, що можна використовувати як функцію точності за наступною формулою: 100-(MAPE*100). Функція для обчислення MAPE знаходиться у 16 комірці</p><h3>Наївне прогнозування (Naive Forecasting)</h3><p>Наївне прогнозування є найпростішим методом для прогнозування часового ряду, точність якого є високою тільки у разі константного (горизонтального) тренду.</p><p>Формула наївного прогнозування наступна: Yt = Yt-1: майбутнє значення часового ряду є його попереднім значенням. Так, не дуже вражаюче, але давайте все ж спробуємо. Розділяю оригінальний часовий ряд на тестову та тренувальну вибірку (останні два роки). Перше прогнозування для тестової вибірки є останнім значенням тренувальної.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/0*lyfMiGO7yszeLpxf.jpeg" /></figure><p>Оскільки 1 значення тестової вибірки є 317, то всі наступні значення дорівнюватимуть теж 317, в результаті чого отримуємо горизонтальну лінію. Перейдемо до більш точних методів.</p><h3>Реконструкція часового ряду з rolling mean</h3><p>Я не зустрічала подібного алгоритму, але він гарно ілюструє пластичність часового ряду та що з ним можна зробити. Спершу подивимося на графік часового ряду без сезонності та графік отриманого масиву rolling mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*-YjEr5-2-MGqDbbQ.jpeg" /></figure><p>Оскільки дані не мають сезонності, самі по собі значення rolling mean є середніми значеннями, як казала вище. А що буде, якщо додати до середніх значень сезонність? Так, вийде реконструйований часовий ряд.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*WEabcCxlt1QpKuF2.jpeg" /></figure><p>Що ж, результат доволі вражаючий, подивимося ще на точність.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*iDK3-LHW0WNBXOjs.jpeg" /></figure><p>Точність у 97% вражає, чому ж тоді не можна використовувати цей метод у реальних проєктах? Цей часовий ряд має має маленьку розмірність, саме через це “наївна” реконструкція спрацювала, також пригадайте, скільки всього потрібно було зробити, щоб отримати результат. Для даних з більшою розмірністю знадобилося б шукати середнє значення за всіма змінними, а операцію віднімання у багатовимірних матрицях швидко б наздогнало прокляття багатовимірності. До того ж, для обробки такого часового ряду знадобилося б набагато більше ресурсів.</p><p>У ячейках нижче можете знайти декомпозицію часового ряду за допомогою бібліотек <strong>scipy.signal та fracdiff. </strong>Ці бібліотеки не мають зворотніх функцій, тому використовувати їх не буду, але вони дуже корисні для більш складних рядів.</p><h3>Декомпозиція за допомогою логарифмування</h3><p>Логарифмування є популярною технікою для роботи з часовими рядами. Давайте його зробимо та подивимося на результат. Важливо використовувати np.log1p замість звичайної np.log для запобігання появі нулів.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*On3ok3w3EiV2oJeC.jpeg" /></figure><p>Логарифмований часовий ряд відрізняється від оригінального тільки в масштабах. Такий ряд не буде стаціонарним, оскільки в ньому залишається тренд. Використовуємо алгоритм rolling mean знову для перетворення ряду у стаціонарний.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*DPZKIoSEmEQc6L1y.jpeg" /></figure><p>Тепер ряд є стаціонарним зі значенням р = 0.02.</p><p>Другий спосіб для перетворення логарифмованого часового ряду у стаціонарний полягає у відніманні значення у попередньому місяці від поточного. Цей спосіб є менш точним та як результат значення р = 0.07, що перевищує межу, але задля інтересу на такому часовому ряді я теж зроблю прогнозування.</p><h3>Прогнозування за допомогою ARIMA</h3><p>ARIMA є однією з ветеранів моделей по роботі з часовими рядами. Якість прогнозування частіше уступає перед більш потужними моделями, але знати про її існування потрібно.</p><p>Модель складається з трьох частин авторегресійної (AR), інтегрованої(I) та Ковзної середньої (MA). Кожна з цих частин має гіперпараметр, який треба знайти: p,d,q. Є два способи знаходження p,q, d частіше за все від 1–4:</p><ol><li>За допомогою графіків автокореляція (acf) та часткової кореляції (pacf). На прикладі стаціонарного логарифмованого ряду без тренду datasetLogScaleMinusMovingAverage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*6qwoYd3i0Cl7cs7-.jpeg" /></figure><ol><li>Щоб знайти значення р на pacf графіку треба знайти точку на осі х, у якій у=0 перший раз: р=2.</li><li>Аналогічно, q знаходять за acf графіком: q=3.</li><li>За допомогою arma_order_select_ic — функції автопідбору. Цей спосіб є більш точним, оскільки дає точні значення, на відміну від першого способу, де значення можна знайти тільки на око. Функція для знаходження параметрів є у 17 ячейці. І її результатом є:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/0*gENHtulWTj2k4LsX.jpeg" /></figure><p>4. У ARIMА я не використовувала точні значення, які знайшла, натомість вони слугували відправною точкою.</p><p>Функцією помилки для ARIMА є RSS: чим значення менше, тим якісніша модель. Для прикладу візьму попередній логарифмований ряд datasetLogScaleMinusMovingAverage, від якого відняли ковзне середнє.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HbKycRrHfGoU6SEG.jpeg" /></figure><p>Після того, як модель навчилася на даних та дала прогнозування на основі 2х останніх років ряду, результат потрібно реконструювати у часовий ряд з сезонністю та трендом. datasetLogScaleMinusMovingAverage — це логарифмований часовий ряд, від якого відняли ковзне середнє. Найпростіший спосіб реконструкції — це додати ковзне середнє логарифмованого ряду та експонентувати результат, щоб отримати реконструйований часовий ряд.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tOugZ0nRp_x_u-fp.jpeg" /></figure><p>Точність: 93.25%, що доволі непогано.</p><p>Такий спосіб реконструкції підходить для більш глибшого розуміння роботи з часовими рядами, аніж для використання для реальних проєктів.</p><h3>SSA (Singular -Spectrum Analysis)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*YV5g5F58pAQS98mb.jpeg" /></figure><p>Це звучить цікаво, аніж страшно, повірте.</p><p>SSA — це один з тих методів, про які чомусь ніхто не говорить, попри їх високу ефективність. Суть метода проста — зробити всі ті ж самі кроки, що я зробила до цього, але набагато швидше та з застосуванням більш складної математики. Його можна розділити на 3 частини: декомпозиція часового ряду, реконструкція та прогнозування. Метод доволі простий для розуміння, але використовує доволі складні методи, як SVD, тому залишу <a href="https://ssa.cf.ac.uk/ssa2010/a_brief_introduction_to_ssa.pdf">теорію</a> для вашого власного розгляду. Коротко: перетворення часового ряду на багатовимірну матрицю Генкеля, далі, за допомогою SVD розділити отриману матрицю на сигнали, з отриманих сигналів обрати найбільш “впливові” та реконстроювати матрицю з їх допомогою, на основі реконструйованої матриці передбачити майбутні значення.</p><p>SSA реалізован у репозиторії <a href="https://github.com/aj-cloete/pssa">PySSA</a>, який і буду використовувати.</p><p>Після того, як матриця, отримана з часового ряду, декомпозована через ssa.decompose(verbose=True) на сигнали, подивимося ближче на них.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fIbpEL8isgBNNRVR.jpeg" /></figure><p>Перші 5 сигналів найбільше впливають на ряд, їх для початку і візьму для реконструкції та прогнозування.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hdFM204ZLoQ-u9at.jpeg" /></figure><p>Реконструкція доволі точна, подивимося, як SSA передбачить значення. Для цього використаю ssa.forecast_recurrent з return_df=True, щоб повернути датафрейм та розрахувати точність прогнозування.</p><pre>ssa_forecast_5=ssa.forecast_recurrent(steps_ahead=48, singular_values=streams5, plot=True,return_df=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WrN_Gha6KnybcR2o.jpeg" /></figure><p>Спочатку можна подумати, що прогнозування позначене тільки синім кольором та починається з 1961 року, але насправді прогнозування починається з 1949 року, тобто графіки оригінального часового ряду та передбачуваного абсолютно збігаються. Точність дорівнює вражаючим 100%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*4zqamQOs2X_6ftnu.jpeg" /></figure><p>Якщо реконструювати та передбачити ряд на основі 10 сигналів, замість 5, точність не зміниться. Подивимося прогнозування на 10 років вперед.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*PE2EcsRKYdH3fIYW.jpeg" /></figure><p>Як передбачала у попередній частині, дисперсія буде збільшуватися. Це прогнозування навіть частково відповідає дійсності, бо у 70х роках почався “бум” на авіаперельоти.</p><h3>Eкспоненціального згладжування (Exponential Smoothing)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*UTtpzyAZh1VIJwPe.jpeg" /></figure><p>Експоненціальне згладжування — це метод прогнозування часових рядів для одновимірних даних.</p><p>Прогнози, створені за допомогою методів експоненціального згладжування, є середньозваженими значеннями минулих спостережень, причому ваги зменшуються експоненціально, чим далі спостереження від початкової дати. Іншими словами, чим пізніше спостереження, тим вища відповідна вага.</p><p>Експонціальне згладжування схоже на ARIMA, але окрім зваженої суми минулих спостережень ще використовують експоненціально зменшувану вагу минулих спостережень.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*PIf5mUyfEGrRQYRq.gif" /></figure><p>Я буду використовувати вже реалізовану модель з statsmodels.tsa.holtwinters. Існують три вида моделі експоненціального згладжування: проста, подвійна та потрійна. Проста модель може працювати тільки зі стаціонарним часовим рядом, подвійна працює з рядом з трендом, але без сезонності, третя працює з повністю нестаціонарним рядом. Саме останню модель я і буду використовувати.</p><pre>from statsmodels.tsa.holtwinters import ExponentialSmoothing<br># prepare data<br>data = pd.read_csv(&#39;/kaggle/input/air-passengers/AirPassengers.csv&#39;)<br>data[&#39;Month&#39;] = pd.to_datetime(data[&#39;Month&#39;])<br>split=120<br>train_exp=data[:split]<br>val_exp=data[split:]</pre><pre># create class<br>model_exp_sm = ExponentialSmoothing(train_exp[&#39;#Passengers&#39;], seasonal_periods=12,<br>    trend=&quot;add&quot;,<br>    seasonal=&quot;add&quot;,<br>    initialization_method=&quot;estimated&quot;).fit()</pre><pre># make prediction for 4 years: 2 years for val set and another 2 years for forecasting<br>y = pd.DataFrame(model_exp_sm.forecast(48), columns=[&quot;pred&quot;])</pre><p>Спершу, розділяю датасет на тренувальний та валідаційний. Зверніть увагу, у data індексами є числа, а не дати, на відміну від датафрейму, який використовую для всіх інших моделей. Далі, створюю клас, тренд є лінійним, а сезонність точно повторюється кожного року, тому їм надаю значення “add”, якщо тренд є експонентою буде “mul”. Для прогнозування та тестування на валідаційному наборі створюю спільний датаферйм: перші два роки для тестування, інші два роки для прогнозування майбутніх значень.</p><p>Параметри моделі можна подивитися наступним способом:</p><pre>model_exp_sm.model.params</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*E6pwOngY1TX5epZx.jpeg" /></figure><p>Точність на валідаційному наборі становить 93.36%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*5Ig6EfZ_BI7Jmynw.jpeg" /></figure><h3>прогнозування через FFT</h3><p>Перетворення Фур’є — це перетворення комплексної змінної в іншу за конкретними параметрами. Такі перетворення частіше за все використовують для роботи з сигналами, але їх також можна використовувати для декомпозиції та прогнозування часового ряду. Для роботи з часовими рядами використовують дискретні перетворення Фур’є, оскільки значення часового ряду вимірюються у конкретному інтервалі.</p><p>Перетворення Фур’є включає в себе багато методів математичного аналізу, тому якщо вам цікаво дізнатися більше, пропоную переглянути цю <a href="https://towardsdatascience.com/the-fourier-transform-1-ca31adbfb9ef">статтю</a><strong>.</strong></p><p>Numpy має оптимізовану реалізацію дискретних перетворень Фур’є — FFT (Fast Fourier Transform). Я знайшла вже готову реалізацію та отримала наступний результат:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nMNHYF0DszkFWaz-.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*yo-Rw3MtgTc0OaMv.jpeg" /></figure><p>Прогнозування для вже існуючого ряду доволі точні, проте прогнозування майбутніх значень не має потрібної сезонності.</p><h3>GRU</h3><p>Для всіх наступних моделей я буду використовувати оригінальний нестаціонарний датасет. Традиційно вважається, що LSTM є більш точною за GRU моделлю, але для цього часового ряду найкращі результати показала саме GRU. У цьому розділі я розповім про підготовку даних, тюнінг моделі та прогнозування майбутніх значень.</p><ol><li>Підготовка часового ряда. До нейромережі подається два вида даних: змінні (х) та цільове значення (у), оскільки оригінальний часовий ряд має тільки одну змінну, кількість пасажирів, його потрібно перетворити у датафрейм, який можна розділити на х та у. Для цього я утворю матрицю з оригінальною змінною та лагами на 3 місяці:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*p97fVysGvIN3yIaK.jpeg" /></figure><p>2. Target -3: значення змінної 3 місяці тому, Target -2: два місяці тому та Target -1: місяць тому. Таким чином, утворилася матриця, де перші 4 стовбці — х, а останній стовпець — у. Через такі махінації часовий ряд втратив перші три місяці.</p><p>3. Нормалізація. Для прискорення навчання та більш якісних результатів отриману матрицю потрібно нормалізувати. MinMaxScaler() — це єдиний варіант нормалізатора, оскільки розподіл часового ряду не є нормальним. Важливою тонкістю при нормалізації є порядок її проведення: метод fit_transfom викликається на тренувальному наборі, transform викликається на тестувальному та валідаційному. Спочатку розділю матрицю на трейн, тест та валідаційний набори. Функція def scaling(df,train) нормалізує окремо кожний сет, bool змінна train визначає чи є сет тренувальним (train=True), чи ні. Цікавою особливістю є те, що якщо розділити дані по повних циклах сезонності, тобто по роках, точність підвищиться.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xGrW1KJAIF84w4S.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-2j-FuPLyWpuLA62.jpeg" /></figure><h3>Тюнінг</h3><p>Тюнінг — це спосіб максимально швидко знайти модель з найвищою точністю. Як і у більшості методів машинного навчання, тут теж є важлива деталь: гарну модель можна отримати лише в разі правильно підібраних гіперпараметрів та їх ранжування. Як тюнер я використовую keras-tuner та клас MyHyperModel(HyperModel) для створення моделі. Шукати гіперпараметри можна і за допомогою більш старих оптимізаторів, таких як Random Search, але краще використовувати Hyperband, який більш швидкий та якісний. Найкращу модель зберігаю.</p><pre>best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]</pre><h3>Навчання</h3><p>Далі, отриману модель слід навчити на підготовлених даних. Щоб уникнути перенавчання я використала EarlyStopping() та ModelCheckpoint(), щоб зберігти найкращі ваги. Робити це через restore_best_weight = True EarlyStopping() <a href="https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">не завжди гарна ідея</a> через те, що ваги будуть зберігатися лише в тому разі, якщо EarlyStopping() зупинився через обмеження, задане у patience, а не коли дійшов до останньої епохи, що буває доволі часто.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*QpmimvgPaTjbATJx.jpeg" /></figure><p>Після успішного навчання завантажую найкращі ваги до моделі</p><pre>#load best weights to the model<br>model.load_weights(&quot;/kaggle/working/checkpoint.model.h5&quot;)</pre><p>На функції втрат можна побачити невелике перенавчання</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GRz1Oq5xxj0ou2Mb.jpeg" /></figure><p>Для перевірки точності моделі на валідаційних даних, потрібно передбачити значення через model.predict() та зробити дані знову не нормалізованими через scaler.inverse_transform(). Точність моделі складає 90%, що не дуже вражає для такої потужної моделі та таких легких даних.</p><h3>Прогнозування майбутніх значень</h3><p>Спочатку створюю масив, що місить кожен місяць з 1961 по 1962 рік.</p><pre>first_year=pd.date_range(&quot;1961-01-01&quot;,&quot;1961-12-01&quot;, freq=&#39;MS&#39;)</pre><p>Далі, потрібно створити 3 місячні лаги. Оскільки валідаційний сет на рік менший за дати, для яких буду передбачати значення, то можна взяти лаги з валідаційного сету:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*KSTtxeXOerLfyeNJ.jpeg" /></figure><p>Далі, аналогічно до валідаційного сету, передбачаються значення через model.predict() та повертаються до ненормалізованого стану.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XG-_OwivkdXXITbz.jpeg" /></figure><h3>XGBoost Regressor</h3><p>Це ще одна модель, яку можна часто зустріти у задачах прогнозування часового ряду. Підготовка даних для цієї моделі ще простіша, оскільки її основа — це Random Forest, для якого не потрібно нормалізовувати дані. Все, що потрібно зробити з даними — це створити матрицю, схожу на ту, що використовувала для GRU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*ze7KxMhu_6pYwVyx.jpeg" /></figure><p>Додала додатковий четвертий лаг та розділила дату на місяць, квартал та рік.</p><h3>Тюнінг</h3><p>Для тюнінгу використовую HyperOpt, особливість цього тюнера в тому, що він зберігає всі результати навчання, в тому числі найкращу модель у Trials(). Зберігаю найкращу модель та підготую дані для навчання.</p><pre>def getBestModelfromTrials(trials):<br>    valid_trial_list = [trial for trial in trials<br>                            if STATUS_OK == trial[&#39;result&#39;][&#39;status&#39;]]<br>    losses = [ float(trial[&#39;result&#39;][&#39;loss&#39;]) for trial in valid_trial_list]<br>    index_having_minumum_loss = np.argmin(losses)<br>    best_trial_obj = valid_trial_list[index_having_minumum_loss]<br>    return best_trial_obj[&#39;result&#39;][&#39;Trained_Model&#39;]</pre><h3>Підготовка даних для навчання</h3><p>Перед розділенням даних на тестовий та тренувальний набір, я створила валідаційний набір з df_w_lags, оскільки кросс — валідація створює тільки тестовий та тренувальний набір. Разом з XGBoost часто використовують кросс- валідацію, яка розділяє дані на тестові та тренувальні наступним чином.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJ_5nqsHITE-riHK.jpeg" /></figure><p>Синім позначені тестові дані, помаранчевим — тествувальні. Такий алгоритм дає змогу більш якісно обробити дані, оскільки тренувальні та тестові сети змінюються.</p><p>Чому ж тоді не використовувати дані, розділені крос — валідацією, для тюнінгу? Швидкість тюніга напряму залежить від кількості даних та розміру пошукового поля, тобто крос — валідація тільки уповільнила б тюнінг.</p><h3>Навчання</h3><p>Функція cross_val_fit повертає якість моделі для кожного валідаційного спліта та саму модель. Як функцію втрати обрала MAE, щоб зменшити значення великих помилок.</p><pre>xgb_reg,scores=cross_val_fit(xgb_reg_tun,df_w_lags)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*omfRBzfCAvLYACVE.jpeg" /></figure><p>По графіку можна побачити, що модель трішки перенавчена, навчання можна було зупинити після 90 епохи. Також можна подивитися, яка змінна найбільше вплинула на модель:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iQg6Ky697FGB5B3Z.jpeg" /></figure><p>В моєму випадку це лаги 1 місяця.</p><h3>Прогнозування майбутніх значень</h3><p>Аналогічно до прогнозування майбутніх значень для GRU, створюю матрицю з лагів попередніх років для прогнозування за допомогою конкатенації. Стовпчик pred містить прогноз.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*McDksqd5TMorJXyF.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4VnHjAuN0AvPtv6s.jpeg" /></figure><p>XGBoost теж вловлює загальну сезонність, але пікове значення досягається у вересні, а не у серпні.</p><h3>Prophet</h3><p>Остання та найлегша у створенні модель. Prophet створила команда вчених з Facebook, основна особливість полягає в тому, що Prophet декомпозує модель під час навчання, на відміну від інших моделей.</p><p>Для навчання дані повинні надходити тільки в наступному вигляді:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*Qvr9O6praEKyaHtw.jpeg" /></figure><p>І так, це вся підготовка, яка потрібна для цієї моделі. Далі, отриманий датафрейм розділяю на тренувальний та валідаційний (останній рік).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EY1lC6Yi0uO_m32G.jpeg" /></figure><p>Пікового значення ряд набуває на 7 місяць, липень, замість серпня.</p><p>Точність є найбільшою серед усіх моделей:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*FEH1gfS6zphZbR3X.jpeg" /></figure><h3>Human Error vs Bayes (Perfect ) Error</h3><p>Метрики точності та помилки — це прекрасний спосіб зрозуміти, справжню якість моделі, але що робити, якщо після оптимізації якість підвищилась трішки і все ще менше бажаних 100%?</p><p>Чи повинна ідеальна модель мати 100% точності? У Машинному навчанні є два типи помилок, щоб зрозуміти це. Перша помилка — “Human Error“ — людська помилка. Вона репрезентує точність людських висновків на тих же даних, на яких навчається модель. Звичайно, ніхто не буде набирати фокус — групу, щоб знайти показник цієї оцінки, але це і не треба, оцінку можна передбачити приблизно. Я не змогла знайти точний відсоток, на який можуть помилитися фінансисти та математики при передбаченні часового ряду, але припустимо, що помилка становить 8%. Для знаходження роблять наступну табличку (ці значення я також припустила). Уявіть 3–4 групи людей з різними знаннями у сфері, до якої належать дані. Відповідно до use case (як модель буде використовуватися), найнижча помилка може бути “ідеальною“ помилкою, людська помилка — середня помилка або середнє між середньої помилкою та найбільшою. Якщо висока точність моделі є критичним показником, наприклад модель розпізнає ракові пухлини, то тоді “ідеальна“ помилка повинна бути вище за найменшу помилку з таблиці, людська помилка — вище за середню помилку з таблиці.</p><p>Професія людини</p><p>Відсоток помилки</p><p>- Людина без досвіду передбачення часового ряду (базове знання математики)</p><p>- Математик/фінансист</p><p>- Математик/фінансист з практичним досвідом</p><p>30%</p><p>8%</p><p>3%</p><p>Функція втрати моделі, після переходу через значення людської помилки, “потрапляє“ на плато, де не може знайти мінімум, відповідно якість моделі залишається сталою. Модель вважається хорошою, якщо її <strong><em>точність вище людської помилки</em></strong>.</p><p>Другий тип помилок — “Bayes Error“ або “ідеальна/недосяжна помилка“. Це помилка, яку в теорії може досягти модель при ідеальному розподілі даних, налаштуванні гіперпараметрів, тощо. Функція втрати моделі завжди буде нижче та ніколи не перейде межу ідеальної помилки.</p><p>Інтуїтивно це можна пояснити наступним чином: людина може передбачити, якою стороною впаде монетка (теорія вірогідності), але якщо крутяться сотні монеток, передбачити стає набагато складніше.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*x9Ad8NlQ7jpojy7X.jpeg" /></figure><h3>Порівняння точності всіх методів</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*IzQ-e5ikuLlJTBHR.jpeg" /></figure><p>Функції втрат майже всіх моделей знаходяться між горизонтальними осями людської та ідеальної помилки.</p><p>Можна сказати, що найвищу точність має SSA, але ця точність для маленьких даних з однією змінною. Останні три моделі показують найвищу якість для більш складних даних.</p><h3>Післямова</h3><p>Дякую, що дочитали, сподіваюся було корисно та цікаво! Як можете побачити, я використовую англомовну літературу, але розумію, що не всім такий спосіб вивчення є зручним, тому прошу поділитися у коментарях україномовними каналами, статтями, аккаунтами в Твіттері, тощо. З ваших відповідей я складу список та опублікую. Дякую!</p><h3>Використані джерела</h3><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.kdnuggets.com/2023/08/leveraging-xgboost-timeseries-forecasting.html</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.datadriveninvestor.com/mastering-advanced-time-series-techniques-7b1080cef853</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.linkedin.com/pulse/how-use-machine-learning-time-series-forecasting-vegard-flovik-phd-1f?utm_source=share&amp;utm_medium=member_ios&amp;utm_campaign=share_via</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.databricks.com/blog/2021/04/15/how-not-to-tune-your-model-with-hyperopt.html</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.linkedin.com/advice/0/what-difference-between-mean-squared-error-tz1mc</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/@rithpansanga/optimizing-xgboost-a-guide-to-hyperparameter-tuning-77b6e48e289d</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/kaggle-blog/chucking-everything-into-a-random-forest-ben-hamner-on-winning-the-air-quality-prediction-788be7620e69</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://hyperopt.github.io/hyperopt/getting-started/search_spaces/</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://www.machinelearningplus.com/time-series/augmented-dickey-fuller-test/</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/stationarity-in-time-series-a-comprehensive-guide-8beabe20d68</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/seasonality-of-time-series-5b45b4809acd</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://medium.com/analytics-vidhya/singular-spectrum-analysis-kernel-pca-for-time-series-regression-64679c155c80</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/the-fourier-transform-1-ca31adbfb9ef</a></p><p><a href="https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101">https://towardsdatascience.com/fourier-transform-for-time-series-292eb887b101</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">Differencing Time Series In Python With Pandas, Numpy, and Polars | Forecastegy</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">When working with time series data, differencing is a common technique used to make the data stationary.Stationary data</a></p><p><a href="https://forecastegy.com/posts/differencing-time-series-in-python-with-pandas-numpy-and-polars/">forecastegy.com</a></p><p><a href="https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">https://medium.com/@doleron/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c27293e7b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Не бійтеся інтегралів]]></title>
            <link>https://medium.com/@mirandorexes/%D0%BD%D0%B5-%D0%B1%D1%96%D0%B9%D1%82%D0%B5%D1%81%D1%8F-%D1%96%D0%BD%D1%82%D0%B5%D0%B3%D1%80%D0%B0%D0%BB%D1%96%D0%B2-14755faced90?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/14755faced90</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[математика]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 17:38:14 GMT</pubDate>
            <atom:updated>2025-09-13T17:38:14.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Основна складність у розв’язанні інтегралів полягає у плутанині великої кількості технік інтегрування. У цій статті я детально розповім про суть інтегралів та систематизацію техніки інтегрування. З цим, розв’язання навіть складного інтеграла можна зробити у декілька строк.</p><h3>В чому суть математики?</h3><p>Це питання починає назрівати в голові вже після років вивчення математики, але, як на мене, відповідь на нього є першим кроком до розуміння інтегралів насправді.</p><p>Математика дає інструменти для оцінки того, що і так здається логічним. Вона не змушує “висасувати з пальця” теорії, які можна віднести до фантастики. Ви можете самостійно вивести формулу площі кола, граючись з кількістю розрізів та товщиною цих розрізів. Математика — це спосіб доведення фундаментальних та складних принципів через те, що вас оточує. Майже всі складні теореми були доведені через розбиття на складові частини та їх подальшу суму.</p><p>Повернімося до прикладу з площею кола, цей приклад детально показаний у серії відео <a href="https://youtu.be/WUvTyaaNkzM?si=p7_xykmX14cQPR3I">3Blue1Brown</a>.</p><ol><li>Маємо найзвичайнісіньке коло з радіусом R = 3.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*fXJQglTmvs0gxpxC.jpeg" /></figure><p>2. Площу кола можна знайти через суму розрізів кола (уявіть як ріжете торт), але для цього треба “розрізати” коло на такі частинки, щоб можна було знайти площу цих розрізів.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*z5pGh6Ax_RHkhiTv.jpeg" /></figure><p>3. Жоден з варіантів розрізів не підходить, чому б не спробувати розріз по кільцям, як у стовбура дерева?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*-1VvqVjQS9QGQqc1.jpeg" /></figure><p>4. Спробуємо знайти площу кожного кільця, або вивести формулу для знаходження. Припустимо, що якщо “розкрити” кільце вийде прямокутник, формулу якого вже маємо.</p><p>Ширину утвореного прямокутника можна знайти по формулі довжини кола, бо, задля простоти експерименту, вона нею і буде.</p><p>Висоту прямокутника, товщину зрізу, задамо константою 0.1 (це може бути як велике, так і маленьке число, задля спрощення обчислень, нехай буде маленьке число).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKXxmlcHmvnNWk47.jpeg" /></figure><p>5. Тепер, маючи ширину та довжину прямокутника, знаходимо площу за формулою: <strong><em>2rdr</em></strong>.</p><p>6. Маючи щойно створену формулу, розраховуємо площу кожного розрізу, після чого сумуємо площі всіх розрізів. Прекрасно! Але наскільки точне таке обчислення? Як бачимо, наше коло складається з 15 розрізів, але через велику товщину кожного розрізу, між ними є пространство, через що коло виглядає не дуже правдоподібно.</p><p>Зменшуючи товщину кола, наприклад, до dr = 0.00001, розрізи розташовані щільніше, коло вже набуває правильної форми. Але тепер потрібно знаходити площу більшої кількості розрізів.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*hWo7JBXo28Zd_FQL.jpeg" /></figure><p>Спробуємо знайти швидший спосіб.</p><ol><li>Спершу спробуємо знову “розкрити” кожен розріз і розташувати його на координатній площині, від найменшого до найбільшого. Дивлячись уважно можна побачити, що зменшуючи товщину розрізу ще більше, dr = 0.000000000000001, маємо майже цільний трикутник, тож тепер площа кола — <strong>це площа під прямою</strong>, “гіпотенузою” трикутника, тобто — площа трикутника.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uiT3dGcqID8RmgsO.jpeg" /></figure><p>2. Розрізи утворюють прямокутний трикутник, з висотою кожного розрізу 2r (поставимо кожен прямокутник так, щоб довжина стала висотою)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8suCmKhq40tIWlw.jpeg" /></figure><p>3. Основа прямокутного трикутника дорівнює радіусу, 3, тоді як бічна сторона — це довжина розрізу, тобто 2r. R для найбільшого розрізу дорівнює радіусу кола, 3, бічна сторона буде 6.</p><p>4. Обчислюємо площу прямокутного трикутника за формулою.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YTH7IIvHCA_a7avY.jpeg" /></figure><p>5. Підставляючи R замість 3, отримаємо формулу площі кола.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S308ZR5gDTx-D3Wm.jpeg" /></figure><p>6. І знову ж питання, наскільки отримане значення точне? Продовжуючи зменшувати товщину розрізів до мільйонних, мільярдних і так далі, між розрізами майже не буде простору, але наскільки б тонкими розрізи не були, отримана таким способом площа кола все одно буде наближеним значенням.</p><p>Фух! Це була цікава гра у розрізання кола, з подальшим перетворенням у суму прямокутників, з яких далі складається прямокутний трикутник. Ви винайшли формулу, застосовуючи найпростішу математичну операцію — суму. Як? Крутили та вертіли задачу, як кубика Рубрика, поки не знайшли правильний кут, під яким видно рішення.</p><h3>Зв’язок інтеграла та похідної</h3><p>Зв’язок похідної та інтеграла називають “Фундаментальною теоремою обчислень”. Інтеграл в англомовних джерелах найчастіше називають “антипохідною”, і як на мене, цей термін краще пояснює природу інтегралу — протилежність до похідною.</p><p>Спершу, згадаймо, що таке похідна. Похідна — це зміна нахилу функції до осі Х на невеликому проміжку, простішими словами, наскільки функція чутлива до зміни Х. Надважливим аспектом у розумінні похідних є те, що вона показує зміну функцію на невеликому інтервалі, а не зміну в конкретній точці, в одну мить.</p><p>Найкраще це ілюструє наступний приклад: уявіть, що ви сідаєте в авто та їдете 500 метрів. Спочатку авто набирає швидкість, перед зупинкою швидкість знижується до повної зупинки. Функція дистанції буде виглядати ось так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Te5e9WCBB4E7q0q.jpeg" /></figure><p>Але як знайти швидкість? Швидкість — це зміна проїханої дистанції за дуже короткий проміжок часу, іншими словами — це різниця між, наприклад, 0.1с та 0.2с, бо швидкості в конкретний час не існує (уявіть фотографію автівки, ви не зможете сказати її швидкість).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bHV6HwxEyDfiTYK1.jpeg" /></figure><p>З цього виходить, що швидкість — це похідна дистанції. І справді, за перші дві секунди, різниця проїханої дистанції у проміжку між 1 та 2 секундах невелика, бо авто тільки починає набирати швидкість, у проміжку між 4–7 секундах зміна проїханої дистанції більша, авто їде з більшою швидкістю, між 9–10 секундах різниця ледь відчутна, бо авто майже зупинилося.</p><p>S(t) — функція дистанції, v(t) — функція швидкості, похідна дистанції.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7gZdb6NAGkH3anSf.jpeg" /></figure><p>Проведіть уявну лінію нахилу, функції S(t) до осі Х, чим більший нахил, тим “яскравішою” буде похідна.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOQsFD8wycD8PMVk.jpeg" /></figure><p>У проміжку між 4–7 секундами, коли авто починає прискорюватися, похідна v(t) помітно змінюється. Для кращого розуміння треба брати дуже малий інтервал (4.1с — 4.2с), але для ілюстрації взяла більший.</p><p>Наприклад, функція та похідна при швидкому старті та різкій зупинці буде виглядати так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TQcOr3xTWEOSZQ1n.jpeg" /></figure><p>Але як знайти тоді швидкість? Швидкість = Дистанція/Час. Оскільки швидкість — це зміна функції дистанції у дуже маленькому інтервалі (для ілюстрації беру великий інтервал у 0.3с):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*JVDtMxjSb3wELQ88.jpeg" /></figure><p>Дуже маленький інтервал — це інтервал, значення якого наближається до 0, наприклад, 0,00000000000000001 та 0,00000000000000002.</p><p>Тому, загальну формулу похідної можна записати ось так, де ds — зміна дистанції на дуже маленькому інтервалі, dt — зміна часу у дуже маленькому інтервалі.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*jbtqXQ4yDH5kN0aQ.jpeg" /></figure><p>Тут, зміна у дистанції виражена через дуже маленький часовий інтервал dt:</p><p>S(1c+0,00000000001) = S(1,00000000001)= 3м.</p><p>Похідна — це зміна функції за дуже короткий інтервал, у околицях однієї точки, але цей інтервал ніколи не буде дорівнювати 0, тобто ніколи не буде у конкретній точці. Без визначення інтервалу як такого, що наближається до 0, розрахунок похідної був би дуже складним. Це допомагає значно спросити похідну.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2WKny5flcwcSaa8Y.jpeg" /></figure><h3>Фундаментальна теорема обчислень — зв’язок похідної та інтегралу</h3><p>В український школах найчастіше пояснюють так: інтеграл — це “батьки” функції, похідна — “діти” функції. Таке пояснення є дуже простим, але не пояснює природу інтегралу. Інтеграл, або “антипохідна”, та похідна це взаємообернені операції. Спробуємо вивести формулу інтегралу самостійно, як з формулою площі кола.</p><p>Щоб пояснити інтеграл використаю як приклад ситуацію, обернену до написаної вище. Уявімо, що потрібно знайти дистанції, яку проїхало авто, використовуючи лише спідометр. Ви побудували ось такий графік, дивлячись на показання спідоментра. Математично, цей графік є похідною від функції дистанції, але у вас є лише спідометр, щоб знайти дистанцію. Щоб знайти функцію дистанції, треба зробити операцію, обернену до похідної, тобто, знайти інтеграл.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CAtcsuAZkrHdg-kz.jpeg" /></figure><p>Функція швидкості v(t) не є лінійною, тому записана у вигляді полінома другого ступеня. Повернемося до визначення швидкості:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*hQXPts5r-MdYilpm.jpeg" /></figure><p>Але як знайти цю функцію S? Як і в найпершій задачі з колом, спробуємо знайти правильний кут, під який потрібно дивитися на задачу. Уявімо, що авто рухається за сталою швидкістю, тоді функція швидкості буде виглядати ось так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HIsk-2pksZ4jpLkm.jpeg" /></figure><p>Виходячи з рівняння швидкості, дистанція S = VT, тобто, дистанція — це площа під графіком функції швидкості, у варіанті зі сталою швидкістю — площа прямокутника. Отримане таким способом значення проїханої дистанції буде наближене до реально значення. Ви можете сказати, це ж бред, як дистанція може бути площею прямокутника, і це дуже правильне питання. Як і в першому прикладі, якщо задача складна — потрібно спробувати розділити її на маленькі частинки, і потім знайти їх суму.</p><p>На які ж частини найлегше для обчислення розділити наш графік швидкості? Знову, прямокутники. У якій ситуація такий спосіб може спрацювати? Якщо авто їде з однаковою швидкістю протягом кожної півсекунди. Швидкість у 1.5 сек. більша, ніж у 1 сек., але оці півсекунди між 1.5сек та 1 сек. авто їде зі сталою швидкістю.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uj8BnxfCpXheNfAq.jpeg" /></figure><p>Виходить доволі негарно, але якщо зменшити інтервал сталої швидкості, прямокутники будуть краще вписуватися під форму графа.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4oxGa-lT_cIxio2L.jpeg" /></figure><p>Тепер спробуємо знайти площу якогось прямокутника.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pND4LuBL_MKOYNl_.jpeg" /></figure><p>Нехай швидкість буде стала на інтервалі у 0.25 сек, тоді ширина прямокутника буде 0.25, але як визначити довжину? Чи взяти більше значення швидкості, 8.4, чи менше, 7? Це не має значення, чим менше інтервал, тим краще прямокутники будуть вписуватися під граф функції.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qHUrMhKHRop_4NyC.jpeg" /></figure><p>Чим меншим буде інтервал, тим більш “плавніше”, без помітних скачків, буде рухатися змодельоване авто.</p><p>Загальна формула площі кожного прямокутника буде: v(t)dt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n_mujoINBICeIgaD.jpeg" /></figure><p>Прекрасно! Тоді, для знаходження площі під функцією, треба просумувати площі всіх прямокутників? Як казала раніше, інтеграл — це операція, обернена до похідної, а сума явно такою не є. Інтеграл повинен стояти “вище” функції, тобто мати якісь ознаки більшості — а саме, показник степені. Навіщо ж це робити? Чим вища степінь полінома, тим складнішу він має форму. Площі під таким складним поліномом неможливо знайти, використовуючи просто суму, наскільки б маленьким не був інтервал, наскільки б добре мільйони маленьких прямокутників не вписувалися під графік функції. Значенням інтегралу буде площа під кривою, графіком, саме інтегралу.</p><p>Важливо запам’ятати, що хоч сума та інтеграл мають схоже написання, вони є різними операціями:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*O3YlCsFxNC6RAajK.jpeg" /></figure><p>dt у сумі буде мати константне значення, тобто, навіть з самим маленьким інтервалом, “шпаринки” між прямокутниками залишаться, тоді як dt у інтегралі завжди буде наближатися до нуля (через це інтеграл іноді розглядають як ліміт суми) — “шпаринки” будуть непомітними.</p><p>Для цього прикладу площа фігури під інтегралом, не функції, буде дистанцією, яку проїхав автомобіль.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*GNZS2v05xZPpLsPX.jpeg" /></figure><p>Ще одним важливим аспектом інтегралу є вільна константа С, що відповідає за “рух” функції по осі Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zzsWqOqlIx_bK9Q_.jpeg" /></figure><p>Скільки б ви не піднімали чи опускали функцію дистанції, як на картинці вище, нахил функції до осі Х, тобто похідна, не зміниться — функція залишиться з власними властивостями. Тобто, інтегралів до функції є безліч, через що функція не прив’язана до одного конкретного інтегралу з одним значенням С. Покажу на прикладі.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*jh_N9aEzeDBqVniv.jpeg" /></figure><p>- є функцією дистанції, тобто, інтегралом до нашої першої функції швидкості. Щоб знайти функцію швидкості, потрібно взяти похідну від інтегралу. Правила інтегрування кажуть, що константи стають 0, тобто отримуємо ту саму функцію швидкості: t(8-t).</p><p>Але, це працює тільки з невизначеними інтегралами (ті, які не мають меж), як у попередньому прикладі. Мені допомагає такі порівняння: невизначений інтеграл — це корабель без якоря, хвилі можуть його піднімати та опускати, тоді як визначений інтеграл має якір, він стоїть на місці, “прив’язаний” до своєї осі. Саме визначений інтеграл є значенням площі під кривою, конкретним числом, а самі межі інтегралу підставляються у невизначений інтеграл. Приклад:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*albF4GsP5zDECTWh.jpeg" /></figure><p>Нижня та верхня межа можуть бути будь — якими числами.</p><p>Навіть якщо додати константу С до визначеного інтегралу, вона анулюється віднімання верхньої межі від нижньої.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4yyKkgTPOpqOb5Fa.jpeg" /></figure><p>Фух, цей розділ дуже добре погрався зі свідомістю, давайте пригадаємо всі основні моменти. Я намагалася якомога простіше пояснити саму суть інтегралу, але за цією суттю йдуть дуже цікаві частні випадки, які трапляються вже в наукових сферах.</p><h3>Recap</h3><ol><li>Інтеграл та похідна — взаємообернені операції.</li><li>dt,dx, d з будь- якою літерою — це показник дуже маленького інтервалу, дуже маленьких змін.</li><li>dt0 завжди наближається до нуля, задля вписування прямокутників ідеально під графік.</li><li>Інтегрування та сума — це різні операції.</li><li>Невизначений інтеграл — це формула, визначений інтеграл — це площа під графіком невизначеного інтегралу.</li><li>Визначений інтеграл “прив’язаний” до осі, тоді як до невизначеного потрібно додавати константу.</li><li>Визначений інтеграл знаходиться шляхом знаходження різниця між невизначеним інтегралом куди підставлена верхня межа, від невизначеного інтегралу, куди підставлена нижня межа.</li></ol><p>У наступних розділах розглянемо конкретні приклади знаходження як визначеного, так і невизначеного інтегралу.</p><h3>Техніки інтегрування</h3><p>Передмова: я, як і доволі багато студентів інженерних спеціальностей, мала труднощі з чітким упорядкуванням, якою технікою який вид інтегрування треба вирішувати. У університетських посібниках я не знайшла чіткої класифікації, знайшла її у підручнику <a href="https://www.math.ksu.edu/~cochrane/m221/m221s22/CalculusVolume2.pdf">MIT Calculus 2</a>. Тепер трохи про Calculus 2. В американській системі інший розподіл тем. Precalculus — це основні операції, дроби, прості рівняння, тощо — на рівні 7 класу наших шкіл. Calculus 1 — це ліміти, похідні першого ступеня, ряди. Calculus 2 — інтеграли, похідні різних ступенів, об’єми складних тіл, тощо. Calculus 2 зазвичай починають вивчати вже в університеті або коледжі.</p><p>Загальний порядок дій:</p><ol><li>Спробувати вирішити інтеграл через додавання, множення (power rule).</li><li>Якщо не вдається, вирішувати за допомогою u-substitutional.</li><li>Якщо обидва варіанти не підійшли, переходити до інших методів.</li></ol><h3>Техніка заміни (U-substitutional)</h3><p>Це проста техніка заміни, яка полягає у тому, щоб всі частини інтегралу визначити через u та du наступним чином: u — повинно підставлятися у ту частину рівнняння, похідна якої є іншою частиною інтегралу, оскільки du — це похідна u. У цій техніці замінюється і dx.</p><p>Приклад 1: Інтегрування u-sub</p><p>Розв’яжемо цей інтеграл:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*4NwzMyG6o4q-amxb.jpeg" /></figure><ul><li>Через похідну якої частини рівняння можна виразити весь інтеграл?</li><li>Якщо взяти 4x, похідна 4х це 4, через що не можна виразити (x²+5)². Якщо ж взяти (x²+5), похідна буде 2х, через неї можна виразити іншу частину інтегралу — 4х.</li><li>Інтеграл має 3 частини, які потрібно замінити: 4x, (x²+ 5)², dx.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*LlWxGnE7ydj2vS-l.jpeg" /></figure><h3>Інтегрування по частинам — Integration by Parts</h3><p>Ця техніка проста, але дуже ефективна. Щоб розуміти техніки інтегрування, потрібно знати на яких математичних законах вони базуються. Це може бути нудно, але обіцяю, це допоможе краще розуміти їх та не гуглити кожен раз.</p><p>Інтегрування по частинам базується на законі добутку (product rule) — це диференціальний добуток двох та більше функцій. Диференціальний добуток не є “звичайним” добутком, світ був би набагато простішим, і в плані технологій, якщо для чисел та функцій добуток працював однаково. Дуже грубо та поверхнево кажучи, диференціальний добуток працює не в одній площині, як добуток чисел, а в багатьох. Тобто, оскільки кожна функція розташована у власній площині, диференціальний добуток повинен “перемножувати” площини обох функцій.</p><p>Наприклад, функція y = x²cos 3x є добутком двох функцій: x2 та cos3x. Ми можемо взяти інтеграл або похідну від кожної функції окремо, але щоб взяти похідну або інтеграл від функції y, потрібно використовувати правило добутку.</p><p><strong>Правило добутку</strong></p><p>Перепишемо функцію як <em>h(x) = f(x)g(x)</em>, де <em>f(x)</em>=x², <em>g(x)</em>= cos 3x. Правило добутку каже. що похідна <em>h(x)</em> — це сума добутків похідної першої функції та другої, похідної другої функції та першої функції:</p><p><em>h′(x) = f ′(x)g(x) + g′(x)f(x)</em></p><p>Тепер спробуємо інтегрувати, щоб отримати функцію <em>h(x):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*fx-JrgBj9JUp8EXQ.jpeg" /></figure><p>- сума функцій під одним інтегралом може бути розділена на 2 та більше інтегралів, dx потрібно приписувати до кожного інтегралу (dx — неймовірно малі зміні на інтервалі).</p><p>Тепер маємо суму двох інтегралів, кожен з яких є добутком функції та похідної.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*DLEicPeU8k7tJgqu.jpeg" /></figure><p>І справді, інтеграл повинен бути “оригінальним” добутком f(x)g(x). Для легшого запам’ятання формули замінимо на u та v:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*AjHjkuaJLD5f7NO0.jpeg" /></figure><p>— u та v — функції, dv та du — їх похідні.</p><p>Інтегрування по частинам розбиває складний інтеграл на простіший. Виходячи з правила добутку, інтегрування по частинам використовується, коли інтеграл містить добуток двох функцій. Але, якщо інтеграл містить добуток під коренем, інтегрування по частинам не спрацює. Добуток повинен бути “чистим”.</p><p>Приклад 1: Інтегрування по частинам</p><ol><li>Не можна казати, що u = x, dv = sinx тільки по червоговості написання. Черговість для добутку не важлива. Тому, треба спробувати всі варіанти:</li></ol><ul><li>Варіант 1: u = sinx, dv = x, тоді du = cosx (похідна sinx), v= x22 ( v — це функція, dv — похідна цієї функції, тобто, щоб знайти функцію, потрібно взяти інтеграл від похідної). Цей варіант навпаки ускладнить інтеграл.</li><li>Варіант 2: u = x, dv = sinx, du = 1dx, v = — cosx. Така підстановка спрощує інтеграл, її і буду використовувати.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*311PvHjknUA6Whrq.jpeg" /></figure><p>І ось, страшний тригонометричний добуток перетворився у просту суму.</p><p>Напевно ви чули, що хороший математик — лінивий математик. При використанні будь — якої техніки інтегрування, задача — це максимально швидко та правильно знайти рішення. Можливо у вас виникло питання, чи є якась підказка по вибору u та dv. Так, вона є, і, що іронічно, її акронім співзвучний до Ліліт.</p><h3>LEATE — метод знаходження u та dv</h3><p>Акронім LIATE ( Logarithmic Functions, Inverse Trigonometric Functions, Algebraic Functions, Trigonometric Functions, Exponential Functions), української так само, використовується ось так: яка функція інтеграла є першою у с акронімі, та функція і є u.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*Qmorp9njEFPHZSgr.jpeg" /></figure><p>Тригонометрична функція хоч і є першої в інтегралі, але в акронімі йде після логарифмічної, тому u = логарифмічна функція, dv = тригонометрична функція.</p><p>Приклад 2: Застосування LEATE</p><p>Використаємо акронім, простіше буде переписати інтеграл ось так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*mC6OBkI-cGFPLHlH.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*We2eRTLabRnxrnTZ.jpeg" /></figure><p>Навіть такий неприємний дробний інтеграл можна вирішити у кілька строк. Якщо вам не подобаються дроби, їх можна переписати у вигляді добутку, але з негативними степенями.</p><p><strong>Приклад 3: Коли LIATE не працює</strong></p><p>Такі інтеграли доволі рідкісні, але і LIATE є тільки підказкою.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*g_0n6GPQ_GNjprTK.jpeg" /></figure><p>Приклад 4: Застосування інтегрування по частинам більше, ніж 1 раз</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*bd4ayAHP8sSruOSG.jpeg" /></figure><p>цей інтеграл не є добутком, на відміну від попередніх прикладів, тобто, в інтегралі є тільки є функція — sinx. Але як же тоді обрати u та dv? У таких випадках за u або dv використовують 1 (найчастіше за все за dv):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*rrJChtnjTxLCS5Y9.jpeg" /></figure><p>Подвійне інтегрування по частинам видається дивним, але зробивши декілька аналогічних вправ дивність зникає.</p><h3>Інтегрування по частинам: Визначений інтеграл</h3><p>На цей вид інтегралів переноситься все те ж саме, що працювало для невизначених інтегралів. Окрім, як казала раніше, константи C — вона вже не потрібна, оскільки інтеграл “прив’язаний” до осей через верхню та нижню межу визначеного інтегралу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*2jhGKAv5uQHIvaDC.jpeg" /></figure><p>Ці межі “окреслюють” інтеграл. Завдання “Знайти площу під кривою” фактично означає вирішити визначений інтеграл.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*vKf6q7zE4FxvbSxt.jpeg" /></figure><p>Приклад 1: Знайти площу між y = tan^(-1)x та віссю X на проміжку [0,1]</p><p>Проміжок дійсних чисел завжди пишеться у квадратних дужках, позитивна/негативна безкінечності — у круглих.</p><p>Щоб знайти площу, потрібно вирішити визначений інтеграл</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*K67T4wGeQMRYgArN.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*84GUj8eHOPNk_E0y.jpeg" /></figure><p>Не мали б інтеграла, будували б мільйон тоненьких прямокутників, а потім знаходили площу як їх суму. На щастя, інтеграл дозволяє знайти площу у кілька строк. Хоч інтеграл і не є добутком функцій, оскільки має тільки одну, але це все ще не табличний інтеграл.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*k_7tRS9l8E8XsX8P.jpeg" /></figure><p>Як бачите, навіть найнеприємніший на вигляд інтеграл можна швидко вирішити.</p><h3>Тригонометричні інтеграли</h3><p>Тригонометричні інтеграли вважаються одними із найскладніших у розв’язанні, але тільки якщо не знати правильну техніку. Вони складаються з добутку тригонометричних функцій. Сама техніка інтегрування є частиною Trigonometric Substitution — об’ємною теми, частину з якою розкажу у цій главі.</p><p>Тригонометричні інтеграли використовуються для розрахунку у різних системах, тому, якщо ви не працюєте у цій області, зустрічаються доволі рідко. Ця тема дуже велика, тому тут опишу тільки основні моменти, від яких, якщо потрібно, можна вивчати далі.</p><h3>Тригонометричні інтеграли як добуток або степінь з sinх та cosх</h3><p>Основні кроки полягають у:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*X6I3a695MM7doICQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5lDq4kNm5ykSgay8.jpeg" /></figure><p><strong>Приклад 1: Коли k — непарна степінь</strong></p><p>Інтеграл виду:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*Nq8G1HmOpJv7-Ilm.jpeg" /></figure><p>Для вирішення підходить тільки 1 випадок.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*zgznmu3eOAEi0cwR.jpeg" /></figure><h3>Тригонометричні інтеграли як добуток або степінь з tanx та secx</h3><p>Перш за все, sec (секант) — це не котангенс. Хоч для нас більш звичним є котанганс, але основними тригонометричними функціями є сінус, тангенс та секант.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*P4f8cus-z3KxAnjR.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*w2dgh37OjIrB2sd3.jpeg" /></figure><p>Аналогічно з синусом та косинусом, алгоритм дій такий:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*ng_hM2pfnwoy6d6j.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CB5A0GIUmxDCouiq.jpeg" /></figure><p><strong>Приклад 1: Коли j парної степені</strong></p><p>Для цього прикладу підходить тільки 1 варіант, на відміну від степенів синуса та косинуса, тут останній пункт має степені різної парності.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*5owIbifnJFSXZLNR.jpeg" /></figure><p>Фух, це може здаватися спочатку незвичним, тому пропоную переглянути більше прикладів тут.</p><h3>Тригонометрична підстановка (Trigonometric substitution)</h3><p>Частиною цього розділу є тригонометричний інтеграл. Тригонометрична підстановка застосовується до інтегралів, які містять квадратний корінь у формах:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*D0kKYbKJ6Q2rb49N.jpeg" /></figure><p>Основна ідея — це переписати інтеграл у вигляді тригонометричного інтегралу.</p><p>Доречним буде питання, чи настільки важливо робити саме таким способом? Так. Іншими техніками інтеграл з коренем розв’язати неможливо.</p><p>Тож, трохи теорії як працює ця підстановка.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*AxbOBYdF5CYLY-fy.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Hjp3wODbOyNuqck.jpeg" /></figure><p><strong>Приклад 1: Інтеграл 1 виду</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*VN10iEC6HzvQZ7Qg.jpeg" /></figure><p>З першого погляду виглядає не дуже дружелюбно (з другого теж), але спробуємо подружитися. Зробимо заміну, як підказує другий пункт:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*IOLcWr02v-EsX7LE.jpeg" /></figure><p>Щоб краще зрозуміти, раджу малювати ось такий трикутник:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*hLWfoj8aeIqpm1lS.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*qaEA23aw-PCqLioj.jpeg" /></figure><p>Такий вид інтегралів є найскладнішим з Calculus2, оскільки підстановку потрібно робити, дивлячись на трикутник.</p><p><strong>Приклад 2: Інтеграли 2 типу</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/0*lDQEdOnzlOclO3wu.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*wMwcqjdsjNIfWCPo.jpeg" /></figure><p>Розв’яжемо інтеграл та намалюємо референсний трикутник</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*6oBoMgdSampGAze6.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*bdWDd-TlZH0uxosh.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*HV2_oCSfdpO_rb8X.jpeg" /></figure><p><strong>Приклад 3: інтеграли 3 типу</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*iVG4bb7N_fdtLR4K.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QKfD73GjvDIIDsIs.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kvVmN9uHo5EdlvpK.jpeg" /></figure><p><em>Завдання: знайти площу між f(x) = x² − 9 та віссю X, на проміжку [3,5]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*9jH92z3utSAGaJJW.jpeg" /></figure><p>Також потрібно замінити межі визначеного інтегралу на:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*6lYjvREcZcen7FZT.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*guIekVpjaUR3mWtb.jpeg" /></figure><h3>Частковий розклад (Partial Fraction)</h3><p>Ця техніка працює з поліномними (багаточлен) інтеграли. Чому для поліномів потрібна окрема техніка? Ви вже знаєте як розв’язати інтеграл з раціональними функціями — за однією з технік вище або, розклавши, вивести табличний інтеграл. Проте. такі функції не мають довільних часток, які мають поліноми.</p><p>Суть техніки — це розкласти складний поліном на складові, які вже можна розв’язати.</p><p>Наприклад,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*gvnCwdoqe3uxmUiZ.jpeg" /></figure><p>Розкладання в цьому випадку — це знаходження коренів полінома у знаменнику, за Вієта чи дискримінантом.</p><p>Поліноми записують у вигляді P(x)/Q(x), техніку часткового розкладу можна застосувати тільки тоді, коли степінь чисельника менша, ніж степінь знаменника, deg(P(x)&lt;Q(x))).</p><p>Загальний алгоритм є наступним:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*9IKRLrc5JmTFbAop.jpeg" /></figure><p>Перший випадок, коли степінь чисельника менша, ніж степінь знаменника, вже побачили. Перейдемо до випадку, коли степінь чисельника більша.</p><p><strong>Приклад 1: deg(P(x)&gt;Q(x)))</strong><br>У цьому випадку потрібно зробити ділення полінома у чисельнику, на поліном у знаменника. Це називається <a href="https://youtu.be/_FSXJmESFmQ?si=rm1EOlNI5ojOF_XZ">Long Division</a> (<a href="https://freetutor.com.ua/Math/Division_of_polynomials">ділення поліномів</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*5vqJX8ihADD5yucp.jpeg" /></figure><p><strong>Приклад 2: Поліном містить неповторювальні фактори (Випадок 3a)</strong></p><p>Бувають випадки, коли степінь чисельника хоч і менша, за степінь знаменника, але поліном не можна розкласти:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*NtYXVcFQD2azbq0z.jpeg" /></figure><p>У таких випадках використовують розклад полінома за константами A,B,C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*y2z2eW-MvN1zWD9t.jpeg" /></figure><p>Зводячи до спільного знаменника, отримаємо:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*Dfjtt24yc_p_C8da.jpeg" /></figure><p>Прирівнюємо чисельник до чисельника, щоб знайти значення A,B,C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*KC8JeULH4ufSaqGu.jpeg" /></figure><p>Існують два методи для знаходження A,B,C — Метод прирівнювання коефіцієнтів та Метод стратегічного заміщення. Як на мене, перший простіший.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n9Vcahu6hQzrbD1z.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*HUxu7i-eEHe-BeKA.jpeg" /></figure><p>Отримані значення коефіцієнтів підставляємо:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*_4reNufOw-CM8c5p.jpeg" /></figure><p><strong>Приклад 3: Поліном містить повторювальні фактори (Випадок 3b)</strong><br>Якщо поліном (найчастіше знаменник) містить степеневий фактор, його потрібно розписувати ось так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*hMceGoLSmiI62iNY.jpeg" /></figure><p>Розв’яжемо інтеграл:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*6lp1Q0ikNi9QjYFd.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*5IBIdnhW09nMIHKV.jpeg" /></figure><p>Зверніть увагу, що (2х-1) повторюється два рази: спочатку у першій степені, потім у другій. Прирівнюємо чисельники:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*NvoSs5qHvOmaugor.jpeg" /></figure><p>Розкриваємо дужки:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*LudXYlU1CIWvea74.jpeg" /></figure><p>Використовуючи один з верхніх методів, отримаємо: A = 2, B = 3, and C = −1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*jhaLGJz70wMIKIGh.jpeg" /></figure><p>Я відбирала приклади, які трапляються найчастіше. Але дуже раджу подивитися більше на<a href="https://www.math.ksu.edu/~cochrane/m221/m221s22/CalculusVolume2.pdf"> сторінці 313</a>.</p><h3>Інші техніки інтегрування та числові методи визначеного інтегралу</h3><p>Інтеграли можна розв’язувати і за допомогою електронного калькулятора CAS, але раджу ним користуватися, тільки якщо є базові знання інтегралів і розуміння технік інтегрування.</p><p>Як казала раніше, визначений інтеграл — це наближене значення площі під кривою. Але, щоб це значення було максимально наближеним, потрібно обирати один з декількох методів, в залежності від виду інтеграла.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DbKGA0MYdLOp_5tD.jpeg" /></figure><p>Один з найперших прикладів, пошук площі під кривою за допомогою безлічі прямокутників — це Midpoint Rule, Правило середньої точки. Ця техніка вважається більш точною, оскільки за своїм визначенням усереднює значення.</p><p>Іншою технікою є пошук площі, розділяючи на трапеції. Така стратегія може здатися більш коректною, оскільки візуально трапеції краще вписуються під графік функції, ніж прямокутники, але Правило трапеції часто “занижує” значення. Відразу не можна на 100% сказати, яка техніка буде краще для того чи іншого інтегралу. Коректним буде знайти площу за обома техніками, потім знайти абсолютні та відносні похибки обох технік та обрати ту, де похибки менші.</p><p>Ці техніки нечасто зустрічаються, у шкільній та університетських програмах, тому раджу самостійно ознайомитися з ними.</p><p>Це все, дякую, що дочитали, і сподіваюся, комусь допомогла ця стаття. Не соромтеся залишати коментарі, якщо щось незрозуміло.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14755faced90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps: Введення та трансформація даних з TFX]]></title>
            <link>https://medium.com/@mirandorexes/mlops-%D0%B2%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%BD%D1%8F-%D1%82%D0%B0-%D1%82%D1%80%D0%B0%D0%BD%D1%81%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D1%96%D1%8F-%D0%B4%D0%B0%D0%BD%D0%B8%D1%85-%D0%B7-tfx-b62009857c5a?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/b62009857c5a</guid>
            <category><![CDATA[українською]]></category>
            <category><![CDATA[tfx]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 18:03:17 GMT</pubDate>
            <atom:updated>2025-09-12T18:03:17.846Z</atom:updated>
            <content:encoded><![CDATA[<p>Як створюються, тестуються та контролюються моделі машинного навчання у реальних проектах. Розглянемо автоматизацію трансформації даних за допомогою TFX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHeJlCdVfjYl5qiaiR-opw.jpeg" /></figure><h3>Різниця між продуктовим та науковим підходом у ML</h3><p>(І чому на Kaggle не завжди хороші рішення)</p><p>Будь — який алгоритм машинного навчання чи нейромережа залежні від даних, на яких навчаються. У сучасному світі тенденція даних може змінюватися кожну годину, кожен день, тощо, в залежності від області. Від цих змін і залежить якість моделей: зміна середнього значення, розподілу, тощо — призведуть до неможлиості використання моделі, якщо модель не перенавчати кожен раз, як відбувається зміна у даних. MLPOps (ML + DevOps) — це область, яка адаптує DevOps практики для створення, розгортання та підтримки моделей, здатних адаптуватися до змін.</p><p>В чому різниця між MLOps рішеннями та тим, що можна побачити на Kaggle або у наукових есе? Відповідь — статичність даних. Що на Kaggle, що при розробці нових моделей вчені та інженери використовують статичний датасет, для обслуговування якого не треба розробляти окрему інфраструктуру і який достатньо обробити (очистити) один раз. У таких задачах нестатичний датасет і непотрібний, бо мета — це розробка високоякісної моделі, яку можна використовувати в подальшому.</p><p>MLOps якраз і допомагає це зробити — створити “цикл”, завдяки якому можна постійно контролювати якість та стан самої моделі, так і даних, і якщо дані змінилися, модель перенавчається на оновленому датасеті.</p><p>Kaggle хоч і є найбільшою платформою для ML інженерів та аналітиків, але рішення, навіть якщо вони виставляються у змаганнях та посідають перші місця, можуть бути не оптимізовані або навіть не пристосовані для автоматизації.</p><h3>Pipeline та основні етапи розробки у MLOps</h3><p>Pipeline — це спосіб автоматизації всіх процесів (стадій) розробки ML моделей. Тобто, замість інженера кожну ячейку кода (кожен файл), запускає оркестратор. Умовно стадії розробки моделі можна розділити на 4 категорії:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*6gJNUv4mPP_4sJ8F.jpeg" /></figure><ol><li>Scoping — визначення потреб та цілей проєкта. Наприклад: потрібно розробити модель для передбачення ціни на нерухомість. Виходячи з цього, модель повинна вирішувати задачу регресії, а активаційна функція повинна бути лінійною. На цьому ж етапі визначаються з технічними характеристиками проекту: тип бази даних, hardware, тощо. Вибір бази даних залежить від часу, за який потрібно отримати передбачення моделі.</li><li>Data — все про дані. Статистичні показники, відбір потрібних ознак, лейблування, трансформація. На цьому етапі формується розуміння “слабких сторін” даних — статистичних або інших особливостей, що можуть призвести до низької якості моделі. Baseline — це ті показники, які модель може мати (показники якості та помилок). Найчастіше використовується HLP (Human Level Performance — людський показник), який показує наскільки точно людина може виконати поставлену задачу. Наприклад, якщо розробляється модель для детекції раку на знімках, як HLP візьметься точність, з якою лікар може визначити, чи є пухлина. Визначити baseline дуже важливо для розуміння продуктивності моделі.</li><li>Modelling — розробка моделі/моделей, тюнінг, тестування: чи є перенавчання або недонавчання, яка якість на різних класах (для класифікації), тощо.</li><li>Deployment — деплой моделі та створення системи для постійного моніторингу. Моніторинг дає змогу одразу визначити проблеми та зміни у даних , моделя — Drift та Skew.</li></ol><p>Pipeline складається з трьох останній стадій: Data, Modelling, Deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*6EWUnGiU4Spje-Ne.jpeg" /></figure><p>Pipeline є циклічним, Modelling та Deployment повторюють постійно, поки якість моделі не досягне потрібного значення при тестуванні та поки модель обслуговується (коли модель вже використовується користувачами). Результатом виконання кожної стадії є артефакти, які генеруються під час виконання компонентів pipeline та охоплюють усе, створене конвеєром, включаючи дані на різних етапах перетворення, схеми, показники та моделі. Метадані — це дані про інші дані, характеристики, властивості та зв’язки між наборами даних, моделей та інших елементів. Метадані допомагають зрозуміти життєвий цикл даних і керувати ним, відстежувати зміни, виправляти проблеми, забезпечувати відтворюваність і дотримуватись правових і нормативних вимог. Містять таку інформацію, як джерело даних, дата створення, авторство, перетворення даних, параметри навчання моделі тощо. Метадані відіграють вирішальну роль в управлінні даними та сприянні співпраці між науковцями та зацікавленими сторонами.</p><ul><li>Data preparation. Input: дані з бази даних або data lake, output: трансформовані дані (артефакти) та метадата, які завантажуються в окрему базу даних.</li><li>Model Creation. Input: дані та метадата з попереднього кроку, output: модель (артефакт) та метадата.</li><li>Rollout. Input: артефакти з попередніх стадій, output: показники, що відслідковуються (якість, помилки) та метадані.</li></ul><p>Кожний етап пайплайну необхідний та важливий. Не можна забувати також і про важливість моніторингу, який може запобігти “взлому“ моделі. Методи хакінгу моделі можуть здатися, на перший погляд, не дуже елегантними та складними, але вони дієві. Наприклад, якщо додати шум на фотографію кішки та надіслати у класифікатор, точність передбачення або дуже сильно впаде, або передбачення буде зовсім некоректним: фотографію кішки позначить як клас “собака“.</p><h3>Виявлення та моніторинг помилок (Drift та Skew)</h3><p>Колись настане момент, де зміна у даних може призвести до поганих або навіть катастрофічних наслідків. Уявіть, що ви розробляєте модель для аналізу кількості та типів взуття, яке потрібно закупити магазину. У перший рік ваша модель працює дуже добре, магазин закупає рівно стільки взуття, скільки може продати. У наступному році тренд змінюється, покупці хочуть придбати інші моделі взуття, але у магазині їх немає, бо модель не змогла проаналізувати новий тренд. Існує два типи таких помилок (data issue):</p><ul><li>Drift (Data drift, Concept drift) — це зміна у даних з часом, через яку точність моделі падає (Model Decay). Data drift сигналізує про зміну даних у часі: користувач почав надсилати більше повідомлень, але система фіксує це як спам.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*G962LMLapOVn0gsV.jpeg" /></figure><ul><li>Concept drift сигналізує про зміну паттернів та зв’язків даних. Прикладом є зміна патерну між тренувальними та тестувальними даними (зміна ознак).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*LpW4VJq6Qn6CKesu.jpeg" /></figure><ul><li>Skew (Schema skew, Distribution skew) — це різниця між джерелами даних, наприклад, тренувальний та валідаційний набори мають різний розподіл або тип ознак відрізняється (ознака у одному наборі має тип Int, у іншому тип Float). Для різних skew існують різні методи виявлення. Наприклад, для Schema skew (різниця між наборами даних) потрібно порівняти статистичні показники всіх наборів даних.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*gnGTrgrM4-kP_pNy.jpeg" /></figure><p>Distribution skew розділяють на 3 підвиди:</p><ul><li><strong>Covariate Shift: </strong>зміни в розподілі вхідних змінних, на яких навчається модель. — Це відбувається, коли граничний (marginal) розподіл ознак (вхідних змінних) відрізняється між навчальним і валідаційним наборами даних, тоді як умовний (conditional) розподіл залишається незмінним. Наприклад, якщо статистичні властивості ознак змінюються у одному з наборів.</li><li><strong>Concept Shift: </strong>зміна між вхідними та вихідними даними. Відбувається, коли умовний (conditional) розподіл міток (лейблів класів) не є однаковим між навчальним та валідаційним наборами, тоді як граничний розподіл залишається незмінним.</li><li><strong>Dataset Shift</strong>: зміна статистичних властивостей даних. Це включає зміну середовище, де збираються дані, та методів збору.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*a0ix4MotZ-Q_vryZ.jpeg" /></figure><h3>Database, Data Warehouse, Data Lake та Feature Store</h3><p>Що перше приходить на думку, коли уявляєте базу даних? Скоріше за все, віртуальне сховище даних. Але яке саме? Чи можуть там зберігатися дані за якийсь час, або тільки у real — time? Чи ці дані структуровані, чи розташовані у якомусь порядку. Всі ці питання характеризують 4 види місць, що зберігають інформацію (я спеціально не написала баз даних, щоб не ввести у плутанину)</p><ul><li><strong>Бази даних (Database)</strong> — це сховище даних, яке зберігає поточну інформацію, яка доступна в real — time. Максимальний розмір — n гігабіт. Запити прості та виконуються теж в real — time. Для ефективності таблиці треба нормалізують.</li><li><strong>Data Warehouse</strong> — об’єктно — орієнтовані, розроблені для зберігання терабайтів даних та версій даних з часовими мітками. На відміну від баз даних, аналізують та збирають дані з багатьох джерел, але не підтримують запити в real — time, запити мають більш складну будову та виконуються довше, але оптимізовані для читання. Нормалізація не потрібна. Зберігають тільки структуровані дані.</li><li><strong>Data Lake</strong> — використовуються саме для аналізу даних, зберігають як структуровані, та і не структуровані (зображення, музика тощо) дані у raw форматі (необроблені) з декількох джерел. Як і бази даних, можуть зберігати гігабайти даних.</li><li><strong>Feature Store</strong> — центральний репозиторій даних конкретно для ML завдань, є приватними, компанія зазвичай розробляє власний feature store. Якщо коротко описати, то feature store виконує роль репозиторія даних. Доступ до таких сховищ контролюється та може розділятися між командами.. Дозволяють трансформувати дані, видаляють дублікати.</li></ul><p>Такі сховища можуть бути як онлайн, так і офлайн. Офлайн зберігає вже оброблені дані, тоді як для обробки даних онлайн потрібно використовувати батчі.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*AWNV9Q8agI0g0gfb.jpeg" /></figure><h3>Оркестратори</h3><p>Коли я тільки починала вивчати MLOps та побачила слово оркестратор, моя перша думка була: “це ж як дирижер“. І частково, так і є: як і дирижер, оркестратор слідкує за виконанням кожного етапу у чітко визначеній послідовності. Робота оркестратора — це автоматизація пайплайнів та контроль над величезними потоками даних, які надходять у модель, він запускає кожний елемент пайплайну у потрібній послідовності у потрібний час.</p><p>На щастя, кількість оркестраторів все збільшується, і навіть якщо проект працює у маловідомому домені, можна знайти підходящий оркестратор.</p><blockquote><em>Оркестратор є важливим компонентом у будь-якому стеку MLOps, оскільки він відповідає за роботу пайплайнів. Для цього оркестратор забезпечує середовище, налаштоване для виконання кроків вашого пайплайну. Він також гарантує, що кроки вашого пайплайну виконуються лише тоді, коли всі їхні вхідні дані (які є виходами попередніх кроків вашого пайплайну) доступні.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*J_jaUi90C8KnZw1B.jpeg" /></figure><p>Найпопулярнішими оркестраторами є <a href="https://airflow.apache.org/">Airflow </a>та <a href="https://www.kubeflow.org/">Kuberflow</a>. У цій вводній статті я не буду зосереджувати увагу на них, оскільки планує приділити багато часу у наступних.</p><p>А зараз давайте поговоримо про те, як запустити пайплайн без оркестратора. Так, це можливо, але тільки на локальному комп’ютері. Бібліотека TFX, яку буду використовувати, має:</p><ul><li>Середовище <a href="https://www.tensorflow.org/tfx/ml_metadata/api_docs/python/mlmd/proto/Context">Context</a>, де можна запустити окремі елементи пайплайну (про них у наступному розділі). При використанні Context інженеру потрібно самостійно запускати пайплайн, тобто автоматизації немає.</li><li><a href="https://www.tensorflow.org/tfx/api_docs/python/tfx/v1/orchestration/LocalDagRunner">LocalDagRunner</a>, ваш власний оркестратор, автоматизує пайплайн, але тільки на локальному комп’ютері.</li></ul><p>Для демонстрації буду використовувати і той, і той метод.</p><h3>MLOps бібліотеки</h3><p>Найвідоміші та найбільш використовувані бібліотеки — це TFX (Tensorflow), Kuberflow Pipeline (Kuberflow) та MLFlow (Databricks). Коротке порівняння TFX та MLFlow:</p><ul><li><strong>Моніторинг</strong>: MLflow частіше використовують для моніторингу через зручніше систему, тоді як у TFX використовуються метадані, які можна вивести у TensorBoard.</li><li><strong>Моделі</strong>: MLFlow є більш гнучкою, дозволяючи використовувати різні типи моделей, на відміну від TFX, що працює з моделями, створених за допомогою Tensorflow.</li><li><strong>Компоненти Pipeline</strong>: TFX працює тільки з елементами TensorFlow, тоді як MLflow є більш гнучким і може працювати з різними фреймворками ML.</li><li><strong>Портативність</strong>: моделі MLflow можна легко переносити в різні середовища завдяки формату MLmodel. Конвеєри TFX тісніше пов’язані з TensorFlow, їх може бути складніше перенести у потрібне середовище.</li></ul><p>Відмінність Kuberflow Pipeline від попередніх бібліотек у способі побудови пайплайну, а саме у вигляді графів, використовуючи інші бібліотеки. Kuberflow Pipeline найчастіше використовують як оркестратор в інших бібліотеках, а не як засіб для створення pipeline, оскільки для кожного компонента пайплайну потрібно створювати .yaml файл.</p><p>У цій статті я буду використовувати TFX бібліотеку, як на мене, вона більш легка у розумінні.</p><h3>TFX</h3><p>Як говорила раніше, результатом виконання кожного елемента у TFX є артефакти та метадані. Для кожної задачі є окремий компонент:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*f6qEC_R86cVAiSwD.jpeg" /></figure><p>1. <strong>ExampleGen</strong>: завантажує та обробляє необроблені дані, перетворюючи їх у формат, придатний для наступних компонентів. Також розділяє на тренувальний та тестувальні ні нібори.</p><p>2. <strong>StatisticsGen</strong>: обчислює підсумкову статистику набору даних, наприклад середнє значення, медіану, стандартне відхилення та гістограми ознак. Ці статистичні дані мають вирішальне значення для розуміння характеристики даних.</p><p>3. <strong>SchemaGen</strong>: генерує схему для набору даних на основі обчисленої статистики з StatisticsGen. Схема зберігає очікувані типи даних, діапазони та інші обмеження для кожної ознаки.</p><p>4. <strong>ExampleValidator</strong>: перевіряє набір даних на аномалії через SchemaGen та StatisticsGen. У випадку, якщо у наборі даних ознака має інший тип даних, інший діапазон даних, ExampleValidator це реєструє.</p><p>5. <strong>Transform</strong>: перетворення, масштабування, групування, виконує всі перетворення, що потрібні під конкретну задачу.</p><p>6. <strong>Tuner</strong>: компонент для тюнінгу моделі, має схожу з Trainer структуру. Для тюнінгу можуть використовувати алгоритми, не тільки присутні у Tensorflow.</p><p>7. <strong>Trainer</strong>: тут відбувається навчання моделі. Якщо гіперпараметри моделі попередньо отримані у Tuner, буде використовувати саме їх.</p><p>8. <strong>Evaluator</strong>: оцінює продуктивність навчених моделей, використовуючи різні показники. Порівнює продуктивність різних моделей і допомагає визначити найефективнішу для деплою.</p><p>9. <strong>InfraValidator</strong>: перевіряє проблеми сумісності, обмеження ресурсів та інші проблеми, пов’язані з деплоєм.</p><p>10. <strong>Pusher</strong>: відповідає за деплой моделі, якщо вона проходить перевірку та відповідає необхідним критеріям якості, інтегрується з такими платформами, як TensorFlow Serving, TensorFlow Lite, TensorFlow.js і TensorFlow Hub.</p><p>TFDV є окремою бібліотекою, але частиною TFX, яку також використовують самостійно для попереднього аналізу даних, а також для зміни схеми. Не потребує оркестратора для роботи. У багатьох туторіалах використовують TFDV як заміну TFX, але безпосередньо для пайплайнів вона вже не підходить, окрім зміни схем.</p><h3>Data Transform via TFX</h3><p>Повний код: <a href="https://www.kaggle.com/code/annack/data-transformation-and-eda-with-tfx?scriptVersionId=180667855">https://www.kaggle.com/code/annack/data-transformation-and-eda-with-tfx?scriptVersionId=180667855</a></p><p>Датасет складається з 16 ознак, які формують ціну автомобіля, ключову ознаку.</p><p>Перш за все, потрібно визначити звідки та куди будуть йти дані та артефакти, метадані зберігаються окремо.</p><pre># location of the pipeline metadata store<br>_pipeline_root = &#39;kaggle/working/pipeline/&#39;</pre><pre># directory of the raw data files<br>_data_root = &#39;/kaggle/input/car-price-prediction-challenge&#39;</pre><p>Далі, в залежності від виду середовища, визначити його. Спочатку хочу показати за допомогою Context.</p><pre>#create context aka local env in TFX<br>context = InteractiveContext(pipeline_root=_pipeline_root)</pre><h3>ExampleGen</h3><p>Перетворення raw даних у формат, який може обробляти елементи TFX та розділення на тренувальний та тестовий набори.</p><pre>#transform raw data in required format for next stages<br>example_gen=CsvExampleGen(input_base=_data_root) <br>context.run(example_gen)</pre><p>Після успішного виконання можна передивитися інформацію про створений артефакт.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UiExlhX1AIJ4YJSt.jpeg" /></figure><p>Створений артефакт та метадаys зберігаються у окремих папках, що створюються за вказаною адресою (_pipeline_root).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*y8mra9v5cvs6ezhB.jpeg" /></figure><p>Індивідуальні екземпляри не можна взяти безпосередньо з компонента, потрібно писати допоміжну функцію, у мене це def get_records(dataset, num_records), що повертає лист.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*CXEKCbToQI3z2Ig2.jpeg" /></figure><h3>StatisticsGen</h3><p>Генерація статистики для всіх наборів даних, в цьому випадку — для тренувального та тестового наборів.</p><pre>statistics_gen=StatisticsGen(examples=example_gen.outputs[&quot;examples&quot;])<br>context.run(statistics_gen)</pre><p>Аналогічно з ExampleGen, після виконання з’являється інформація про створені артефакти. Для візуалізації створеного артефакта існує наступна команда:</p><pre>context.show(statistics_gen.outputs[&quot;statistics&quot;])</pre><p>Зверніть увагу, що артефакти знаходяться у outputs.</p><p>У вікні візуалізації можна подивитися розподіл, середнє, чи є пропущені дані або знайти інформації щодо конкретної ознаки.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0RQnRTlwGLhnjyr.jpeg" /></figure><h3>SchemaGen</h3><p>Створює схему (таблицю) з типом, доменами та можливими значеннями/діапазонами ознак.</p><pre>schema_gen=SchemaGen(statistics=statistics_gen.outputs[&quot;statistics&quot;],infer_feature_shape=True)<br>context.run(schema_gen)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*FAk3N9duqtmE5YIs.jpeg" /></figure><p>Завдяки схемі відстежуються drift та skew у даних. Стовбець “Presence“ відповідає за перевірку наявності ознак, якщо у ознаки є мітка “required“, то ознака повинна бути в усіх наборах даних, а у випадку, якщо ознака відсутня, при перевірці з ExsmpleValidator буде помилка.</p><p>Виникає резонне питання: скільки схем повинно бути всього, чи потрібно створювати окремо схему для кожного набору даних? Це залежить від задачі. Для supervised навчання зазвичай створюється одна схема для всіх наборів даних, щоб не пропустити drift чи skew. Тоді виникає наступне питання, що робити з target ознакою (Y матриця, яка містить цільову ознаку у тренувальному наборі), оскільки що в тестувальному та валідаційному, що в даних, отриманих від користувача, цільової ознаки не буде? Треба дати “зрозуміти“ пайплайну, що відсутність цільової ознаки не є помилкою, тобто, зміни мітку з “required“ на “optional“. Скажу чесно, я доволі довго шукала, як це зробити, бо гайдів дуже мало. Ось спосіб, що знайшла:</p><ul><li>Отримати розташування згенерованої схеми</li></ul><pre>schema_path = os.path.join(schema_gen.outputs[&quot;schema&quot;].get()[0].uri, &#39;schema.pbtxt&#39;) <br>#only showing training as an example</pre><ul><li>Завантажити за допомогою TFDV.Це самий той випадок, до використання TFDV безпосередньо в пайплайні є доцільним.</li></ul><pre>import tensorflow_data_validation as tfdv<br>schema=tfdv.load_schema_text(schema_path)<br></pre><pre>#Створити папку для оновленої схеми<br>_updated_schema_dir = &quot;/kaggle/working/kaggle/working/pipeline/UpdatedSchema&quot;<br># Create the new directory for updated schema<br>!mkdir -p {_updated_schema_dir}</pre><ul><li>Змінити min_fraction та зберегти min_fraction відповідає за “кількість“ ознаки у даних, якщо потрібно менше 100% (1) ознаки, то вона вважається опціональною.</li></ul><pre>#get target feature<br>price_feature = tfdv.get_feature(schema, &#39;Price&#39;)<br>price_feature.ClearField(&#39;shape&#39;)<br>#change target presence to 0.5 - change field to &quot;optional&quot;<br>price_feature.presence.min_fraction= 0.5<br>tfdv.display_schema(schema)<br>#write new schema<br>tfdv.write_schema_text(schema, os.path.join(&quot;/kaggle/working/kaggle/working/pipeline/UpdatedSchema&quot;, &#39;schema.pbtxt&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*g6MgDIynPt2Ch3Zz.jpeg" /></figure><ul><li>Якщо не видалити розмірність ознаки, під час трансформації буде наступна помилка:</li></ul><pre>price_feature.ClearField(&#39;shape&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*wAH_jf-uxQKZbE9O.jpeg" /></figure><ul><li>Додати оновлену схему до метаданих. Щоб використовувати будь — які імпортовані компоненти, вони повинні бути в сховищі метаданих. Цей пункт вкрай важливий, але мало де можна знайти його використання.</li></ul><pre># Use an ImporterNode to put the curated schema to ML Metadata<br>from tfx.v1.dsl import Importer<br>from tfx.types import standard_artifacts<br>user_schema_importer = Importer(<br>    source_uri=&quot;/kaggle/working/kaggle/working/pipeline/UpdatedSchema&quot;,<br>    artifact_type=standard_artifacts.Schema)<br># Run the component<br>context.run(user_schema_importer, enable_cache=False)</pre><ul><li>user_schema_importer має всі ті є властивості, що і стандартна схема:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oUyUAT5h_Ic61e1_.jpeg" /></figure><h3>ExampleValidator</h3><p>Перевірка на drift та skew за допомогою створеною схеми.</p><pre>example_validator=ExampleValidator(statistics=statistics_gen.outputs[&quot;statistics&quot;],schema=user_schema_importer.outputs[&#39;result&#39;])<br>context.run(example_validator)</pre><p>Тут на вхід подається артефакти одразу двох компонентів: статистика та схема.</p><pre>context.show(example_validator.outputs[&quot;anomalies&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*kkqU3THE2DaGRc_r.jpeg" /></figure><p>Жодних аномалій не знайдено, оскільки датасет був цілісний, а не розділений не різні набори одразу.</p><h3>Transform</h3><p>Тут відбуваються всі перетворення даних: нормалізація, feature cross, тощо. Щоб спростити, числові ознаки та цільову ознаку (Price) нормалізую, а категоріальні закодую через аналог one — hot encodding. Цей компонент, як і подальші, використовують користувацькі інструкції — окремий файл, в якому знаходиться весь код для обробки даних.</p><p>Спершу потрібно створити файл, де ознаки будуть розділені по групам. Для більшою гнучкості ознаки та трансформація розділені по різним файлах</p><pre># Set the constants module filename<br>transformation_file_constant = &#39;user_tranformation_constant_.py&#39;</pre><pre>%%writefile {transformation_file_constant}<br>categorical_features=[&quot;Category&quot;,&quot;Color&quot;,&quot;Doors&quot;,&quot;Drive wheels&quot;,&quot;Engine volume&quot;,&quot;Fuel type&quot;,&quot;Gear box type&quot;,&quot;Leather interior&quot;,&quot;Levy&quot;,&quot;Manufacturer&quot;,&quot;Mileage&quot;,&quot;Model&quot;,&quot;Wheel&quot;]<br>numerical_features=[&quot;Airbags&quot;,&quot;Cylinders&quot;,&quot;ID&quot;,&quot;Prod. year&quot;]<br># Feature that the model will predict<br>label_key = &#39;Price&#39;<br># Utility function for renaming the feature<br>def transformed_name(key):<br>    return key + &#39;_xf&#39;</pre><p>Перевіримо, чи коректні ознаки у числовій групі</p><pre>import user_tranformation_constant_<br>user_tranformation_constant_.numerical_features</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*Ks-_fYUsuK3x0e7D.jpeg" /></figure><p>Далі, створюємо сам файл для обробки.</p><pre># Set the transform module filename<br>_transformation_module_file = &#39;user_tranformation_module.py&#39;</pre><pre>%%writefile {_transformation_module_file}</pre><pre>import tensorflow as tf<br>import tensorflow_transform as tft<br>import pandas as pd<br>import user_tranformation_constant_</pre><pre># Unpack the contents of the constants module<br>_NUMERIC_FEATURE_KEYS = user_tranformation_constant_.numerical_features<br>_CATEGORICAL_FEATURE_KEYS = user_tranformation_constant_.categorical_features<br>#_FLOAT_INT_FEATURE_KEYS = User_tranformation_constant.numerical_features<br>_LABEL_KEY = user_tranformation_constant_.label_key<br>_transformed_name = user_tranformation_constant_.transformed_name</pre><pre># Define the transformations<br>def preprocessing_fn(inputs):<br>    &quot;&quot;&quot;tf.transform&#39;s callback function for preprocessing inputs.<br>    Args:<br>        inputs: map from feature keys to raw not-yet-transformed features.<br>    Returns:<br>        Map from string feature key to transformed feature operations.<br>    &quot;&quot;&quot;<br>    outputs = {}</pre><pre>    # Scale these features to the range [0,1]<br>    for key in _NUMERIC_FEATURE_KEYS:<br>        outputs[_transformed_name(key)] =  tft.scale_to_0_1(<br>            inputs[key])<br>        <br>  <br>    outputs[_transformed_name(_LABEL_KEY)]=tft.scale_to_0_1(inputs[_LABEL_KEY])</pre><pre>    for key in _CATEGORICAL_FEATURE_KEYS:<br>        # Ensure the feature is treated as a string<br>        string_feature = tf.strings.as_string(inputs[key])<br>        #tf.print(&quot;Processing feature:&quot;, key, &quot;with shape:&quot;, tf.shape(string_feature))<br>        <br>        # Reshape the tensor to remove the extra dimension if necessary<br>        string_feature_flat = tf.squeeze(string_feature, axis=-1)<br>        #tf.print(&quot;Flattened feature shape:&quot;, tf.shape(string_feature_flat))<br>        <br>        # Apply vocabulary transformation<br>        transformed_feature = tft.compute_and_apply_vocabulary(<br>            string_feature_flat, <br>            default_value=-1,  # Specify a default value for out-of-vocabulary tokens<br>            num_oov_buckets=1  # Specify the number of out-of-vocabulary buckets<br>        )<br>        <br>        outputs[_transformed_name(key)] = transformed_feature<br>        #tf.print(&quot;Transformed feature:&quot;, key, &quot;with shape:&quot;, tf.shape(transformed_feature))<br>        <br>    return outputs</pre><p>При енкодування категоріальних ознак обов’язково треба прибирати зайві розмірності:</p><pre>string_feature_flat = tf.squeeze(string_feature, axis=-1)</pre><p>Аналогічно з попередніми компронентами, Transform запускається через context. На вхід подаються самі дані з ExampleGen, схема та файл трансформацій.</p><pre>tf.get_logger().setLevel(&quot;ERROR&quot;)<br>transform = Transform(<br>    examples=example_gen.outputs[&#39;examples&#39;],<br>    schema=user_schema_importer.outputs[&#39;result&#39;],<br>    module_file=os.path.abspath(_transformation_module_file))<br>context.run(transform)</pre><p>Артефактів з цього компонента набагато більше, ніж з попередніх.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-SQqCZrISZ7ibPbq.jpeg" /></figure><p>Видаляти цільову ознаку з тестувального набору буду під час тюнінгу у наступній статті.</p><h3>Пайплайн на локальному оркестраторі LocalDagRunner()</h3><p>LocalDagRunner() є “міні — версією“ оркестратора для локального комп’ютера.</p><p>Всі ті ж самі компонети, що і в попередньому розділі, але замість запуску кожного окремо, запускаються автоматизовано.</p><pre>_metadata_path=&quot;/kaggle/working/kaggle/working/pipeline/metadata.sqlite&quot;<br>_pipeline_name=&quot;car-price-pred-challenge&quot;<br>_schema_path=&quot;/kaggle/working/kaggle/working/pipeline/UpdatedSchema&quot;<br>def _create_pipeline(pipeline_name:str,pipeline_root: str, data_root: str, <br>                     metadata_path: str,schema_path:str) -&gt; tfx.dsl.Pipeline:<br>    <br>    example_gen = tfx.components.CsvExampleGen(input_base=data_root)</pre><pre>  # Computes statistics over data for visualization and example validation.<br>    statistics_gen = tfx.components.StatisticsGen(<br>      examples=example_gen.outputs[&#39;examples&#39;])</pre><pre>  # import updated schema<br>    schema_importer = Importer(<br>    source_uri=schema_path,<br>    artifact_type=standard_artifacts.Schema<br>)</pre><pre>  <br>    example_validator = tfx.components.ExampleValidator(<br>      statistics=statistics_gen.outputs[&#39;statistics&#39;],<br>      schema=schema_importer.outputs[&#39;result&#39;])<br>    <br>    transform = Transform(<br>        examples=example_gen.outputs[&#39;examples&#39;],<br>        schema=schema_importer.outputs[&#39;result&#39;],<br>        module_file=os.path.abspath(_transformation_module_file))<br>    <br>    components = [<br>      example_gen,<br>      statistics_gen,<br>      schema_importer,<br>      example_validator,<br>      transform<br>      ]</pre><pre>    return tfx.dsl.Pipeline(<br>      pipeline_name=pipeline_name,<br>      pipeline_root=pipeline_root,<br>      metadata_connection_config=tfx.orchestration.metadata<br>      .sqlite_metadata_connection_config(metadata_path),<br>      components=components)</pre><p><em>metadata_path_ </em>автоматично створюється у коренній папці пайплайну.</p><p>Після визначення пайплайну запускаємо його через оркестратор:</p><pre>tfx.orchestration.LocalDagRunner().run(<br>  _create_pipeline(<br>      pipeline_name=_pipeline_name,<br>      pipeline_root=_pipeline_root,<br>      data_root=_data_root,<br>      metadata_path=_metadata_path,<br>      schema_path=_schema_path))</pre><p>Для візуалізації окремого компоненту потрібно мати додаткову функцію:</p><pre>from tfx.orchestration.portable.mlmd import execution_lib<br>def get_latest_artifacts(metadata, pipeline_name, component_id):<br>  &quot;&quot;&quot;Output artifacts of the latest run of the component.&quot;&quot;&quot;<br>  context = metadata.store.get_context_by_type_and_name(<br>      &#39;node&#39;, f&#39;{pipeline_name}.{component_id}&#39;)<br>  executions = metadata.store.get_executions_by_context(context.id)<br>  latest_execution = max(executions,<br>                         key=lambda e:e.last_update_time_since_epoch)<br>  return execution_lib.get_output_artifacts(metadata, latest_execution.id)</pre><p>Вона завантажує результат виконання потрібного компонента з бібліотеки MLMD — бібліотеку метадати TFX. Далі, з’єднуємося з MLMD та визначаємо, який саме компонент потрібно отримати. Я хочу вивести результат StatisticsGen:</p><pre>from tfx.orchestration.metadata import Metadata<br>from tfx.types import standard_component_specs<br>metadata_connection_config = tfx.orchestration.metadata.sqlite_metadata_connection_config(<br>    _metadata_path)</pre><pre>with Metadata(metadata_connection_config) as metadata_handler:<br>    <br>    ev_output = get_latest_artifacts(metadata_handler, _pipeline_name,<br>                                   &#39;StatisticsGen&#39;)<br>    anomalies_artifacts = ev_output[standard_component_specs.STATISTICS_KEY]</pre><p>Змінна anomalies_artifacts містить всі дані про артефакт.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*-DRkVW1p5aK1QRPL.jpeg" /></figure><p>І для візуалізації створюю ще одну додаткову функцію:</p><pre># Non-public APIs, just for showcase.<br>from tfx.orchestration.experimental.interactive import visualizations</pre><pre>def visualize_artifacts(artifacts):<br>  &quot;&quot;&quot;Visualizes artifacts using standard visualization modules.&quot;&quot;&quot;<br>  for artifact in artifacts:<br>    visualization = visualizations.get_registry().get_visualization(<br>        artifact.type_name)<br>    if visualization:<br>      visualization.display(artifact)</pre><pre>from tfx.orchestration.experimental.interactive import standard_visualizations<br>standard_visualizations.register_standard_visualizations()</pre><pre>visualize_artifacts(anomalies_artifacts)</pre><p>Отримаю те ж саме віконечко з статистикою, що і при запуску на context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KuwXPrD9kXm2lTie.jpeg" /></figure><p>Дякую, що прочитали! У наступній статті про тюнінг, тренування та валідацію моделі.</p><h3>Джерела для подальшого вивчення</h3><p><a href="https://towardsdatascience.com/machine-learning-orchestration-vs-mlops-d4cfe3b7bec">Machine Learning Orchestration vs MLOps</a></p><p><a href="https://medium.com/data-for-ai/feature-store-vs-data-warehouse-306d1567c100">Feature Store vs Data Warehouse</a></p><p><a href="https://medium.com/exness-blog/the-best-orchestration-tool-for-mlops-a-real-story-about-difficult-choices-5ee6a087c9e3">The best orchestration tool for MLOps: a real story about difficult choices</a></p><p><a href="https://medium.com/exness-blog/the-best-orchestration-tool-for-mlops-a-real-story-about-difficult-choices-5ee6a087c9e3">SELECTING YOUR OPTIMAL MLOPS STACK: ADVANTAGES AND CHALLENGES</a></p><p><a href="https://towardsdatascience.com/4-challenges-of-reproducibility-in-the-machine-learning-model-deployment-3b4ca7b975c8">4 Challenges of Reproducibility in the Machine Learning Model Deployment</a></p><p><a href="https://saschaheyer.medium.com/tensorflow-extended-101-literally-everthing-you-need-to-know-aeecc51e6832">TensorFlow Extended 101: (literally) Everything you need to know</a></p><p>Курс та спеціалізація: <a href="https://www.deeplearning.ai/courses/machine-learning-in-production/">https://www.deeplearning.ai/courses/machine-learning-in-production/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b62009857c5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Класифікація 101: Низька якість, ансамблювання та незбалансовані класи]]></title>
            <link>https://medium.com/@mirandorexes/%D0%BA%D0%BB%D0%B0%D1%81%D0%B8%D1%84%D1%96%D0%BA%D0%B0%D1%86%D1%96%D1%8F-101-%D0%BD%D0%B8%D0%B7%D1%8C%D0%BA%D0%B0-%D1%8F%D0%BA%D1%96%D1%81%D1%82%D1%8C-%D0%B0%D0%BD%D1%81%D0%B0%D0%BC%D0%B1%D0%BB%D1%8E%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F-%D1%82%D0%B0-%D0%BD%D0%B5%D0%B7%D0%B1%D0%B0%D0%BB%D0%B0%D0%BD%D1%81%D0%BE%D0%B2%D0%B0%D0%BD%D1%96-%D0%BA%D0%BB%D0%B0%D1%81%D0%B8-02ad43bc88b0?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/02ad43bc88b0</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[class-imbalance]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 14:53:15 GMT</pubDate>
            <atom:updated>2025-09-04T14:53:15.298Z</atom:updated>
            <content:encoded><![CDATA[<p>Я розпочинаю серію статей, присвячених задачі класифікації. Формат “101” взятий з американської навчальної програми, де таким номером позначають вхідні курси, курси рівня junior. Для прикладу буду використовувати свій проект з кеглевського змагання, який увійшов у перші 45%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToK2q2iSRNFuQ5R_Q5NzFQ.jpeg" /></figure><h3>Розділювальна площина (гіперплощина)</h3><p>Виходячи з назви, основна ціль задачі класифікації — віднести конкретні дані до конкретного класу, але як саме це можна зробити, і чому навіть найскладніші нейронні мережі не мають 99% точності?</p><p>Уявіть, що вам треба відсортувати 10 книг різних жанрах по 5 жанрах. Скоріше за все, ви прочитаєте короткий опис кожної книги, візуально оціните обкладинку, можливо, прочитаєте про автора. Опис, обкладинка та автор — це ознаки, за яким буде проводитися сортування.</p><p>Задача класифікації в машинному навчанні має схожу, але більш математичну реалізацію. Основна мета якої — побудувати розділювальну площину з мінімальним значенням функції помилки. Все ще звучить доволі просто, еге ж? Але давайте подивимося на те, що таке навчальні дані насправді.</p><p>Для навчання нейромережі потрібно мати датасет, який складається з n-кількості ознак. Разом ознаки (features) формують простір ознак, кількість вимірів якого і є головним викликом, кількість вимірів = кількості ознак. Розглянемо на прикладі: маємо датасет з 2 ознак: гендер 1 та гендер 2, задача — класифікувати дані по класам. Даний датасет є двовимірним, оскільки має 2 ознаки.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*AUtVxkBxWUTEgpGv.jpeg" /></figure><p>Наведена задача є задачею бінарної класифікації, про неї — далі. Розділювальна функція (червона пунктирна лінія), по якій алгоритм буде класифікувати, є лінійною, тобто, щоб вирішити дану задачу можна використати найпростіший алгоритм — логістичну регресію. На перший погляд, все просто, але датасети для реальних задач можуть мати 50, 100, 500 вимірів.</p><h3>Велика розмірність — великі проблеми</h3><p>Дві основні проблеми в даних, через які алгоритм або нейромережа мають низьку точність — це кількість вимірів та форма.</p><p>Почну з першої проблеми — багатовимірність. Уявіть, що ви заблукали в печері, який шанс вийти з печери, маючи 2 або 200 ходів? Багатовимірність призводить до довшого часу навчання, перенавчання моделі, та прокляття багатовимірності (феномен Хьюза):</p><ul><li>Чим більше розмірності матриць, тим більше ресурсів потрібно на операції з ними</li><li>Модель не можу узагальнювати (generalization)</li><li>У багаторозмірних площинах неймовірно складно знайти відстань від однієї точки даних до іншої, у випадку класифікації це феномен Хьюза: чим більше вимірів, тим легше знайти розділювальну поверхню під час тренування, але в той же час, тим важче моделі зробити узагальнення (generalization).</li></ul><p>Задля оптимізації та візуалізації використовують методи Зменшення розмірності (Dimensionality reduction), такі як PCA, MDS та інші. Основний принцип їх роботи — перенести кожний екземпляр, кожну точку даних, у простір меншої розмірності, зазвичай 2- 3 вимірних.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*Lsu_XulGDX38j5OR.jpeg" /></figure><p>Методи Зменшення розмірності є дуже важливою частиною feature engineering, їм буде присвячений окремий довгочит.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vvlEUNo9dPw5V_an.jpeg" /></figure><p>Друга проблема — це форма даних, в залежності від неї інженер обирає метод Зменшення розмірності: лінійний або нелінійний. Для розділення даних у багатовимірних просторах потрібно побудувати розділювальну площину. Чи може ця площина бути нелінійною, наприклад, розділити дані на малюнку зліва? Теоретично — так, але це вже виходить за рамки поняття розділювальної площини та не використовується у машинному навчанні.</p><p>На прикладі дані 2-х вимірні дані зліва переводять у 3-х вимірний простір, у якому можна побудувати розділювальну площину.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s-txr1pIZyLp9AeZ.jpeg" /></figure><p>Варто зазначити, що алгоритми Зниження розмірності є частиною feature engineering, тобто, якщо ви маєте непотрібні ознаки, які можна видалити або застосувати feature cross, то це потрібно зробити.</p><h3>Model — driven vs data — driven approach</h3><p>Існує два підходи до побудови моделі: приділити більше часу обробці та перетворення даних або зробити мінімальну обробку даних, натомість зосередити всі сили на розробці потужної та оптимізованої моделі. Кожний підхід має свої переваги та недоліки, в залежності від поставленої задачі. Особисто я прихильниця data — driven і ось чому:</p><ul><li>Брак потужностей: щоб побудувати складну та точну модель, яка може опрацьовувати великовимірні датасети, потрібна величезна кількість даних, більший час навчання, складніший тюнінг та оптимізація, навіть якщо використовувати квантизацію та інші ефективні методи.</li><li>Проблема узагальнення: навіть найкращі моделі, наприклад, той же ChatGPT мають bias на окремі теми — упередженість щодо національності, раси, тощо.</li><li>Створити високоточну модель для необроблених в більшості випадків набагато складніше та ресурсоємно, ніж обробити дані.</li></ul><h3>Ентропія</h3><p>Ентропія випадкової величини X — це рівень невизначеності, притаманний можливому результату змінної.</p><p>Звучить абстрактно, але зараз стане зрозуміліше. Спершу, розглянемо приклад: визначимо ймовірність діставання фігур різного типу з контейнера.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*WyBUFrvZAwZ1yVrZ.jpeg" /></figure><p>Контейнер 1: Ймовірність витягнути трикутник становить 26/30, а ймовірність витягнути коло — 4/30.</p><p>Контейнер 2: Ймовірність витягнути трикутник становить 14/30 і 16/30 у випадку кола. Ймовірність вибору певної форми майже 50 на 50. Впевненість у виборі фігури менша, ніж у випадку 1.</p><p>Контейнер 3: Ймовірність витягнути коло становить 29/30, а ймовірність витягнути трикутник — 1/30. З високою ймовірністю можна стверджувати, що вибрана фігура буде колом.</p><p>В якому з цих трьох випадках можна бути максимально впевненим у передбаченні того, яку фігуру витягнете? Інтуїтивно у випадку 3, що і підтверджує ентропія.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*yp46CrUZ_Li9wwDI.jpeg" /></figure><p>Простими словами ентропія — це показник передбачуваності. Чим менший показник ентропії, тим впевненіше можна бути.</p><h3>Ентропія як функція втрат</h3><p><em>Ця частина присвячена класифікації за допомогою тільки нейромереж, методи машинного навчання, що використовуються для класифікації, працюють за іншими принципами.</em></p><p>Важливо пам’ятати різницю між функцією втрат та оптимізатором. Функція втрат оцінює різницю між класом (лейблом) та передбаченим нейромережею значенням, тоді як оптимізатор змінює ваги (матриця W) під час Backpropagation для знаходження мінімума функції втрат. Всі активаційні функції для класифікації повертають вірогідність конкретного класу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*fJt_tyzqZetjiDMd.jpeg" /></figure><p>Але як можна оцінити точність передбачення нейромережі, якщо це вірогідність? Чи можна просто відняти вірогідність від лейблу? Перш за все, якщо просто віднімати, вірогідність стає звичайним числом, що нічого не оцінює. Якщо ж оцінювати передбачену вірогідність за формулою ентропії, отримаємо показник “впевненості в передбаченні’’. Для більшого розуміння розрахуємо ентропію для цієї передбаченої ймовірності та справжнього класу:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*iXp9OJTuBXway32j.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*RssPeDO6p7Vv-7hg.jpeg" /></figure><p>Ентропія у 0.3677 є показником того, що нейромережа не дуже “впевнена’’ у власному передбаченні. Перевіримо вірогідність для наступної епохи:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*GZGkcqvlGgWu_QAk.jpeg" /></figure><p>Значення ентропії знизилося (вірогідність правильного класу, першого, стала вищою) — нейромережа навчається.</p><h3>Categorical Cross-Entropy vs Sparse Categorical Cross-Entropy</h3><p>В залежності від вигляду, в якому подаються класи (лейбли) до нейромережі базується вибір функції ентропії. Що категоріальна, що спарс ентропія використовують однакову формулу ентропії.</p><ul><li>Categorical Cross-Entropy: якщо лейбли у вигляді one — hot вектора, тобто справжній клас позначений 1, всі інші класи позначені як 0. Наприклад, ваш датасет складається з 3 класів: собаки, коти, папуги. Фотографія, де є собака, буде мати вектор [клас собака, клас кіт, клас папуга] = [1,0,0].</li><li>Sparse Categorical Cross-Entropy: якщо лейбли — це номер класу, 1,2,3…, тощо.</li></ul><p>На практиці рекомендується все ж використовувати лейбли у вигляді one — hot вектора, бо між векторами немає зв’язку. Наприклад, якщо ваші лейбли нумерувалися у довільному порядку, клас “1“ — це хліб, клас “2“ — собака, нейромережа може ‘’подумати’’, що між собакою та хлібом є зв’язок.</p><h3>Ансамблювання</h3><p>Пам’ятаєте шкільну гру “Що? Де? Коли?”? Моя команда часто їздила на змагання, і саме там я зрозуміла цінність командної роботи. Ансамблювання працює за схожим принципом — об’єднуючі результати кількох моделей, можна підняти якість передбачення, знизити variance, bias, підняти рівень генералізації (узагальнення) навіть на даних з шумом.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f3XP7pBCeiitGc2y.jpeg" /></figure><h3>Як обрати моделі для ансамблювання?</h3><p>Є два підходи: Гомогенний — ансамблювання моделей однакового типу, та гетерогенний — ансамблювання моделей різного типу.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*CspGA9Tf0arvQurn.jpeg" /></figure><p>Гомогенне ансамблювання реалізовано в двух алгоритмах: Bagging та Boosting</p><h3>Bagging</h3><p>Гомогенне ансамблювання, зменшує variance.</p><p>Навчання: Паралельне навчання</p><p>Приклад: Random Forest</p><p>Цей метод передбачає навчання декількох екземплярів моделі на різних підмножинах навчальних даних, створених за допомогою bootstrapping (випадкової вибірки із заміною).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*fqDe6GCRDkaN2uW2.jpeg" /></figure><p>Bootstrapping дозволяє тренувати модель на незалежних підмножинах (samples) датасету, не знаючи реального розподілу даних, тим самим підвищуючи узагальнення. Bootstrap-вибірки часто використовуються для оцінки дисперсії або довірчих інтервалів статистичних оцінок, оскільки кожна вибірка є незалежною.</p><p>Умовно можна розділити на дві частини: Bootstrapping та Aggregating (те, що по суті і є ансамблювання)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bhrwKDWY3A59wnxB.jpeg" /></figure><p>Є два види фінальної функції (частина Aggregating), яка зводить результат передбачення всіх моделей: для задачі регресії — це середнє зважене, для класифікації — голосування (voting), hard — voting, коли передбачений клас — це той клас, який спрогнозували (передбачили) більшість моделей, soft — voting, спрогнозованим класом є клас з найбільшої середньої ймовірністю.</p><h3>Boosting</h3><p>Гомогенне ансамблювання, зменшує bias</p><p>Навчання: Послідовне навчання.</p><p>Приклад: XGBoost, LightGBM</p><p>Моделі навчаються послідовно, при цьому кожна нова модель фокусується на помилках попередніх. Ідея полягає в ітеративному підборі моделей таким чином, щоб навчання моделі на даному кроці залежало від моделей, підібраних на попередніх кроках.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pYyzR-TWUE5BTlAO.jpeg" /></figure><p>Кожній одиниці даних датасету присвоюється вага, неправильно класифіковані точки отримують більшу вагу в наступних ітераціях. Оскільки boosting є ітеративним методом, його найкраще використовувати на shallow моделях, ніж на великих та складних. На відміну від bagging, тут передбачення видає остання модель, фінальної функції немає.</p><h3>Stacking</h3><p>Гетерегенне ансамлювання, зменшує bias</p><p>Навчання: кожна модель навчається незалежно</p><p>Для Stacking моделі можуть навчатися як паралельно, так і послідовно. Вважається найбільш потужним алгоритмом, оскільки дає можливість використовувати різні типи моделей, а замість фінальної функції використовується мета-модель, яка оброблює передбачення вже навчених моделей.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*caBiJ3noAnpElDI6.jpeg" /></figure><p>Важливим моментом ансамблювання є те, що вибір моделей повинен узгоджуватися зі способом поєднання цих моделей. Якщо обираються базові моделі з низьким bias, але високою variance, то це має бути метод ансамблювання, який має тенденцію до зменшення дисперсії (variance), тоді як якщо обираються моделі з низькою дисперсією, але високим зміщенням (bias), то це має бути метод ансамблювання, який має тенденцію до зменшення bias. Алгоритми машинного навчання з низькою дисперсією включають лінійну регресію, логістичну регресію та лінійний дискримінантний аналіз (LDA). До алгоритмів з високою дисперсією відносяться Random Forest, SVM і KNN.</p><h3>Незбалансовані класи</h3><p>Незбалансовані датасети мають нерівну кількість елементів у класах і без належної обробки (або використання методів, які можуть оброблювати незбалансовані класи — Random Forest) можуть призвести до перенавчання або недонавчання.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*KZdyztD4G-Z4QMF5.jpeg" /></figure><p>Уявімо, що маємо незбалансований датасет, на якому потрібно навчити класифікатор для розпізнавання пухлини. Датасет містить 90% фотографій пацієнтів без пухлина та 10% з пухлиною. При використання оригінального датасету для навчання модель, скоріше за все, буде класифікувати, а точніше просто виводити результат “пухлини немає“, без обробки паттернів у даних. Грубо кажучи, замість нейромережі отримаємо програму, яка буде виводити в консоль “пухлини немає“.</p><p>Для навчання робастного класифікатора найбільш популярними методами є методи додавання даних до малих класів (OverSampling) або зниження кількості елементів всіх класів до кількості елементів найменшого класу (Undersampling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*avc3huddwY505k6U.jpeg" /></figure><p>Вибір який з методів використовувати залежить від конкретної ситуації, але в більшості випадків Undersampling не обирають, бо він приводить до втрати даних.</p><h3>Steel Plate Defect Prediction Competition</h3><p>Мій повний код можете знаходиться <a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling#Weighted-Average-Ensembling-NN">тут</a>.</p><h3>Обробка даних</h3><p>Мета змагання — розробити класифікатор для класифікації подряпин по 7 класам. Оригінальний датасет має 34 ознаки, це не 200, але і не 3, необхідно спробувати зменшити кількість ознак.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*ZTxFlMomVmEV1VY_.jpeg" /></figure><p><strong><em>Кореляція</em></strong></p><p>Деякі ознаки мають високу кореляцію — одну ознаку можна виразити через іншу. Кореляція не дає змогу зрозуміти, наскільки важливі ознаки, тим самим зменшуючи інтерпретованість моделі — розробнику складно зрозуміти, через які ознаки модель має низьку точність та як можна покращити. Інтерпретованість неймовірна важлива та цікава тема, про яку розповім в наступних довгочитах, присвячених вже MLOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k8eEbeHXoddMySIA.jpeg" /></figure><p>Деякі семпли (одиниці даних датасету) мають одразу декілька міток класів, а деякі не мають міток взагалі, що фактично робить з багатокласової класифікації multilabel класифікацію. Деякі розробники вирішили будувати саме multilabel модель, але я вирішила залишитися у багатокласовій класифікації.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*liWNrK1W5NK9hPLw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*yhTu0tkM8Nxreceb.jpeg" /></figure><p>Для вирішення цієї проблеми зробила наступне:</p><ul><li>Залишити тільки одну мітку — Other_faults у семплів, що мають декілька лейблів.</li><li>Семпли, які не мають подряпин видалила. Можна припустити, що вони потрапили у датасет помилково.</li></ul><h3>Feature Engineering</h3><p>Датасет має 13 ознак, перетворивши які можна зменшити розмірність даних. Наприклад, віднявши від X_maximun Y_minimum знаходиться ранжування, тобто, з двох ознак створюється спільна, тим самим позбавляючи кореляції.</p><pre>def calculate_coordinate_range_features():<br>        data[&#39;X_Range&#39;] = (data[&#39;X_Maximum&#39;] - data[&#39;X_Minimum&#39;])<br>        data[&#39;Y_Range&#39;] =( data[&#39;Y_Maximum&#39;] - data[&#39;Y_Minimum&#39;])<br>        data.drop([&quot;X_Maximum&quot;,&quot;Y_Minimum&quot;,&quot;X_Minimum&quot;,&quot;Y_Maximum&quot;], axis=1, inplace=True)</pre><p>Функція<a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling?scriptVersionId=169428218&amp;cellId=24"> def feature_engineering(data)</a> є прикладом nested функції.</p><p>Після застосування залишилося 22 ознаки.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*r4RU83edDsq_-St6.jpeg" /></figure><p>Привидення ознак до одного діапазону (scaling) є необхідною процедурою для деяких алгоритмів, але майже завжди не є зайвою, оскільки допомагає пришвидшити навчання. Робила за допомогою RobustScaler, окремо для тестової та тренувальної вибірки.</p><pre>from sklearn.preprocessing import RobustScaler<br>train = train_x_featENG.astype(np.float64)<br>test = test.astype(np.float64)<br>test=feature_engineering(test)<br>scaler = RobustScaler()<br>train_scaling = scaler.fit_transform(train)<br>test_scaling = scaler.transform(test)</pre><p>Вибір саме такого скейлера обумовлений тим, що дані мають викиди.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*xkNBZajHkYjao0Sc.jpeg" /></figure><h3>Незбалансовані класи</h3><p>Для балансування класів обрала техніку збільшення малих класів — OverSample, оскільки кількість даних і так невелика, щоб додатково зменшувати через UnderSample.</p><pre>from imblearn.over_sampling import RandomOverSampler<br>ros = RandomOverSampler(sampling_strategy=&#39;auto&#39;, random_state=42)<br>sampling_y=train_y.to_numpy()<br>X_res, y_res = ros.fit_resample(train_scaling, sampling_y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*2l4AfKNuKIm0OTxi.jpeg" /></figure><h3>Візуалізація та зменшення розмірності</h3><p>Hypertools — бібліотека для геометричної візуалізації багатовимірних даних, на відміну від PCA, що є технікою Зменшення розмірності. Що перший, що других алгоритм показують, що розділювальну площину буде побудувати не так вже й просто.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*UbiAOvGzCpXtyPR3.jpeg" /></figure><p>Вирішила не використовувати дані, на яких будувала PCA задля чистоти експерименту ансамблювання.</p><h3>Ансамблювання</h3><p>Я зробила для варіанти ансамблювання:</p><ul><li>Зведення результатів двох boosting методів, XGBoost та LightGBM за допомогою VotingClassifier, що є майже bagging методом</li><li>Weighted Average ансамблювання двох нейромереж за допомогою мета — моделі, спрощений Stacking, бо я люблю експерементувати.</li></ul><p><strong>VotingClassifier</strong></p><p>Для цієї реалізації попередньо зробила тюнінг XGBoost моделі, проте LightGBM модель залишила з мануальними параметрами (для LightGBM тюнінг не робила, оскільки всі можливі GPU в Кегглі вже використала, без них тюнінг неймовірно довгий).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*S4BtQ3_Z-eJJoBRb.jpeg" /></figure><p>Для VotingClassifier необхідним параметром є ваги, які в моєму випадку є ROC-AUC оцінкою двох моделей: чим нижче точність моделі, тим менший її вплив на передбачення.</p><pre>def evaluate_models(models, X_train, X_val, y_train, y_val):<br> # fit and evaluate the models<br>     scores = list()<br>     for model in models:<br> # fit the model<br>         model.fit(X_train, y_train)<br> # evaluate the model<br>         yhat = model.predict_proba(X_val)<br>         acc = roc_auc_score(y_val, yhat)<br> # store the performance<br>         scores.append(acc)<br> # report model performance<br>     return scores<br>from sklearn.ensemble import VotingClassifier<br>models=[LGBMClassifier(**parameters_dict),XGBClassifier(**c)]<br>scores = evaluate_models(models, X_train, X_test, y_train, y_test)<br># create the ensemble<br>ensemble = VotingClassifier(estimators=[(&#39;lr&#39;, LGBMClassifier(**parameters_dict)), (&#39;rf&#39;, XGBClassifier(**c))], voting=&#39;soft&#39;, weights=scores)</pre><p>Обрала soft — voting, оскільки ансемблюю тільки дві моделі. Точність на тестувальному наборі довольна висока, точність на валідаційному, по якому оцінюються учасники змагання, нижча.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*LVXu1DBjP3msZMU3.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*-pzoOYMgYOcxkFhD.jpeg" /></figure><p><strong>WeightedAverage Ensembling + skip — connections NN</strong></p><p>WeightedAverage є простим методом ансамблювання.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*z-027k0SXK-BUGW9.jpeg" /></figure><p>Так, передбачаючі запитання, я додала вельми відомі skip — connections до однієї з двох ансамблевих нейромереж, такі зв’язки допомагають градієнту не затухати. Повна схема дуже велика, можете подивитися <a href="https://www.kaggle.com/code/annack/steel-plate-defect-prediction-ensembling?scriptVersionId=169428218&amp;cellId=74">тут</a>. Блок skip — connections виглядає наступним чином:</p><pre>def skip_connection(previous_layer):<br>    def skip():<br>        start = layers.Dense(256, activation=&quot;leaky_relu&quot;)(previous_layer)<br>        dense_0 = layers.Dense(256, activation=&quot;leaky_relu&quot;)(start)<br>        dense_1 = layers.Dense(256, activation=&quot;leaky_relu&quot;)(dense_0)<br>        dense_2 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_1)<br>        dense_3 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_2)<br>        batch_norm = layers.BatchNormalization()(dense_3)<br>        dense_4 = layers.Dense(128, activation=&quot;leaky_relu&quot;)(batch_norm)<br>        concat = keras.layers.Concatenate(axis=1)([start, dense_4])<br>        #batch_norm_1 = layers.BatchNormalization()(concat)<br>        outputs = layers.Dense(128, activation=&quot;leaky_relu&quot;)(concat)<br>        return outputs<br>    return skip()</pre><p>Повна структура першої нейромережі:</p><pre>inputs = keras.Input(shape=(X.shape[1],))<br>dense_1=layers.Dense(256, activation=&quot;leaky_relu&quot;)(inputs)<br>dense_2=layers.Dense(512, activation=&quot;leaky_relu&quot;)(dense_1)<br>#batchNorm_1=layers.BatchNormalization()(dense_2)<br>s=skip_connection(dense_2)<br>dropout=tf.keras.layers.Dropout(0.2)(s)<br>s2=skip_connection(dropout)<br>dropout_2=tf.keras.layers.Dropout(0.3)(s2)<br>s3=skip_connection(dropout_2)<br>dropout_3=tf.keras.layers.Dropout(0.2)(s3)<br>#s4=skip_connection(dropout_3)<br>#dropout_4=tf.keras.layers.Dropout(0.3)(s4)<br>dense_3=layers.Dense(256, activation=&quot;leaky_relu&quot;)(dropout_3)<br>dense_3_1=layers.Dense(128, activation=&quot;leaky_relu&quot;)(dense_3)<br>dense_4=layers.Dense(7, activation=&quot;softmax&quot;)(dense_3_1)</pre><pre>model = keras.Model(inputs=inputs, outputs=dense_4,name=&quot;skip_conn_model&quot;)</pre><p>Задля швидшого навчання друга модель має дуже просту архітектуру, без skip — connections:</p><pre>inputs = keras.Input(shape=(X.shape[1],))<br>dense_1=layers.Dense(256, activation=&quot;elu&quot;)(inputs)<br>dense_2=layers.Dense(512, activation=&quot;elu&quot;)(dense_1)<br>batchNorm_1=tf.keras.layers.Dropout(0.4)(dense_2)<br>#s=skip_connection(batchNorm_1)<br>#dropout_2=tf.keras.layers.Dropout(0.4)(s)<br>dense_3=layers.Dense(512, activation=&quot;elu&quot;)(batchNorm_1)<br>dense_3_1=layers.Dense(256, activation=&quot;elu&quot;)(dense_3)<br>dropout_2=tf.keras.layers.Dropout(0.2)(dense_3_1)<br>dense_3_2=layers.Dense(128, activation=&quot;elu&quot;)(dropout_2)<br>dense_4=layers.Dense(7, activation=&quot;softplus&quot;)(dense_3_2)</pre><pre>model1 = keras.Model(inputs=inputs, outputs=dense_4,name=&quot;light_model&quot;)</pre><p>Оптимайзер для обох моделей — Adam, метріка — AUC.</p><p>Перенавчання моделей, які довго вчиш дуже неприємна річ, тому найкращі ваги зберігаю за допомогою checkpoints у моделі після навчання. У деяких статтях можна побачити зберігання найкращих вагів через EarlyStopping, але це неправильно.</p><pre>def checheckpoints(model):<br>    path=&#39;/kaggle/working/Weights_&#39;+model.name+&#39;.weights.h5.keras&#39;<br>    checkpoint = tf.keras.callbacks.ModelCheckpoint(path, <br>                    monitor=&quot;val_loss&quot;, mode=&quot;min&quot;, <br>                    save_best_only=True, verbose=10)<br>    return checkpoint,path<br>callback =  tf.keras.callbacks.EarlyStopping(<br>    monitor=&quot;val_loss&quot;,<br>    patience=10<br>)</pre><p><strong>Результати навчання</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*fErnep5EMwjUAiG9.jpeg" /></figure><p>Друга, простіша модель, на моє здивування показала набагато кращі результати.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*Ar2YOaQyh66KHQMh.jpeg" /></figure><p>Перенавчання почалося на 40 епосі, до цього, функція помилки рівномірно спадала.</p><p>Такі результати добре показують, що першу модель треба спростити, або додати регуляризацію. В реальних проектах, моделі звичайно треба тюнінгувати. Аналогічно з першим варіантом, як ваги для ансамлювання використала ROC — AUC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*5Zlhw6C6NL9TJMWO.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*ADgzBRhjhItTpAPR.jpeg" /></figure><p>Блок усереднення передбачення двох моделей.</p><pre>class WeightedAverage(Layer):</pre><pre>    def __init__(self):<br>        super(WeightedAverage, self).__init__()<br>        <br>    def build(self, input_shape):<br>        <br>        self.W = self.add_weight(<br>                    shape=(len(input_shape),),<br>                    initializer=weight_init,<br>                    dtype=tf.float32,<br>                    trainable=True)<br>    def call(self, inputs):<br>    <br>        inputs = [tf.expand_dims(i, -1) for i in inputs]<br>        inputs = Concatenate(axis=-1)(inputs) <br>        weights = tf.nn.softmax(self.W, axis=-1)</pre><pre>        return tf.reduce_mean(weights*inputs, axis=-1)</pre><p>Мета модель має наступний вигляд:</p><pre>inputs = Input(shape=(X.shape[1],), name=&#39;inputs&#39;)  # input layer<br># get output for each input model<br>outputs = [model(inputs) for model in models] <br># take average of the outputs<br>x = WeightedAverage()(outputs) </pre><pre>x = layers.Dense(512, activation=&#39;leaky_relu&#39;)(x)<br>x = tf.keras.layers.Dropout(0.4)(x) <br>x = layers.Dense(256, activation=&#39;leaky_relu&#39;)(x) <br>x = layers.Dense(128, activation=&#39;leaky_relu&#39;)(x) <br>x = tf.keras.layers.Dropout(0.4)(x) <br>x = layers.Dense(128, activation=&#39;leaky_relu&#39;)(x) <br>x = layers.Dense(64, activation=&#39;leaky_relu&#39;)(x) <br>output = layers.Dense(7, activation=&#39;softmax&#39;, name=&#39;output&#39;)(x) # output layer</pre><pre># create average ensembled model<br>avg_model = keras.Model(inputs, output)</pre><p>Що ж, експеримент наразі є не дуже успішним, але я планую продовжити намагатися підвищити точність іншими методами.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*bCSknjPoknkY3c4c.jpeg" /></figure><p>Можливе пояснення — це проблема в самому датасеті, тобто потрібно змінити тактику feature engineering, та спробувати синтетичні дані.</p><h3>Складний випадок: minority class 0.17%</h3><p>Недавно мені попався дуже цікавий та складний датасет: <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud">Fraud Detection</a>. Цікавий він в першу чергу неймовірно малим minority класом. У таких випадках багато алгоритмів може сприймати менший клас як шуми, тобто класифікувати всі транзакції як 0, тобто безпечні. В <a href="https://www.kaggle.com/code/annack/fraud-prediction-high-recall-nn-and-ensemble">кеглі </a>описали більш детально.</p><p><a href="https://www.kaggle.com/code/annack/fraud-prediction-high-recall-nn-and-ensemble">Fraud Prediction|| High Recall NN and Ensemble</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*S5v4nQgfkeSycPdBkFyQGw.png" /><figcaption>Результати тюнінг нейромережі</figcaption></figure><p>Пройдуся швидко по основним пунктам та моїм рішенням:</p><ul><li>Робити EDA краще як на повному датасеті, так і на семплі (семпл це частина датасета, де класи мають рівну пропорцію 50/50), але confusion matrix треба дивитися тільки по семплу, оскільки кореляції можуть бути не помітні на всьому датасеті.</li><li>Видалення outliers: Найкращим рішенням буде перевірити кілька методів. Один з найкращих — це видаляти викиди дивлячись на ознаки з великою позитивною та негативною кореляціями. Такі популярні методи як Isolation Forest видаляють більшу частину меншого класу, оскільки вважають їх за викиди.</li><li>Train/Test Split: якщо потрібно test, val, test сети, потрібно спочатку розділити на трейн, тест, потім розділити на трейн та валідаційний. Так data leakage буде меншим.</li><li>TSNE: дуже корисний інструмент для візуалізації розподілу даних, навіть на таких незбалансованих датасетах.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*GGzD4t1ZhTvLRJc1Z_TwXg.png" /></figure><ul><li>Тюнінг наше все: незалежно від моделі, тюнінг обо’язковий. У випадку дисбалансу краще додавати ваги класів та початкову ініціалізацію (нейромережі) самостійно. Для нейромереж на базі Tenserflow — Keras Tuner, для інших моделей — Optune (user- friedly, not very flexible: нова модель — нова функція) або HyperOpt (повільніша, може давати трошки гірші результати, але більш flexible).</li><li>Метрики та функція втрат. Функцію втрат краще обирати дивлячись на те, наскільки сильна незбалансованість, якщо дуже сильна — використовувати balanced loss function. Метрики: recall(цей датасет) або precision — дивлячись на те, що потрібно трекати:true negative або false positive. Для тюнінга краще використовувати val prc, val auc — збірні метрики precision, recall.</li></ul><p><strong><em>Дякую за прочитання! Буду дуже рада відповісти на всі запитання.</em></strong></p><h3>Корисні посилання</h3><ul><li><a href="https://semaphoreci.medium.com/how-to-handle-imbalanced-data-for-machine-learning-in-python-b6d56c9a0489">Як опрацьовувати незбалансовані класи?</a></li><li><a href="https://pub.aimind.so/never-use-restore-best-weights-true-with-earlystopping-754ba5f9b0c6">Як правильно зберігати найкращі ваги моделі?</a></li><li><a href="https://towardsdatascience.com/bias-and-variance-for-model-assessment-a2edb69d097f">Bias Variance Decompositional</a></li><li><a href="https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205">Ансамблеві методи</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02ad43bc88b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ресурси для вивчення ML, AI, математики та англійської]]></title>
            <link>https://medium.com/@mirandorexes/%D1%80%D0%B5%D1%81%D1%83%D1%80%D1%81%D0%B8-%D0%B4%D0%BB%D1%8F-%D0%B2%D0%B8%D0%B2%D1%87%D0%B5%D0%BD%D0%BD%D1%8F-ml-ai-%D0%BC%D0%B0%D1%82%D0%B5%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B8-%D1%82%D0%B0-%D0%B0%D0%BD%D0%B3%D0%BB%D1%96%D0%B9%D1%81%D1%8C%D0%BA%D0%BE%D1%97-151859fb4001?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/151859fb4001</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 14:21:34 GMT</pubDate>
            <atom:updated>2025-09-04T14:21:34.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRcDYhsRvXJhaAlhvcDM5Q.jpeg" /></figure><p>Почну з того, що всі перелічені вище області не є легкими для опанування, для їх повного вивчення треба витратити не один рік. Я розділила матеріали на 3 рівня у кожній категорії: початковий, середній, просунутий, щоб кожен читач зміг знайти матеріали за своїм рівнем. Також я додала деякі ресурси українською.</p><p>Одразу наголошу, що як бакалавр прикладної математики я вже маю необхідну “базу“, тому більшість ресурсів зосереджена на 2–3 рівні.</p><p>Всі перераховані нижче курси та спеціалізації я закінчила, або проходжу зараз, їх не дуже багато, але я впевнена в їх якості.</p><p><strong><em>Стаття буде доповнюватися…</em></strong></p><h3>Англійська</h3><p>Ця частина найдовша, якщо вам цікаві тільки ресурси — переходьте у кінець.</p><p>Я не є професійним лінгвістом, вивчення мов та неврологія — моє хобі. Спосіб, про який я розказую далі — це мій власний досвід та знання, що знайшла у відкритих джерелах.</p><h3>Англійська — стежка до сучасної науки</h3><p>На питання чому важливо її знати більшість відповість для комунікації. І це вірно, але окрім цього більшість наукових робіт, статей, відео перекладаються або пишуться на англійській. Без її знання складно вивчити новий алгоритм/метод/теорему. Постає питання, чи не простіше вивчати це на російській, якщо немає на українській? Я не буду зачіпляти тему повної неетичності вивчення мовою ворога та те, що чим більше читати російською, тим більше інформації нею підсовують пошукові алгоритми, що у свою чергу створює інформаційну бульбашку. Російська наука, як і російське техно — кубло є відсталим: вони придумують “нові“ закони та теореми, виставляючи це як щось проривне, хоча це існує вже не один десяток років; на жаль, це не заважає їм покращувати ракети. Найяскравіший приклад — діагноз “ВСД“, який не має визнання у міжнародній медичній спільноті, але при тому у нас був дуже поширений, що призвело до неправильного лікування цілого покоління.</p><h3>Як правильно вчити нову мову?</h3><p>Зараз я вчу 4 мови: англійську, польську, фінську та німецьку, і допоміг мені в цьому спосіб нижче.</p><p>Розкажу коротку історію моїх невдалих спроб вивчення англійської у школі. Протягом всіх шкільних років я мала величезну проблему з вивченням англійської, я шульга з гарною пам’яттю (як казали, це повинно було пришвидшити вивчення), але на слух англійську сприймати не могла взагалі, а граматика була нудною. На 1 курсі університету з’явилася потреба читати англомовні статті, моя англійська покращилася до рівня strong B1, але слухати будь — що англійською я все ще не могла. Після 2 курсу почала шукати наукові методи вивчення мов, щоб вони не забувалися через пару місяців. І таким чином я відкрила для себе вивчення англійської через призму неврології. <strong>Детальніше про це дуже </strong><a href="https://www.youtube.com/watch?v=Kzv6IfLTWdU"><strong>раджу послухати у цієї прекрасної авторки</strong></a><strong>.</strong></p><p>При вивченні будь — якої мови задіюються 3 елементи: слух, говоріння та мислення (цей симбіоз, до речі, і є частковим стопором від деменції). Зі слухом і говорінням все ясно, але як щодо мислення? Кожна мова має часи, але не у всіх мовах їх однакова кількість. Наприклад, в українській 3 часи, в англійській — 2, Present Simple та Past Simple (Continuous та Perfect є аspects, а не tenses). Мозок починає думати у двох та трьох часах, що поліпшує когнітивні процеси, що в свою чергу, з часом, веде до швидшого та якіснішого володіння мовою.</p><p>Секрет лежить у тому, як вчать мову діти. Дитину з перших днів не вчать граматиці, а показують та називають оточуючі предмети, коли дитина трохи підростає, їй пояснюють емоції та основні концепції, і тільки у школі або садочку дитина починає вчити граматику. Одразу зазначу, граматику вчити необхідно, але починати вивчення мови з неї не варто. Через такий метод дитина починає думати на мові та відчувати її. Принцип на основі цього я і використала для вивчення англійської: почала з того, що переклала назви всіх предметів у кімнаті на англійську, потім почала дивитися дитячі передачі та мультики, читати дитячу художню літературу (на жаль, Толкін писав складніше) та прості статті по програмуванню. <strong>Основний фокус: вчити іноземну мову не через рідну мову, а з нуля та оточити себе нею.</strong></p><p>Після 2 місяців таких занять я мала змогу читати статті по ML та математиці, з яких вивчила терміни та те, як вивчають математику у західних країнах (вона доволі сильно відрізняється від нашої). Переді мною ніби з’явилася нова, таємнича галактика, сповнена секретів, які я нарешті могла розгадати.</p><p>Зараз, після майже 2 років вивчення таким методом, можу майже спокійно розуміти як американську, так і британську англійську (і не тільки лондонський акцент) та маю рівень C2 за EF SET.</p><h3>Лінгвістичне дерево або як перекладати без перекладу</h3><p>Як відбувається переклад, якщо вчити іноземну мову через рідну? Уявіть лінгвістичне дерево як алгоритм або рослину. У корні дерева знаходиться ваша рідна мова.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*cZUDiJ2QakIXV2Ka.jpeg" /></figure><p>Спочатку мозок думає на рідній мові, потім намагається перекласти на англійську з урахуванням меншої кількості часів та граматики. Не дуже швидкий шлях, чи не так? А якщо додати ще одну мову? Наприклад, якби б я вчила фінську через англійську?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1rvLxzdx4AuDtpkK.jpeg" /></figure><p>І ось, шлях до перекладу на фінську збільшився в 3 рази.</p><p>При вивченні іноземної самостійно, не через рідну або іншу іноземну мову, картинка зміниться.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/0*k5jFgdAHHOMgBd4r.jpeg" /></figure><p>Мозок буде переключатися між мовами, ніби між режимами. Так, такий спосіб більш просунутий на початку, але набагато дієвіший — забути вивчену мову складно.</p><p>Коли я читаю чи слухаю на англійській, то не маю фази “я перекладаю ось це слово на українську“ : слова ніби матеріалізуються у свідомості, я розумію значення слова без перекладу на українську. Просто, спокійно та природньо.</p><h3>Постійність — шлях до успіху</h3><p>На жаль, постійність найважливіша частина вивчення будь — чого. Ви можете займатися пару годин одного дня, закинути на тиждень, і в результаті все забути. Метод “вчити як дитина“ буде працювати та давати хороші результати тільки з постійним перебуванням у англомовному середовищі. Будьте в ньому хоча б годину в день і через місяць побачите неймовірний результат.</p><h3>Британський vs американський англійський. З якого починати?</h3><p>Особисто для мене американська англійська простіша через те, що у школі та університеті викладали саме її, як думаю і для багатьох. На мою думку, починати простіше з неї: більшість ресурсів, які я зустрічаю, написані або ведуться саме нею.</p><p>Я не можу зарахувати себе до лав любителів американської англійської, мені не подобається вимова, простота слів, тощо. Вже рік я самостійно вивчаю британську англійську, вимову, сленг та акценти у різних регіонах, і можу з впевненістю сказати — вона набагато складніша.</p><p>Перед тим, як переходити далі, пропоную вам пройти <a href="https://www.efset.org/">цей тест</a>, щоб знати свій рівень англійської. Він безкоштовний та базується на системі оцінювання IELTS. Має тести на 15 та 50 хвилин, не оцінює speaking та writing.</p><h3>Застосунки</h3><p><strong>Рівень A1 — A2:</strong></p><p>Duolingo — вивчення у ігровій формі.</p><p>Memrise — також вивчення у ігровій формі, але з акцентом на діалоги.</p><p><strong>Рівень A2-B2:</strong></p><p>Knudge.me — для запам’ятовування слів та базової граматики через флеш — картки. Підходить і для С1.</p><p>IELTS Prep — завдання міжнародного тесту IELTS: тести, граматика, словниковий запас. Підходить і для С1.</p><p>LingQ — англійська на слух, словник, граматика.</p><p>British Council Grammar — граматика на граматичні тести. . Підходить і для С1.</p><h3>Посібники</h3><p>Є для всіх рівнів.</p><p>Oxford University Press — особисто для мене найкраща серія посібників. Включає посібники для вивчення граматики та аудіювання.</p><p>Cambridge University Press. Популярні серією посібників “Grammar in Use“. Ці посібники більш зосереджені на граматиці та словниковому запасі. Мають також гарну серію для підготовки до IELTS.</p><p>В Україні купую на сайті (не реклама) <a href="https://www.britishbook.ua/?gclid=CjwKCAiAk9itBhASEiwA1my_60RqOzOQGlDOHIlmVEh88G4Bw8DRelg7YgQNdoPDqjfy_6631rYCfxoCwgIQAvD_BwE">British Books </a>, тут найбільша збірка проф. посібників не тільки для вивчення, але й для підготовки до всіх міжнародних екзаменів, також багато англомовної художньої літератури. Ціни найдешевші з усіх книжкових магазинів, що знаю.</p><h3>Серіали та фільми англійською</h3><p>На жаль, тут варіантів не сильно багато.</p><p>Netflix — 7 євро в місяць, можливість підключення до 4 девайсів. Всі серіали, фільми, шоу, мають мінімум українські субтитри, більшість мають український професійний дубляж.</p><p>Prime Video — також 7 євро в місяць, український дубляж мають пару фільмів та серіалів, українські субтитри — приблизно у 30%.</p><h3>Канали</h3><p><a href="https://www.youtube.com/@EnglishClass101"><strong>Learn English with EnglishClass101.com</strong></a><strong> — </strong>американська англійська<strong>, </strong>гарно підходить для початківців.</p><p><a href="https://www.youtube.com/@bbclearningenglish"><strong>BBC Learning English</strong></a><strong> — </strong>британська англійська<strong>, </strong>гарно підходить для початківців.</p><p><a href="https://www.youtube.com/@englishprosto"><strong>Англійська по-простому!</strong></a><strong> — </strong>україномовний канал вчителя англійської, ідеально для вивчення базової граматики.</p><p><a href="https://www.youtube.com/@EnglishSpeakingSuccess"><strong>English Speaking Success</strong></a><strong> — </strong>добре для рівня B1 і вище. Граматика, вимова та підготовка до IELTS.</p><p><a href="https://www.youtube.com/@EnglishAddict/videos"><strong>English Addict with Mr Duncan</strong></a><strong> — </strong>дивний, але забавний ведучий, також підходить для рівня B1 та вище.</p><p><a href="https://www.youtube.com/@voalearningenglish"><strong>VOA Learning English</strong></a><strong> — </strong>канал більше сфокусований на вивченні англійської на слух, підійде для А2.</p><p><a href="https://www.youtube.com/@EnglishTestBlog/featured"><strong>EnglishTestBlog.com</strong></a><strong> </strong>— англійська для смолл — токів, базова граматика та тести. Підійде для рівнів А1 — В1.</p><p><a href="https://www.youtube.com/@priggish_english"><strong>priggish_english</strong></a><strong> — </strong>україномовний канал викладачки. Також вона має телеграм — канал, куди часто публікує посібники. Ідеально для початківців.</p><p><a href="https://www.youtube.com/@EnglishwithLucy"><strong>English with Lucy</strong></a><strong> — </strong>обожнюю всім серцем. Більше підходить для рівнів В1 і вище. Одна з небагатьох викладає граматику та сленг для рівнів С1- С2.</p><p><a href="https://www.youtube.com/@Ieltsadvantage/videos"><strong>IELTS Advantage</strong></a><strong> — </strong>підготовка до IELTS, розбір граматики, розбір помилок на інтерв’ю учасників IELTS. Підходить для рівнів з B1.</p><h3>Спеціалізації по ML та AI від світових університетів безкоштовно</h3><p>Якщо ви є студентом українського університету, маєте можливість отримати доступ до величезної кількості курсів та спеціалізації у різних областях. Освітній хаб Coursera 2 роки тому створила програму Ukraine Response, яка містить курси, спеціалізації та проєкти по окремим темам.</p><p>Для реєстрації потрібно використати пошту з доменом університету та факультету (ту, яку маєте в Teams). При успішній реєстрації повинні бачити хаб університету ( на ньому всі курси безкоштовні) та глобальний хаб (на ньому курси платні).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*aozZlq_mlkZbHODS.jpeg" /></figure><p>Якщо ви хочете взяти курс з глобального хабу, але не маєте змоги оплатити вартість курсу, можете запросити фінансову підтримку.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UxuytoCEXoiaWDKi.jpeg" /></figure><p>В 95% випадків фінансову допомогу надають, чекати рішення потрібно 2 тижні.</p><h3>З чого почати вивчення ML та AI?</h3><p>З базових алгоритмів та теорії обчислень. Ідеальний курс для цього — <a href="https://www.youtube.com/watch?v=8mAITcNt710">Harvard CS50</a>. Як першу мову рекомендую обрати саме Python. Всі ресурси по ML та AI викладаються саме на цій мові, більшість компанії пишуть алгоритми саме на ній. Знати Python — все одно що знати англійську: проста для входження, використовується у багатьох сферах, ідеальна для вивчення алгоритмів та подальшого вивчення більш складних мов як C++ та C#.</p><p><strong>Ранжування для ML/AI зробила опираючись на складність використовуваних методів:</strong></p><p>Простий рівень — алгоритми машинного навчання (ML).</p><p>Середній рівень — нейромережі (AI), алгоритми тюнінгу та оптимізації моделей машинного навчання.</p><p>Просунутий рівень — Generative AI, LLM, MLOps, тюнінг та оптимізація нейромереж.</p><p>Оптимізація є окремою областю, що входить у Computer Science, тюнінг є частиною AI області. Їх складність обумовлена використанням складних математичних алгоритмів.</p><h3>ML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*1UIXS9vPW7DX47p2.jpeg" /></figure><p>Більшість ресурсів підходять для вивчення ML та AI одночасно, але буду копіювати для простішого використання меню.</p><h3>Спеціалізації та курси</h3><p>Не мають українського перекладу, але мають субтитри.</p><p><strong>Початковий рівень</strong></p><p><a href="https://www.coursera.org/specializations/machine-learning-introduction">Machine Learning Specialization</a> — база, грунт, основа, фундамент. Цю спеціалізацію веде Ендрю Ин — засновник Coursera та професор Стенфордського університету, за сумісництвом якого спеціалізація і розроблена.</p><p><a href="https://www.coursera.org/learn/machine-learning-introduction-for-everyone">Machine Learning Introduction for Everyone</a> — курс від IBM, гарний для початку, але не зрівняється з першим варіантом.</p><p><strong>freeCodeCamp.org — </strong>містить курси для початківців майже по всім напрямам IT.</p><p><strong>Середній та </strong>просунутий <strong>рівень:</strong></p><p>Більшість алгоритмів, які складають базу для ML є доволі простими, а те, що часто класифікують як advenced ML algorithms є нейромережами.</p><p>Тому, до середнього та складного рівня я віднесу оптимізацію та тюнінг базових моделей.</p><p><a href="https://www.coursera.org/learn/advanced-machine-learning-signal-processing">Advanced Machine Learning and Signal Processing</a> — курс від IBM присвячений оптимізації, більш складним моделям машинного навчання та обробці сигналів.</p><h3>Канали</h3><p><strong>Ідеально для початківців:</strong></p><p><a href="https://www.youtube.com/@freecodecamp"><strong>freeCodeCamp.org </strong></a><strong>— </strong>окрім цілого списку, присвяченого ML, також роблять класні та креативні проєкти. Цей канал є частиною freeCodeCamp.org.</p><p><strong>Для початків та вище:</strong></p><p><a href="https://www.youtube.com/@Fireship"><strong>Fireship</strong></a><strong> — </strong>ідеальна візуалізація терміну “технарський канал“. Тут ви знайдете все, від алгоритмів та реалізації ігор до алгоритмів машинного навчання.</p><p><a href="https://www.youtube.com/@mitocw"><strong>MIT OpenCourseWare</strong></a><strong> — </strong>публічні записи лекцій університету MIT. На каналі записи зі всіх лекцій, тому потрібно шукати по потрібним темам.</p><p><a href="https://www.youtube.com/@AndrejKarpathy/videos"><strong>Andrej Karpathy</strong></a><strong> — </strong>вчений та розробник багатьох алгоритмів штучного інтелекту.</p><p><a href="https://www.youtube.com/@AAmini"><strong>Alexander Amini</strong></a><strong> — </strong>записи лекцій MIT.</p><p><a href="https://www.youtube.com/@YannicKilcher"><strong>Yannic Kilcher</strong></a><strong> — </strong>креативний розробник, гарно пояснює наукові тези.</p><p><a href="https://www.youtube.com/@robmulla"><strong>Rob Mulla</strong></a><strong> — </strong>реалізує та пояснює популярні алгоритми машинного навчання та штучного інтелекту.</p><p><a href="https://www.youtube.com/@DavesSpace"><strong>Dave’s Space</strong></a><strong> — </strong>неймовірно цікавий технічний канал, присвячений багатьом областях.</p><p><a href="https://www.youtube.com/@sentdex"><strong>sentdex</strong></a><strong> — </strong>автор зосереджен на реалізація ML та AI алгоритмів та моделей з нуля, без використання фреймворків.</p><p><a href="https://www.youtube.com/@aihouse_ukraine"><strong>AI HOUSE</strong></a><strong> — </strong>УКРАЇНСЬКИЙ ПОДКАСТ ПРО ШТУЧНИЙ ІНТЛЕКТ. Пробачте за капслок, обожнюю всім серцем.</p><h3>Книги</h3><p>Залізне правило, яке я вивчила — найкращі книги видає видавництво O’Reilly. Більшість книг не мають українського перекладу, а паперовий тираж має доволі велику ціну.</p><p><strong>Початковий рівень:</strong></p><p><em>Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition</em>, Aurélien Géron, 2019 рік.</p><p><em>Introduction to Machine Learning with Python, Andreas C. Müller &amp; Sarah Guido </em>Версія є у відкритому доступі на англійській — <a href="https://www.nrigroupindia.com/e-book/Introduction%20to%20Machine%20Learning%20with%20Python%20(%20PDFDrive.com%20)-min.pdf">посилання</a>.</p><p><strong>Середній рівень:</strong></p><p><em>Machine Learning Design Patterns</em>, Valliappa Lakshmanan, Sara Robinson, Michael Munn.</p><p><em>AI and Machine Learning for Coders</em>, Laurence Moroney. Коротко про цього автора. Як Ендрю Ин — база для ML/AI, так цей пан база для вивчення MLOps та оптимізації. Його курс у наступній частині.</p><p>Просунутий рівень:</p><p><em>Machine Learning, Optimization, and Data Science Algorithms for Optimization</em>, <a href="https://mitpress.mit.edu/author/mykel-j-kochenderfer-18773">Mykel J. Kochenderfer</a> and <a href="https://mitpress.mit.edu/author/tim-a-wheeler-28144">Tim A. Wheeler</a></p><p><em>Hyperparameter Tuning for Machine and Deep Learning with R</em></p><h3>Статті</h3><p>Всі наведені нижче сайти містять статті як початкового рівня, так і просунутого.</p><p><strong>Безкоштовні</strong></p><p><a href="https://machinelearningmastery.com/category/algorithms-from-scratch/">machine learning mastery</a> — багато інформації та зручний сайт. У розділі категорії можна обрати тему, що вам потрібно.</p><p><a href="https://www.kdnuggets.com/">Kdnuggets</a> — цей сайт часто позиціонують як “безкоштовний аналог Medium“</p><p><a href="https://www.datacamp.com/search-resources">DataCamp</a> — один з найякісніших безкоштовних сайтів.</p><p><a href="https://www.analyticsvidhya.com/blog/">Analytics Vidhya </a>— загалом непоганий ресурс, особисто користуюся ним доволі рідко, бо у статтях занадто мало теорії. Але гарний ресурс для початківців.</p><p><strong>Потребують підписки</strong></p><p><a href="https://medium.com/">Medium </a><strong>— </strong>найбільша блог платформа, має як безкоштовні статті, так і ті, що можна прочитати тільки з підпискою. Medium надає свій домен для створення спільнот, моя найулюбленіша — <a href="https://towardsdatascience.com/">Towards Data Science</a>: багато теорії, багато математики, але за підпискою.</p><p>Вартість підписки 5$, якщо у вас є можливість, підпишіться — не пожалкуєте.</p><h3>AI</h3><h3>Курси та спеціалізації</h3><p>Не мають українського перекладу, але мають субтитри.</p><p><strong>Початковий рівень:</strong></p><p><a href="https://www.coursera.org/specializations/deep-learning">Deep Learning Specialization</a> — Викладає, як і ML спеціалізацію, Ендрю Ин. Спеціалізація створена разом з його другою освітньою платформою DeepLearning AI.</p><p><a href="https://www.coursera.org/learn/ai-for-everyone">AI For Everyone</a> — курс, прекрасно підходить для початківців. Фокус курсу на самій області, радше ніж на алгоритмах.</p><p><strong>Середній та просунутий рівні</strong>:</p><p><a href="https://www.coursera.org/specializations/machine-learning-engineering-for-production-mlops">Machine Learning Engineering for Production (MLOps) Specialization</a> — соавторами цієї спеціалізації є Ендрю Ин та Лоренс Мороні, про якого казала у попередньому. Наразі я закінчую цю спеціалізації, і можу точно сказати, що кращого місця, щоб вивчити MLOps не існує.</p><p><a href="https://www.coursera.org/professional-certificates/tensorflow-in-practice">DeepLearning.AI TensorFlow Developer Professional Certificate</a> — автором спеціалізації також є Лоренс Мороні. Присвячена розробці на Tensorflow. Цю спеціалізації рекомендую починати тільки тоді, коли опанували всі AI/ML моделі.</p><p><a href="https://www.coursera.org/specializations/tensorflow-advanced-techniques">TensorFlow: Advanced Techniques Specialization</a> — продовження попередньої спеціалізації більш складними алгоритмами.</p><p><a href="https://www.coursera.org/specializations/generative-adversarial-networks-gans">Generative Adversarial Networks (GANs) Specialization</a> — спеціалізація присвячена генеративному штучному інтелекту.</p><p><a href="https://www.coursera.org/specializations/natural-language-processing">Natural Language Processing Specialization</a></p><h3>Канали</h3><p><a href="https://www.youtube.com/@AndrejKarpathy/videos"><strong>Andrej Karpathy</strong></a><strong> — </strong>вчений та розробник багатьох алгоритмів штучного інтелекту.</p><p><a href="https://www.youtube.com/@AAmini"><strong>Alexander Amini</strong></a><strong> — </strong>записи лекцій MIT.</p><p><a href="https://www.youtube.com/@YannicKilcher"><strong>Yannic Kilcher</strong></a><strong> — </strong>креативний розробник, гарно пояснює наукові тези.</p><p><a href="https://www.youtube.com/@robmulla"><strong>Rob Mulla</strong></a><strong> — </strong>реалізує та пояснює популярні алгоритми машинного навчання та штучного інтелекту.</p><p><a href="https://www.youtube.com/@DavesSpace"><strong>Dave’s Space</strong></a><strong> — </strong>неймовірно цікавий технічний канал, присвячений багатьом областях.</p><p><a href="https://www.youtube.com/@sentdex"><strong>sentdex</strong></a><strong> — </strong>автор зосереджений на реалізація ML та AI алгоритмів та моделей з нуля, без використання фреймворків.</p><p><a href="https://www.youtube.com/@WeightsBiases"><strong>Weights &amp; Biases</strong></a><strong> — </strong>найбільший канал, присвячений штучному інтелекту.</p><p><a href="https://www.youtube.com/@aihouse_ukraine"><strong>AI HOUSE</strong></a><strong> — </strong>HEAR ME OUT<strong> </strong>УКРАЇНСЬКИЙ ПОДКАСТ ПРО ШТУЧНИЙ ІНТЛЕКТ. Пробачте за капслок, обожнюю всім серцем.</p><h3>Статті</h3><p>Всі наведені нижче сайти містять статті як початкового рівня, так і просунутого.</p><p><strong>Безкоштовні:</strong></p><p><a href="https://machinelearningmastery.com/category/algorithms-from-scratch/">machine learning mastery</a> — багато інформації та зручний сайт. У розділі категорій можна обрати тему, що вам потрібно.</p><p><a href="https://www.kdnuggets.com/">Kdnuggets</a> — цей сайт часто позиціонують як “безкоштовний аналог Medium“</p><p><a href="https://www.datacamp.com/search-resources">DataCamp</a> — один з найякісніших безкоштовних сайтів.</p><p><a href="https://www.analyticsvidhya.com/blog/">Analytics Vidhya </a>— загалом непоганий ресурс, особисто користуюся ним доволі рідко, бо у статтях занадто мало теорії. Але гарний ресурс для початківців.</p><p><strong>Потребують підписки:</strong></p><p><strong>Medium — </strong>найбільша блог платформа, має як безкоштовні статті, так і ті, що можна прочитати тільки з підпискою. <strong>Medium </strong>надає свій домен для створення спільнот, моя найулюбленіша — <a href="https://towardsdatascience.com/">Towards Data Science</a>: багато теорії, багато математики, але за підпискою.</p><p>Вартість підписки 5$, якщо у вас є можливість, підпишіться — не пожалкуєте (але спочатку задонатьте на один з актуальних зборів).</p><h3>Книги</h3><p><strong>Початковий рівень:</strong></p><p><em>Artificial Intelligence Basics: A Non-Technical Introduction</em>, <a href="https://www.amazon.de/-/en/Tom-Taulli/e/B001IOBMIQ/ref=dp_byline_cont_book_1">Tom Taulli</a></p><p><em>Artificial Intelligence Engines: A Tutorial Introduction to the Mathematics of Deep Learning</em>, <a href="https://www.amazon.de/-/en/James-V-Stone/e/B001IR3EY8/ref=dp_byline_cont_book_1">James V Stone</a></p><p><em>Fundamentals of Deep Learning</em><strong>, </strong>Джо Папа, Нікхіл Будума, і Нітхін Будума</p><p><em>Explainable AI for Practitioners</em><strong>, </strong>Девід Пітман і Майкл Манн<br><em>AI and Machine Learning for Coders</em><strong>, </strong>Лоуренс Мороні</p><p><strong>Середній рівень:</strong></p><p><em>AI at the Edge</em><strong>, </strong>Єнні Планкетт і Даніель Сітунаяке</p><p><em>Designing Machine Learning Systems</em><strong>, </strong>Чіп Хюєн</p><p><strong>Просунутий рівень:</strong></p><p><em>Nature-Inspired Computation and Swarm Intelligence</em>, Xin-She Yang</p><p><em>New Optimization Algorithms and their Applications: Atom-Based, Ecosystem-Based and Economics-Based</em>, <a href="https://www.yakaboo.ua/ua/author/view/liin-van">Ліїн Ван, </a><a href="https://www.yakaboo.ua/ua/author/view/vjejguo-chzhao">Вейго Чжао, </a><a href="https://www.yakaboo.ua/ua/author/view/chzhjen-sin-chzhan">Чженсін Чжан</a></p><p><em>Optimization Algorithms. AI techniques for design, planning, and control problems</em>, Alaa Khamis</p><p><em>Optimization and Machine Learning</em>, Rachid Chelouah, Patrick Siarry</p><p><em>Introducing MLOps: How to Scale Machine Learning in the Enterprise</em>, Mark Trevelli</p><p><em>Practical MLOps: Operationalizing Machine Learning Models</em>, 1st Ed. Noah Gift, Alfredo Deza</p><h3>Математика</h3><h3>Канали</h3><p><a href="https://www.youtube.com/@3blue1brown">3Blue1Brown </a>— автор публікує дуже прості та зрозумілі відео по математиці, фізиці та лінійній алгебрі, також канал має українську версію.</p><p><a href="https://www.youtube.com/@veritasium"><strong>Veritasium</strong></a><strong> — </strong>канал присвячений науці загалом, але багато відео на математичну тематику.</p><p><a href="https://www.youtube.com/@MichelvanBiezen"><strong>Michel van Biezen</strong></a><strong> — </strong>американський вчений та педагог, його відео покривають весь необхідний базис для машинного навчання та штучного інтелекту.</p><p><a href="https://www.youtube.com/@TheMathSorcerer/videos"><strong>The Math Sorcerer</strong></a><strong> — </strong>присвячений всьому навколоматематичному, але містить мало теорії, math nerd.<br><a href="https://www.youtube.com/@Eigensteve"><strong>Steve Brunton</strong></a><strong> — </strong>лінійна алгебра, методи оптимізації та штучний інтелект.</p><h3>Курси та спеціалізації</h3><p>Початковий рівень</p><p><a href="https://www.coursera.org/specializations/mathematics-for-machine-learning-and-data-science">Mathematics for Machine Learning and Data Science Specialization</a> — ідеально для початківців, які тільки почали вивчати математику. Для тих, хто має справу з математикою може показатися нудною</p><p><a href="https://www.coursera.org/specializations/mathematics-machine-learning">Mathematics for Machine Learning Specialization</a> — ідеально для початківців та тих, хто має складності з розумінням лінійної алгебри (1 курс)</p><p><a href="https://www.coursera.org/learn/stanford-statistics">Introduction to Statistics</a> — курс від Стенфордського університету, з якого гарно починати знайомство зі статистикою</p><p><a href="https://www.coursera.org/specializations/linear-algebra-elementary-to-advanced">Linear Algebra from Elementary to Advanced Specialization</a></p><p>Середній та просунутий рівень</p><p><a href="https://www.coursera.org/specializations/advanced-statistics-data-science">Advanced Statistics for Data Science Specialization</a></p><p><a href="https://www.coursera.org/specializations/probabilistic-graphical-models">Probabilistic Graphical Models Specialization</a> — теорія вірогідності</p><p><a href="https://www.coursera.org/specializations/data-mining">Data Mining Specialization</a> — аналіз та обробка інформації.</p><p><a href="https://www.coursera.org/specializations/integral-calculus-data-modeling">Integral Calculus through Data and Modeling Specialization</a></p><h3>Книги</h3><p>Всі книги зібрані у цій <a href="https://machinelearningmastery.com/resources-for-linear-algebra-in-machine-learning/">статті</a>.</p><p><strong><em>Дякую, що прочитали!</em></strong></p><p><strong><em>Якщо маєте цікаві ресурси, прошу, діліться у коментарях, буду дуже рада.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151859fb4001" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chords Detection using YOLOV5]]></title>
            <link>https://medium.com/@mirandorexes/chords-detection-using-yolov5-2108f2341425?source=rss-9ebacfcfa438------2</link>
            <guid isPermaLink="false">https://medium.com/p/2108f2341425</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[NeuroLace]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 14:15:36 GMT</pubDate>
            <atom:updated>2025-09-04T14:15:36.565Z</atom:updated>
            <content:encoded><![CDATA[<p>Як любов до музики та технологій надихнула мене на створення того, що бачите на екрані.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F882655448%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F882655448&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1750798709-10b03594dc17a5217de1e307817442786dd381a140f100991ecab905eec55adf-d_960%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1184" height="1270" frameborder="0" scrolling="no"><a href="https://medium.com/media/839401ec514a5069d1850540de748299/href">https://medium.com/media/839401ec514a5069d1850540de748299/href</a></iframe><p><a href="https://github.com/AnnacKK/Chords-detection">Репозиторій</a></p><p>У цій статті я детально розповім, як створювала датасет та навчала нейромережу, що розпізнає 14 основних гітарних акордів. Почнемо з найпростішого: навіщо це потрібно? По — перше, це цікавий та доволі складний учбовий проект, по — друге, його можна використовувати як тренажер для гітаристів — початківців (після допрацювання, звичайно). Складність найпростіше пояснити через аналогію з відомим датасетом коти — собаки. Людина з легкістю може розпізнати, де на фотографії кіт, а де собака, незалежно від їх пози, тоді як нейромережі іноді важко це зробити. Основна проблема в тому, що деякі породи котів в деяких ракурсах можуть виглядати як собаки, і навпаки. Ця ж проблема існує при розпізнаванні гітарних акордів: в деяких ракурсах акорди є дуже схожі або ж навіть ідентичні, про вирішення цієї проблеми трішки пізніше.</p><p>Я не буду детально розповідати про алгоритм роботи YOLO, тож якщо вам цікаво, пропоную послухати <a href="https://www.youtube.com/watch?v=9s_FpMpdYW8">лекцію</a> від Ендрю Ин.</p><h3>Основна ідея</h3><p>Навчити нейромережу на датасеті, що складається з фотографій положення рук при грі основних 14 гітарних акордів, після навчання моделі YOLO за допомогою бібліотеки opencv, налаштувати потік з вебкамери, таким чином, щоб модель розпізнавала акорди в режимі реального часу. Звучить складно, але оскільки це учбовий проєкт основний фокус на навчання на власному датасеті.</p><h3>Підготовка даних</h3><p>Вибір датасету грає одну з основних ролей у якості моделі та трактується підхідом, за яким інженер розробляє модель. Серед існуючих підходів, <a href="https://dcai.csail.mit.edu/lectures/data-centric-model-centric/">Data-Centric та Model-Centric</a>, все частіше обирають перший, який вважається більш практичним, тоді як другий підхід частіше використовують у наукових роботах. Я прибічниця першого, тому що він дає необхідну гнучкість у час, коли дані змінюються неймовірно швидко і ці зміни потрібно брати до уваги.</p><p>Для навчання моделі YOLO мені знадобиться створити власний датасет, оскільки у відкритому доступі немає. Важливе питання, яке потрібно вирішити — це кількість фотографій у кожному класі та ракурси, з яких вони будуть зроблені. Для якісного навчання моделі потрібно мінімум 500–1000 фотографій для кожного класу, але оскільки проект учбовий, я зменшу кількість до 30 фотографій для кожного класу: 14 класів * 30 фотографій = 420 загалом. Зміна ракурсів потрібна для того, щоб внести різноманіття — <a href="https://stagezero.ai/blog/data-diversity-importance-ai/">data diversity</a>, таким чином не допустити “привчення” моделі до конкретного типу фотографій. Наприклад, якщо зробити 30 фотографій з переднього центрального ракурсу (рука розташована по центру, без повороту вліво\вправо) — скоріш за все, модель буде розпізнавати акорд тільки в такому положенні руки, що може призвести до поганої якості класифікації.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RQZpqrbGcUxrBH-R.jpeg" /></figure><p>Питання друге, як зібрати швидко 420 фотографій? Перший варіант — автоматично зробити фотографії за допомогою вебкамери , другий — зробити фотографії на телефон, потім змінити їх розмір та ім’я файлу (мені краще перейменувати автоматично кожну фотографію за назвою акорда, але це необов’язково). Я зробила обидва варіанти, але остаточно зупинилася на другому через більш деталізовані фото, функції перейменовування та обрізки фотографій є у файлі rename_resize.py, перший варіант знаходиться у файлі .ipynb.</p><h3>Модель</h3><p>Імплементацію алгоритму YOLO обрала неофіційну від Ultralytics, 5 версію — вона є швидкою, точною та доволі легкою в порівнянні з іншими моделями. У документації рекомендується брати зображення розміром 320 або 640 пікселей. У деяких туторіалах використовують прямокутні зображення, проте на обрізку фотографій самим алгоритмом потрібна додаткова пам’ять. Для використання моделі необхідно клонувати репозиторій:</p><pre>!git clone https://github.com/ultralytics/yolov5</pre><p>та імпортувати необхідні бібліотеки:</p><pre>!pip install -r yolov5/requirements.txt</pre><p>Тепер тестова детекція об’єктів з вебкамери, для цього потрібно завантажити вже навчену модель:</p><pre>model = torch.hub.load(&#39;ultralytics/yolov5&#39;, &#39;yolov5s&#39;)</pre><p>‘yolov5s’ — назва вагів, в даному випадку я використовую small версію для пришвидшення. Для запуску лайфстріма:</p><pre>cap = cv2.VideoCapture(0)</pre><pre>while cap.isOpened():</pre><pre>    ret, frame = cap.read()</pre><pre>    results = model(frame)</pre><pre>    cv2.imshow(&#39;YOLO&#39;, np.squeeze(results.render()))</pre><pre>    if cv2.waitKey(10) &amp; 0xFF == ord(&#39;q&#39;):</pre><pre>        break</pre><pre>cap.release()</pre><pre>cv2.destroyAllWindows()</pre><p>Кожен фрейм відео з вебкамери передається до моделі, після чого результат класифікації та рамки знайденого об’єкта виводяться на екран, оскільки результат повертається у 4х вимірному форматі, його необхідно привести до 3х вимірного за допомогою np.squeeze.</p><h3>Імпорт бібліотек</h3><p>Перше, що необхідно зробити — це оновити python, anaconda (середовище розробки) та numpy — це дасть змогу завантажити необхідні біліотеки чи оновити до необхідних версій, що сумісні з torch. Для трекінгу метрик я використовую <a href="https://www.comet.com/site/">comet ml</a>, його потрібно імпортувати перед модулем torch:</p><pre>from comet_ml import Experiment<br>from comet_ml.integration.pytorch import log_model<br>experiment = Experiment(<br>  api_key=&quot;   &quot;,<br>  project_name=&quot;project_name&quot;,<br>  workspace=&quot;workspace_name&quot;)</pre><p>Айпі ключ можна знайти у налаштуванні проекту у самому comet ml</p><p>В залежності від середовища розробки, існують 3 варіанти компонент, на яких буде навчатися модель. Найоптимальнішим є навчання на GPU (відеокарті), для якої оптимізовані функції. Зі встановленням torch може виникнути багато неприємних казусів, тому я покажу метод, який особисто мені допоміг:</p><ol><li>Перейдіть на <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a> та оберіть необхідний варіант. Cuda — навчання на відеокарті, cpu — навчання на процесорі.</li></ol><p>2. Скопіюйте згенерований рядок та вставте у термінал (cmd)</p><p>3. Якщо імпорт успішний, перейдіть у середовище розробки та імпортуйте torch вже у середовище. Якщо імпорт успішний — вітаю.</p><p>4. Для тих, в кого є проблеми з версіями бібліотек, як і у мене, перейдіть на сайт <a href="https://download.pytorch.org/whl/cu118/torch_stable.html">https://download.pytorch.org/whl/cu118/torch_stable.html</a> та оберіть потрібну версію torch, torchvision та torchaudio. На момент написання цієї статті, актуальною версією є наступна:</p><pre>!pip3 install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio===2.1.0+cu118 -f https://download.pytorch.org/whl/cu118/torch_stable.html --user</pre><h3>Labelling</h3><p>Нажаль, пришвидшити лейблування доволі складно, тому приготуйтеся, що цей процес буде нудним та довгим. Існують декілька програм для лейблування, найкраща у використанні, як на мене — це <a href="http://makesense.ai/">makesense.ai</a>, єдиний недолік — неможливість створювати та зберігати проекти, щоб продовжити лейблування з того місця, на якому закінчили, якщо ви закрили сайт, доведеться починати спочатку.</p><p>Коректне виділення рамки об’єкта є надважливим, оскільки напряму впливає на якість моделі. Я користуюся наступним принципом: об’єкт у рамці повинна мати змогу ідентифікувати і людина. Наприклад, f minor та g minor відрізняються тільки фретом, на якому знаходяться, тому для цих акордів виділяла кисть та частину грифу: f minor знаходиться на першому фреті, тому його можна швидко ідентифікувати за головкою грифа:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Bo5urosh2NGAEZvP.jpeg" /></figure><p>Швидкий гайд для початку:</p><ol><li>З головної сторінки перехід до панелі через Get Started.</li><li>Обираєте файли, які потрібно лейблувати та натискаєте “Object Detection”</li><li>Для наступного кроку рекомендую підготувати .txt файл з назвами класів (новий клас з нового рядка), який допоможе автоматично створювати класи, замість ручного введення.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*xBFkkbuzTXLy1ehH.jpeg" /></figure><p>4. Виділення постановки руки на кожній фотографії та лейблування відповідним класом.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*tqtjvb049XBPhScv.jpeg" /></figure><p>5. Після завершення, імпорт як формат YOLO через Export Annotations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*ckziuxAgoT_t0E8K.jpeg" /></figure><p>У zip файлі міститься 420 текстових файлів, кожен з яких у свою чергу має номер класу та розташування рамки об’єкта, що належить цьому класу.</p><h3>Створення YAML файлу</h3><p>YAML файл містить визначення кожного класу — порядковий номер, саме цей номер є в текстових файлах, отриманих після лейбелінгу. Згідно нової документації YOLO файл має виглядати наступним чином:</p><p>Послідовність класів повинна бути така ж, як у класів, які використовувалися при лейблуванні: a_major — 0 клас, тобто перший у списку класів y <a href="http://makesense.ai/">makesense.ai</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*94s91fp58iPXS3jE.jpeg" /></figure><p>Ура! Дані підготовлені і можна починати навчання. Але перед цим, хочу звернути увагу на розташування файлів. Моя основна папка — Object_Detection, в якій розташовані 2 необхідні папки: data ( в ній міститься датасет) та yolov5 (з компонентами YOLO та інформацією про тренування).</p><p>Папка data містить папку images — в ній знаходяться усі фотографії та папку labels з текстовими файлами, отриманими після лейблування.</p><p>Файл custom.yaml знаходиться у папці data у <strong><em>yolov5: …\Object_Detection\yolov5\data\custom.yaml</em></strong></p><p><strong>На що потрібно звернути увагу перед навчанням</strong></p><ol><li>Чи імпортовані необхідні бібліотеки</li><li>Чи id класів у тектових файлах збігаються з id класів у .yaml файлі</li><li>Чи встановлений torch вірно: для перевірки версії:</li></ol><pre>torch. __version__.</pre><h3>Навчання</h3><p>Для запуску навчання необхідно ввести тільки одну строчку коду (яка може призвести до неприємних проблем, описаних нижче)</p><pre>!cd yolov5 &amp;&amp; python train.py --img 640 --batch 16 --epochs 400 --data custom.yaml --weights yolov5s.pt --workers 2</pre><p>!cd yolov5 — папка, де розташоване YOLO</p><p>python <a href="http://train.py/">train.py</a> — файл тренування моделі</p><p>img 640 — розмір зображення</p><p>batch 16 — кожен батч містить 16 зображень</p><p>epochs 400 — навчання тривалістю 600 епох</p><p>data custom.yaml — розташування та назва yaml файлу</p><p>workers 2 — скільки “потужностей“ буде використовуватися для навчання.</p><p>Якщо ви не впевнені, чи йде навчання на GPU, можна призначити вручну:</p><pre>torch.cuda.set_device(0)</pre><p>На GTX 1050 Tі навчання тривало близько 3х годин.</p><p>Після завершення навчання у папці yolov5/runs/train/exp1 (номер експерименту = кількості запусків навчання) знаходяться ваги моделі та метрики, які можна вивести як графіки:</p><pre>from utils.plots import plot_results<br>plot_results(&#39;yolov5/runs/train/exp29/results.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*znNONzXwrOSjzcjt.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1AkRywmantAjDJtW.jpeg" /></figure><pre>model = torch.hub.load(&#39;ultralytics/yolov5&#39;, &#39;custom&#39;, path=&#39;yolov5/runs/train/exp29/weights/last.pt&#39;, force_reload=True)</pre><p>- завантажує ваги у модель, яку потім можна використовувати. Передбачення у лайфстрімі можна зробити, використавши попередній код.</p><p>Як видно на превью на початку статті, класифікація доволі точна для учбового проєкту, але, звичайно, модель все ще недонавчена через маленький датасет, який не включає багато видів фотографій.</p><h3>Баги при навчанні</h3><ol><li><strong>SSL: CERTIFICATE_VERIFY_FAILED</strong> може бути пов’язано з помилкою завантаження шрифта Arial (так, мені теж було смішно). Вирішення бага описано тут: <a href="https://github.com/ultralytics/yolov5/issues/12306">https://github.com/ultralytics/yolov5/issues/12306</a></li></ol><p><strong>2. IOPub data rate exceeded. The notebook server will temporarily stop sending output</strong></p><p>3. Цей баг був виправлен у релізі <a href="http://jupyter-notebook.readthedocs.io/en/stable/changelog.html">5.2.2</a>, але якщо він все ж виникнув, мені допомогло збільшення рейту у файлі конфігурації <a href="https://stackoverflow.com/questions/43288550/iopub-data-rate-exceeded-in-jupyter-notebook-when-viewing-image">https://stackoverflow.com/questions/43288550/iopub-data-rate-exceeded-in-jupyter-notebook-when-viewing-image</a></p><h3>Що далі?</h3><p>Не однією гітарою єдині. Бас, укулеле, 12-ти струнна гітара та інші музичні інструменти — для них теж можна створити власні нейромережі. Мені було дуже цікаво працювати з таким проєктом, а Вам сподіваюсь читати. Побачимося наступного разу!</p><h3>Референси</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*t5qPJQ8feqkEMr_5.jpeg" /></figure><p><a href="https://docs.ultralytics.com/yolov5/tutorials/train_custom_data/#local-logging">Train Custom Data — Ultralytics YOLOv8 Docs</a></p><p><a href="https://docs.ultralytics.com/yolov5/tutorials/train_custom_data/#local-logging">Learn how to train your data on custom datasets using YOLOv5. Simple and updated guide on collection and organization of</a></p><p><a href="https://docs.ultralytics.com/yolov5/tutorials/train_custom_data/#local-logging">docs.ultralytics.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2108f2341425" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>