<?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 Nurdan Aydogdu on Medium]]></title>
        <description><![CDATA[Stories by Nurdan Aydogdu on Medium]]></description>
        <link>https://medium.com/@aydogdunurdan?source=rss-2c9d96df88e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UfMshFjP_tOXcJSh</url>
            <title>Stories by Nurdan Aydogdu on Medium</title>
            <link>https://medium.com/@aydogdunurdan?source=rss-2c9d96df88e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:43:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aydogdunurdan/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[Zaman Serilerinde Çoklu (Multi-Output) Tahmin Yöntemi]]></title>
            <link>https://medium.com/t%C3%BCrkiye/zaman-serilerinde-%C3%A7oklu-multi-output-tahmin-y%C3%B6ntemi-20caa672d7a3?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/20caa672d7a3</guid>
            <category><![CDATA[time-series-forecast]]></category>
            <category><![CDATA[multi-output-forecast]]></category>
            <category><![CDATA[zaman-serisi-çoklu-tahmin]]></category>
            <category><![CDATA[türkçe]]></category>
            <category><![CDATA[multioutputregressor]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 17:54:45 GMT</pubDate>
            <atom:updated>2025-12-04T15:20:25.504Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bu yazı, zaman serisi tahminlerinde, çok çıktılı (multi-output) yöntemin nasıl uygulamdığını anlatan, bir eğitim dökümanı olarak tasarlanmıştır. / Multi-Output (Direct Multi-Step) Time Series Forecast</h4><p><a href="https://medium.com/t%C3%BCrkiye/zaman-serilerinde-i%CC%87teratif-yinelemeli-%C3%A7ok-ad%C4%B1ml%C4%B1y%C3%B6ntemle-tahmin-400331812951"><strong>Zaman Serilerinde İteratif (Yinelemeli), Çok Adımlı Tahmin Yöntemi için</strong></a></p><p><a href="https://github.com/nrdnay/Multi-Output-TimeSeries-Forecast-Training/blob/main/Multi-Out-TimeSeries-Forecast-Training-EN.ipynb"><strong>Eğitime ait kodlamanın tamamı için GitHub</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*tsIV7kusKm_OWFai3XYeYw.png" /></figure><h4>1) Zaman Serilerinde Kullanılan Tahmin Yöntemleri</h4><p>Bir zaman serisinin geleceğini tahmin etmek için birkaç yol vardır:</p><p><strong>Çok çıktılı (multi-output, direct multi-step) yöntem</strong>: Bu yazıda ele aldığımız bu yöntemde tek bir model, aynı anda çoklu adımları çıktı olarak verir (ör. model çıktısı bir vektör: [t+1, t+2, …, t+24]).</p><p><a href="https://medium.com/p/400331812951"><strong>İteratif (Recursive) yöntem</strong></a><strong>:</strong> Model sadece <em>bir sonraki zaman periyodunu (ay, gün vb) </em>tahmin eder. Sonra tahmin, tekrar modele sokulup bir sonraki zaman periyodu tahmin edilir. Adım adım ilerlenir.</p><p><strong>Direct (doğrudan — tek tek eğitim) yöntemi</strong>: Her hedef adım için ayrı bir model eğitilir (t+1 için bir model, t+2 için başka model…). Dezavantaj: daha çok model, daha çok veri, daha çok enerji gerektirir.</p><p><strong>Sequence-to-sequence</strong> <strong>(encoder-decoder) yöntemi : </strong>RNN (LSTM, GRU) veya Transformer tabanlı (özellikle NLP için Transofrmer veya BERT) seq2seq modelleri doğrudan çok adımlı tahmin yapabilir.</p><p><strong>Bazı hibrid yöntemler:</strong> iteratif + düzeltme, ensembler’lar vb.</p><h4>2) Çok Çıktılı (Multi-output) Yöntem</h4><p>👉 T<strong>ek bir modelin gelecek için aynı anda birden fazla değeri tahmin etmesi</strong> demektir. Bu nedenle recursive yönteme göre daha istikrarlı sonuçlar alınır.</p><p><strong>t</strong>, zaman periyodu olmak üzere, model örneğin önümüzdeki 24 ayın değerlerinin tamamını aynı anda <strong>tek seferde</strong> üretebiliyor: t+1, t+2, t+3, …, t+24</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*ntCrWuZVK3mNym7g3noAAg.png" /></figure><h4>3) Neden çok çıktılı (multi-output) yöntem tercih edilir?</h4><ul><li>Hızlıdır.</li><li>Tüm tahminleri tek seferde verir.</li><li>Hata birikimi yoktur çünkü; her adım için oluşan tahmin hatası, sonraki adıma taşınmaz.</li><li>Uzun vadeli tahminlerde daha “stabil” davranır.</li></ul><p>📌 Özetle, eğer“bir kerede uzun vade görülmek isteniyorsa” multi-output yöntem tercih edilebilir.</p><h4>4) Multi-output yöntem hangi durumlarda tercih edilir?</h4><p><strong>a) Hangi Durum?</strong></p><ul><li>Uzun vadeli (12+ adım) tahmin yapılacaksa</li><li>Hata birikimi istenmiyorsa</li><li>Bilgisayar zamanı kısıtlıysa</li></ul><p><strong>b) Hangi veri tipi?</strong></p><ul><li>Zaman serileri</li><li>Sensör verileri</li><li>Enerji talep verileri</li><li>Finansal simülasyonlar</li></ul><p><strong>c) Hangi Modelleme?</strong></p><ul><li>Lineer regresyon</li><li>Random Forest</li><li>XGBoost</li><li>Sinir ağları (MLP, CNN, LSTM)</li></ul><p><strong>d) Hangi Uygulamalar?</strong></p><ul><li>Hava durumu</li><li>Enerji talep tahmini</li><li>Elektrik fiyat tahmini</li><li>Satış tahmini</li><li>Stok planlama</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*tY0gvg354sPK1n1u289tBw.png" /></figure><h4>UYGULAMALI ANLATIM ile MULTI-OUTPUT YÖNTEMİ</h4><p><strong>Kod ve kodlamaya ait açıklamar, aşağıda bölüm bölüm anlatılmıştır:</strong></p><h4><strong>1) Sentetik Veri Üretimi</strong></h4><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.multioutput import MultiOutputRegressor<br>from sklearn.linear_model import LinearRegression</pre><pre>np.random.seed(42)<br>periods = 72</pre><pre>dates = pd.date_range(start=&quot;2019-01-01&quot;, periods=periods, freq=&quot;MS&quot;)</pre><pre>trend = 0.5 * np.arange(periods)<br>seasonal = 10 * np.sin(2 * np.pi * np.arange(periods) / 12)<br>noise = np.random.normal(scale=3.0, size=periods)<br>base = 50</pre><pre>prices = base + trend + seasonal + noise<br>series = pd.Series(prices, index=dates, name=&quot;price&quot;)</pre><h4>Amaç:</h4><p>72 aylık (6 yıl) <strong>tamamen yapay / sentetik</strong> bir fiyat serisi oluşturmak,<br>İteratif yöntemde kullandığımız serinin <strong>birebir aynısını</strong> üretmek.<br>Böylece iki yöntemin (itertif yöntem ile çoklu çıkıt) <strong>karşılaştırılabilir</strong> olması sağlanır.</p><h4><strong>Kod Açıklamaları</strong></h4><p>📌<strong>import numpy as np</strong> NumPy sayılarla işlem yapmak için kullanılır. Özellikle <strong>rastgele sayı</strong>, <strong>trend üretme</strong>, <strong>dizi işlemleri</strong> için gereklidir.</p><p>📌<strong>import pandas as pd</strong> Zaman serisini saklamak için kullanılır. Tarih indeksli tablo üretmeye yarar.</p><p>📌<strong>import matplotlib.pyplot as plt</strong> Grafik çizebilmek için.</p><p>📌<strong>np.random.seed(42)</strong> Rastgele sayı üreticisinin başlangıç noktasını belirler. Her çalıştırmada aynı sonuç çıkmasını → tekrar üretilebilirliği sağlar.</p><p>📌<strong>periods = 72</strong> Tam <strong>72 veri noktası</strong> üretileceğini söyler (aylık veri = 6 yıl).</p><p>📌 <strong>pd.date_range(...)</strong> İstenen zaman periyodu aralığında veri üretir. Örneğin 72 adet, aylık.</p><p>📌<strong>pd.date_range(..., freq=&quot;MS&quot;)</strong></p><p>freq = MS, “Month Start” anlamına → her ayın 1’i anlamına gelir.</p><p>Modelin zaman serisinin düzenli olması için kullanılır.</p><p>📌<strong>Trend bileşeni</strong></p><pre>trend = 0.5 * np.arange(periods)</pre><ul><li>Her ay fiyatın 0.5 birim artmasını sağlar.</li><li>np.arange → 0,1,2,3,… gibi artan sayılar üretir.</li><li>Ekonomik serilerde yükselişi temsil eder.</li></ul><p>📌<strong>Mevsimsellik bileşeni</strong></p><pre>seasonal = 10 * np.sin(2 * np.pi * np.arange(periods) / 12)</pre><ul><li>Her 12 ayda bir tekrar eden bir sinüs dalgası oluşturur.</li><li>Sinüs dalgası mevsimsellik modelleri için klasik bir yaklaşımdır.</li></ul><p>📌<strong>Gürültü (noise)</strong></p><pre>noise = np.random.normal(scale=3.0, size=periods)</pre><ul><li>Gerçek hayatta fiyatlar tam düzgün artmaz. O nedenle sentetik veriye gürültü elenerek gerçekçilik artırılır.</li><li>Normal dağılım (çan eğrisi) kullanılır.</li></ul><p>📌<strong>Temel seviye</strong></p><pre>base = 50 # Fiyatların başlangıç noktası.</pre><p>📌<strong>Tüm bileşenlerin toplamı ve zaman serisine dönüştürme</strong></p><pre>prices = base + trend + seasonal + noise<br>series = pd.Series(prices, index=dates, name=&quot;price&quot;)</pre><ul><li><strong>Series(…) </strong>ile artan trendli ve gürültülü sentetik zaman serisi üretildi.</li><li><strong>DataFrame(…) </strong>“value” adlı tek sütunlu bir tablo oluşturur.</li><li>Artık elimizde sentetik olarak üretilmiş, <strong>tarih indeksli</strong>, <strong>72 gözlemli</strong>, <strong>temiz bir seri</strong> var.</li></ul><h4>2) Lag (1–12) Oluşturma ve Target (t+1..t+24) Oluşturma</h4><pre>df = pd.DataFrame(series)</pre><pre>for lag in range(1, 13):<br>    df[f&quot;lag_{lag}&quot;] = df[&quot;price&quot;].shift(lag)</pre><pre>for step in range(1, 25):<br>    df[f&quot;target_t_plus_{step}&quot;] = df[&quot;price&quot;].shift(-step)</pre><pre>df_clean = df.dropna().copy()</pre><h4><strong>Amaç:</strong></h4><p><strong>Girişler (Features)</strong></p><ul><li>Modelin bakacağı geçmiş 12 ayı oluşturuyoruz:</li><li>lag_1 → 1 ay önceki fiyat</li><li>lag_2 → 2 ay önceki fiyat<br> …</li><li>lag_12 → 12 ay önceki fiyat</li></ul><p><strong>Çıkışlar (Targets)</strong></p><ul><li>Modelin tahmin edeceği 24 ayı oluşturuyoruz:</li><li>target_t_plus_1 → 1 ay sonrası</li><li>target_t_plus_24 → 24 ay sonrası</li></ul><p>📌 Multi-output modelin ana mantığında, bir giriş <strong>→</strong> birden fazla çıkış vardır.</p><h4><strong>Kod Açıklamaları</strong></h4><p>📌<strong>df = pd.DataFrame(series)</strong></p><ul><li>Tek sütunluk zaman serisini tabloya dönüştürür.</li><li>Sonrasında yeni sütunlar eklemek kolay olsun diye.</li></ul><p>📌<strong>Lag sütunları oluşturma</strong></p><pre>for lag in range(1, 13):<br>    df[f&quot;lag_{lag}&quot;] = df[&quot;price&quot;].shift(lag)</pre><p><strong>✔ Lag penceresi = Geçmişe giden penceredir. </strong>Adım saysını verir. Her bir adım, 1 zaman periyoduna eşdeğerdir.</p><p>Örneğin “lag_3” şöyle olur:</p><ul><li>1 ay önceki değer → lag_1</li><li>2 ay önceki değer → lag_2</li><li><strong>3 ay önceki değer → lag_3</strong></li><li>Böylece model geçmiş 12 aya bakarak tahmin yapabilir.</li><li>shift(lag) → seriyi belirtilen kadar geçmişe kaydırır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*FEciCOeuE_LT36Vbl4zfcA.png" /><figcaption>Bu tabloda <strong>lag sütunları geçmiş pencereyi oluşturuyor.</strong></figcaption></figure><p>📌<strong>TARGET sütunları (24 aylık horizon)</strong></p><pre>for step in range(1, 25):<br>    df[f&quot;target_t_plus_{step}&quot;] = df[&quot;price&quot;].shift(-step)</pre><p><strong>✔ Gelecek shift penceresi = Tahmin etiketi (y)</strong></p><p>“target_t_plus_1” şöyle olur:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*B1YZQSaRtHDftCJZTJbrfg.png" /></figure><p>shift(-step) → ileri doğru kaydırır → gelecekteki değerlerdir. Bu sütunlar multi-output hedef değişkenleridir.</p><h4>⚠ Önemli</h4><p>✔ T = bugünkü değer<br> ✔ lag_1..lag_12 = geçmiş 12 ay<br> ✔ target_t_plus_1..target_t_plus_24 = gelecek 24 ay</p><p><strong>Hepsi tek DataFrame’de bir araya gelir ve </strong>çok çıktılı (multi-output) veri seti tamamen hazır olur.</p><p>📌<strong>df_clean = df.dropna().copy()</strong></p><p>Hem lag, hem future shift kullandığımız için en baştaki 12 satır ile, en sondaki 24 satır boş kalır ve bunlar <strong>.dropna()</strong> ile temizlenir. Kalan satır sayısı:</p><pre>72 - 12 - 24 = 36 satır</pre><p>Bu yüzden multi-output’ta <strong>df_clean = 36 olur</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*D4_v7578gWczbBRLvhHWzQ.gif" /></figure><h4>3) Train–Test Split (24 / 12 olarak)</h4><pre>train = df_clean.iloc[:24]<br>test  = df_clean.iloc[24:36]</pre><pre>X_train = train[[f&quot;lag_{i}&quot; for i in range(1,13)]].values<br>Y_train = train[[f&quot;target_t_plus_{i}&quot; for i in range(1,25)]].values</pre><pre>X_test  = test[[f&quot;lag_{i}&quot; for i in range(1,13)]].values</pre><h4>Amaç:</h4><p>❗<a href="https://medium.com/t%C3%BCrkiye/zaman-serilerinde-i%CC%87teratif-yinelemeli-%C3%A7ok-ad%C4%B1ml%C4%B1y%C3%B6ntemle-tahmin-400331812951"><strong>İteratif yöntemde</strong></a><strong> → Train = 48, Test = 12 idi. </strong>Ama burada veri 36&#39;ya düştüğü için: <strong>Train = 24, Test = 12 </strong>olmak zorundadır.</p><p>Satır sayısı 36 olduğu için traini 48 yapmak matematiksel olarak mümkün değildir.</p><ul><li>Daha önce oluşturulan <strong>lag sütunları</strong> <strong>X (girdi) </strong>olarak alınır.</li><li>Daha önce oluşturulan <strong>target sütunları</strong> <strong>Y</strong> <strong>(çıktı)</strong> olarak alınır.</li></ul><h4>Kod Açıklamaları</h4><p>📌<strong>iloc[:24]</strong> İlk 24 satır → eğitim için.</p><p>📌<strong>iloc[24:36]</strong> Son 12 satır → test için.</p><p>📌<strong>X_train</strong> Giriş değişkenleri = geçmiş 12 ay.</p><p>📌<strong>Y_train</strong> Çıkış değişkenleri = 24 aylık future horizon.</p><p>📌<strong>values</strong> Veriyi NumPy dizisine dönüştürür. scikit-learn modelleri NumPy ile çalışır.</p><h4>4) MODEL: MultiOutputRegressor + LinearRegression</h4><pre>model = MultiOutputRegressor(LinearRegression())<br>model.fit(X_train, Y_train)</pre><h4>Amaç</h4><p>Model geçmiş 12 ayı giriş olarak alır ve <strong>24 aylık geleceği aynı anda</strong> tahmin eder.</p><p>📌<strong>MultiOutputRegressor</strong>, her çıkış değişkeni için ayrı bir model eğitir ve hepsini aynı anda kullanır. Her hedef için bağımsız regresyon uygulanır.</p><h4>Kod Açıklamaları</h4><p>📌<strong>LinearRegression()</strong> Basit ve hızlı bir regresyon modelidir.</p><p>📌<strong>MultiOutputRegressor()</strong> Tek model ile çoklu çıktı tahmini sağlar. 24 hedefi, 24 ayrı model gibi ele alır.</p><p>📌<strong>fit(X_train, Y_train)</strong> Modeli eğitir.</p><h4>5) Tek Seferde 24 Aylık Tahmin</h4><pre>last_input = X_test[-1].reshape(1, -1)<br>pred_24 = model.predict(last_input)[0]</pre><h4>Amaç:</h4><p>Test setindeki son satırın geçmiş 12 ayı alınıyor ve model veriliyor.</p><p>Model <strong>tek seferde 24 farklı ayın tahminini</strong> çıkartıyor. Recursive yöntemdeki gibi 1 ay → 1 ay → 1 ay şeklinde ilerleme yoktur.</p><h4>Kod açıklamaları</h4><p>📌<strong>X_test[-1]</strong> Test verisinin son örneği.</p><p>📌<strong>.reshape(1, -1)</strong> Model tek bir örnek beklediği için yeniden şekillendiriyoruz.</p><p>📌<strong>.predict(last_input)</strong> 24 tahmini birden üretir.</p><h4>6) Performans Ölçümleri</h4><pre># Test seti için gerçek t+1 hedef değerleri:<br>Y_test_1 = test[&quot;target_t_plus_1&quot;].values<br><br># Test setindeki her X_test satırı için modelin verdiği çoklu tahminlerden sadece t+1&#39;i alınır<br>y_pred_test_1 = model.predict(X_test)[:, 0]  # ilk sütun → t+1 tahmini<br><br># Metrikler<br>mse  = mean_squared_error(Y_test_1, y_pred_test_1)<br>rmse = np.sqrt(mse)<br>mae  = mean_absolute_error(Y_test_1, y_pred_test_1)<br>mape = np.mean(np.abs((Y_test_1 - y_pred_test_1) / Y_test_1)) * 100<br><br># Sonuçları yazdır<br>print(&quot;\n--- TEST PERFORMANCE (t+1) ---&quot;)<br>print(f&quot;MSE : {mse:.4f}&quot;)<br>print(f&quot;RMSE: {rmse:.4f}&quot;)<br>print(f&quot;MAE : {mae:.4f}&quot;)<br>print(f&quot;MAPE: {mape:.2f}%&quot;)</pre><h4>Amaç :</h4><p>Multi-output yöntem <strong>aynı anda 24 farklı gelecek değeri </strong>tahmin edebilen bir modeldir.<br> Ancak bu 24 tahminden hangisinin “gerçek veriye göre doğru çalıştığını” anlamak için bir karşılaştırmaya ihtiyaç vardır. <strong>Test seti</strong>, yani modelin görmediği son 12 satır, bize bunun için fırsat verir. Test setinde her satır için:</p><ul><li>X_test → “geçmiş lag değerleri”</li><li>Y_test → “gelecek 24 ayın gerçek değerleri” bulunmaktadır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*qxDd0V_NGpR0usmYHnqZMQ.gif" /></figure><p>Ancak bu gerçek değerlerden yalnızca <strong>t+1 (1 ay sonrası)</strong> değerleri elimizde vardır ve modelin eğitimi ve güvenilir karşılaştırma buna dayanır.</p><p>Bu nedenle performans ölçümünü <strong>t+1 adımı için yapıyoruz. </strong>(İleri adımlar da hesaplanabilir ama güvenilirlik t+1’de daha yüksektir)</p><h4>Kod Açıklamaları :</h4><p><strong>Test setindeki gerçek t+1 değerlerinin alınması</strong></p><pre>Y_test_1 = test[&quot;target_t_plus_1&quot;].values</pre><p><strong>target_t_plus_1</strong>, veriyi oluştururken yaptığımız:</p><pre>df[&quot;target_t_plus_1&quot;] = df[&quot;price&quot;].shift(-1)</pre><p>işleminin ürünüdür. Yani her satırdaki X’e karşılık: <strong>1 ay sonraki gerçek fiyat</strong> burada saklanmıştır. Test seti 12 satır olduğu için burada da <strong>12 adet gerçek (yani 1 zaman periyodu ileri kaydırmayla elde edilmiş) t+1 değeri</strong> vardır.</p><h4>Modelin tahmin ettiği t+1 değerlerinin alınması</h4><pre>y_pred_test_1 = model.predict(X_test)[:, 0]</pre><p><strong>model.predict(X_test)</strong> çıktısı 12 satır, 24 sütundan oluşur.</p><p>Her sütun, şu tahminleri temsil eder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*rC3OBgSkNFpFUPm-UcBfNw.png" /></figure><p>Bu yüzden:</p><pre>[:, 0]</pre><p>demek → <strong>sadece 1 ay sonrası tahminleri al</strong> anlamına gelir.</p><h4>Performans metriklerinin hesaplanması</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*rYedPuSs0Daq86n49cPyeQ.png" /><figcaption>Kod çalıştırıldıktan sonra alınan Performans Sonuçları</figcaption></figure><p><strong>MSE — Mean Squared Error</strong></p><pre>mse = mean_squared_error(Y_test_1, y_pred_test_1)</pre><p>Gerçek ve tahmin farklarının <strong>karelerinin ortalamasıdır</strong>. Küçük olması istenir.</p><p><strong>RMSE — Root Mean Squared Error</strong></p><pre>rmse = np.sqrt(mse)</pre><p>MSE’nin karekökü → orijinal birimlere geri döner (fiyat).</p><p><strong>MAE — Mean Absolute Error</strong></p><pre>mae = mean_absolute_error(Y_test_1, y_pred_test_1)</pre><p>Gerçek ve tahmin arasındaki ortalama mutlak farktır ve yorumlaması en kolay metriktir.</p><p><strong>MAPE — Mean Absolute Percentage Error</strong></p><pre>mape = np.mean(np.abs((Y_test_1 - y_pred_test_1) / Y_test_1)) * 100</pre><p>Yüzde olarak hata oranı verir. Örneğin MAPE = %4 demek, o<em>rtalama hata gerçek değerin %4’ü kadar demektir.</em></p><p>Özetle bu bölümde: Test setindeki <strong>gerçek t+1 değerleri</strong> alınıp modelin <strong>t+1 tahminleri</strong> hesaplandı ve MSE, RMSE, MAE, MAPE performans metrikleri ile karşılaştırma yapıldı. Bu sayede modelin <strong>geleceği ne kadar doğru tahmin edebildiğini</strong> ölçülmüş oldu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*q1SuvMGNUMn6uwZHoQRCKQ.png" /><figcaption>GRAFİK : Multi-output Time Series Forecasting with Linear Regression</figcaption></figure><h4>7) Grafik</h4><pre>forecast_dates = pd.date_range(<br>    start=series.index[-1] + pd.offsets.MonthBegin(1),<br>    periods=24,<br>    freq=&quot;MS&quot;<br>)</pre><pre>forecast_series = pd.Series(pred_24, index=forecast_dates)</pre><pre>plt.figure(figsize=(12,5))<br>plt.plot(series.index, series.values, label=&quot;Gerçek Seri&quot;)<br>plt.plot(forecast_series.index, forecast_series.values,<br>         marker=&#39;o&#39;, linestyle=&#39;--&#39;, label=&quot;24-Step Direct Forecast&quot;)<br>plt.legend()<br>plt.show()</pre><h4>Amaç:</h4><p>📌 Modelin tahminlerinin geçmiş verinin devamı olarak nasıl göründüğünü anlamak. Sol tarafta geçmiş 72 aylık gerçek veri, sağ tarafta modelin tahmin ettiği 24 ay yer alır.</p><h4>Kod açıklamaları</h4><p>📌<strong>Yeni tarihlerin oluşturulması</strong></p><pre>pd.date_range(start=..., periods=24)</pre><p>Tahmin edilen 24 ayın tarih indeksleri.</p><p>📌<strong>Tahmin serisinin oluşturulması</strong></p><pre>pd.Series(pred_24, index=forecast_dates)</pre><p>📌<strong>Grafik çizme</strong></p><p>plt.plot() geçmiş veri ve tahmin serisi için</p><h4>7) Neden çok çıktılı (multi-output) yöntem örneğinde Train verisi 48 yapılamıyor?</h4><p>Gelecek 24 ay tahmininde çok çıktılı (multi-output) yöntem için gerekli minimum veri:</p><pre>lag (12) + horizon (24) = 36</pre><p>Bu nedenle 72 gözlemden geriye 36 kullanılabilir satır kalıyor. <a href="https://medium.com/t%C3%BCrkiye/zaman-serilerinde-i%CC%87teratif-yinelemeli-%C3%A7ok-ad%C4%B1ml%C4%B1y%C3%B6ntemle-tahmin-400331812951">İteratif yöntem uygulamasında</a>, her tahmin veri setine dahil edilediği için, veri sayısında artış söz konusuydu. Oysa multi-output yöntemde, Train=48, Test=12 olması için en az <strong>96 gözlem</strong> olması gerekiyor.</p><h3>Özet Olarak Neler Yapıldı?</h3><p>Sentetik 72 aylık sentetik zaman serisi kullanılarak, tek seferde gelecek 24 ayı, aynı anda tahmin eden bir Multi-Output Linear Regression modeli kuruldu.</p><p>Bu yaklaşımda model, son 12 ayın geçmiş fiyatlarını girdi, önümüzdeki 24 ayın fiyatlarını ise çıktı olarak alan bir yapı ile eğitildi.<br>Bunun için veri hazırlamada Lag özellikleri (lag_1 … lag_12) ve gelecek 24 ay hedefleri (target_t_plus_1 … target_t_plus_24) oluşturuldu.</p><p>Veri satırlarındaki ileri-geri kaydırmalar nedeniyle, boş kalan satırlar silindikten sonra 36 satırdan oluşan bir veri seti oluştu. ilk 24 satırı train, son 12 satırı test olarak ayrıldı.</p><p>MultiOutputRegressor’den faydalanılarak LinearRegression ile model kuruldu. Model, test setinin son satırını kullanarak 24 aylık tahmin üretti ve tek periyotluk tahmin baz alınarak performans ölçüldü (MSE, RMSE, MAE, MAPE). Bu işlem sonunda model hem bir trendi hem sezonsal hareketleri yakalamayı başardı.</p><h4>Neden Multi-Output Yöntem?</h4><p><strong>Avantajları:</strong></p><p>-İteratif yöntem gibi tahmini kendi içine geri vermediği için hata birikmesi yaşamaz</p><p>-24 farklı geleceği bağımsız ama aynı anda öğrenir.</p><p>-Çok adımlı tahminlerde hızlı ve pratiktir.</p><p>-Tek seferde 24 sayı üretmek gerektiğinde kullanışlıdır.</p><p><strong>Dezavantajları:</strong></p><p>-t+12, t+18, t+24 gibi uzak adımlar için, doğruluk genelde düşer.</p><p>-Uzak hedefleri bilmek zor olduğu için model bu ilişkileri öğrenmekte zorlanabilir.</p><ul><li>Her ileri adım birbirinden kopuk olduğu için “geçmiş → çok uzak gelecek” ilişkisi zayıflayabilir.</li></ul><p>Multi-Output Forecast için başlangıç aşamasında Linear Regression idealdir ancak; Random Forest Regressor, XGBoost, Seq2Seq LSTM gibi modellerle performansı daha da geliştirme yoluna gidilebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*jHNhlWJe6FvJAbywvq-W0A.gif" /></figure><h4>Bu Uygulamada;</h4><p><strong>1. </strong>Sentetik veride hem trendi hem mevsimsellik oluşturuldu. Bu işlem sonunda model hem bir trendi hem sezonsal hareketleri yakalamayı başardı.</p><p>Ürettiğimiz sentetik seriye; Lineer trend, 12 aylık sinusoidal sezonluk döngü ve Gürültü (noise) ekledik. Linear Regression dahi bu yapıyı belli ölçüde takip edebildi.</p><p><strong>2.</strong> 12 → 24 pencere yapısı kuruldu.</p><p>Lag (geçmiş) penceresi: 12 ay</p><p>Future (gelecek) penceresi: 24 ay</p><p>Bu, literatürde “12×24 windowed supervised learning” olarak adlandırılıyor.</p><p>Zaman serisini, klasik bir makine öğrenmesi problemine dönüştürdük.</p><p><strong>3. </strong>Multi-output hedef yapısı kuruldu.</p><p>Geleceği çok adımlı tahminleyen yöntemlerin en önemli adımı: Model 24 farklı y değerini bir vektör olarak öğrendi.</p><p><strong>4.</strong> Gerçek test verisi ile performans ölçümü eklendi.</p><p>Modelin MSE, RMSE, MAE ve MAPE performans değerleri hesaplandı.</p><p>Bu metrikler modelin 1 adım ötesini ne kadar doğru öğrendiğini gösterdi.</p><p><strong>5.</strong> Gerçek–Tahmin grafikleri ile gelecek görselleştirildi.</p><p>Grafikte solda gerçek seri, sağda 24 aylık tahmin çizgisi yer aldı.</p><p>Modelin trendi devam ettirdiğini ve sezonsal formu büyük ölçüde takip ettiğini gördük.</p><p><strong>Güçlü Yanlar</strong><br>⭐ 1. Çok adımı tek seferde tahminlemek hızlıdır. İteratif yöntemde olduğu gibi 24 kez model çalıştırmak gerekmez.</p><p>⭐ 2. Daha kararlı tahminler verir. Çünkü bir adımda yapılan hatalar bir sonraki adıma taşınmaz.</p><p>⭐ 3. Kodlaması basittir. Veri bir kez düzenlenir, model tek seferde öğrenir.</p><p><strong>Zayıf yanlar</strong><br>❗ 1. Uzak adımların doğruluğu genelde zayıftır. Örneğin t+20, t+24 gibi ileri hedeflere ait gerçek bilgiler sınırlıdır.</p><p>❗ 2. Bütün hedefler aynı model tarafından öğrenildiği için bir geleceğin hatası, diğer geleceği de etkileyebilir.</p><p>❗ 3. Derin öğrenme veya karmaşık modeller kadar esnek değildir. Linear Regression gibi lineer modeller karmaşık ilişkileri yakalayamaz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*D84xBFoEDDYTM9OwTNiWLQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20caa672d7a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/t%C3%BCrkiye/zaman-serilerinde-%C3%A7oklu-multi-output-tahmin-y%C3%B6ntemi-20caa672d7a3">Zaman Serilerinde Çoklu (Multi-Output) Tahmin Yöntemi</a> was originally published in <a href="https://medium.com/t%C3%BCrkiye">Türkçe Yayın</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zaman Serilerinde İteratif (Yinelemeli), Çok Adımlı Tahmin Yöntemi]]></title>
            <link>https://medium.com/t%C3%BCrkiye/zaman-serilerinde-i%CC%87teratif-yinelemeli-%C3%A7ok-ad%C4%B1ml%C4%B1y%C3%B6ntemle-tahmin-400331812951?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/400331812951</guid>
            <category><![CDATA[türkçe]]></category>
            <category><![CDATA[recursive-function]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[zaman-serisi-tahmin-model]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 20:05:04 GMT</pubDate>
            <atom:updated>2025-12-01T14:15:50.218Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bu yazı, zaman serisi tahminlerinde, iteratif (yinelemeli) çok adımlı yöntemin uygulamasını anlatan, bir eğitim dökümanı olarak tasarlanmıştır. (Recersive Multi-step Forecasting for Time Series) 👉 <a href="https://github.com/nrdnay/Iterative-Multistep-Forecast-Training-For-TimeSeries/blob/main/Iterative-Multistep-Forecast-Training-EN.ipynb">Kodlamaların Tamamı GitHub</a> 👉 <a href="https://medium.com/@aydogdunurdan/zaman-serilerinde-%C3%A7oklu-multi-output-tahmin-y%C3%B6ntemi-20caa672d7a3">Zaman Serilerinde Çoklu (Multi-Output) Tahmin Yöntemi</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*9evm5ylal1GhedTzRP02Dg.png" /></figure><p><strong>Matematikte iterasyon</strong>, genellikle bir işlemin noktasal ya da fonksiyonel olarak sabit bir sonuca veya çözüme yaklaşana kadar yinelenmesidir (tekrarlanmasıdır). <strong>Programlamada iterasyon döngüler (loops)</strong> kullanılarak gerçekleştirilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*WCphMkXh5izvY2tsEOslKw.png" /><figcaption>Kodlamada iterasyon, döngülerle (loops) oluşturuluyor.</figcaption></figure><p>Belirli bir değişken için farklı zaman periyotlarında (günlük, haftalık, aylık, yıllık gibi) toplanan verilere <strong>“zaman serisi” </strong>verileri denir. Zaman serileriyle çalışırken yaygın olarak, gelecekteki bir aralığın (t+1, …, t+n) veya zaman içindeki uzak bir noktanın (t+n) tahmin edilmesi amaçlanır. Örneğin ekonometride zaman serisi kullanılarak bir hisse senedinin açılışta veya uzun vadede fiyatı öngörülür.</p><p>Modellemede, ileriyi -t(n)- tahmin etmek için, önceki değerlere -t(n-1)- ihtiyaç duyulur. O nedenle, iteratif çok adımlı tahmin yönteminde, zaman serisi periyoduna bağlı olarak (günlük, aylık…), her yeni tahminin bir önceki tahmine dayandığı yinelemeli bir süreç uygulanır.</p><p>Basitçe anlamak için elimizde bir kitabın son 12 aya ait fiyat listesinin olduğunu varsayalım. Oluşturduğumuz model ile kitabın “bir sonraki ay” (ay+1) fiyatı tahmin ediliyor. Modeli iteratif olarak kurguladığımızda ise, ay+1 (gelecek ay) tahmini, mevcut 12 aylık listenin sonuna ekleniyor. Liste 13 elemanlı oluyor. 12 fiyat için kurgulanan modelde, listedeki ilk fiyat, yeni tahminlemede model dahil edilmiyor. Yani yeni tahmin, listedeki güncel son 12 değeri alarak, bu kez ay+2 ‘yi (1 ay sonrayı) tahminliyor ve listenin sonuna eklenerek, bir sonraki tahmin için girdilerde yerini alıyor. Tekrar son 12 ay alınıp, ay+3 tahmin edilip listeye eklenerek, ay+4 tahminine girdi oluşturuyor ve böylece gelecek 24 ay tahmini için, işlem 24 kere tekrarlanıyor. Bu işlem, <strong>Yinelemeli Çok Adımlı Tahmin (Recursive / Iterative Multi-step Forecasting)</strong> olarak adlandırılıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*S8-nR90z1KhzeFbawtfxxg.png" /><figcaption>Özyinelemeli (iteratif) Çok Adımlı Tahmin İlerleyişi</figcaption></figure><blockquote><em>Her iterasyon, daha önceki iterasyonların başarı ve başarısızlıklarından etkilenir. İteratif yöntem ilerledikçe, hatalı tahminler de girdiye eklendiği için tahmin hataları (hata birikimi) artabilir. Bu önemli bir dezavantaj oluşturur.</em></blockquote><h3>1) Neden iteratif yöntem tercih edilir?</h3><ul><li>Basit ve yaygındır. Tek adım sonrasını (gelecek ay, yıl gibi) tahmin için eğtilen model, iterasyon ile çok adım tahmin için (gelecek aylar, yıllar vs.) kullanılabilir.</li><li>Eğitim verisi ve model daha basittir ve dolayısıyla ekonomiktir. Çünkü çok-adımlı ayrı bir model eğitmek yerine tek model yeterlidir.</li><li>Eğer model, bir sonraki adım tahminini yapmayı çok iyi öğrenmişse, kısa-orta vadede kuvvetli iteratif tahminlerde bulunabilir.</li><li>Eğer eğitim seti küçükse, çok-adımlı doğrudan modeller için yeterli olmayabilir. O nedenle iteratif yöntem tercih edilir.</li></ul><h3>2) İteratif Yerine Alternatif Yöntemler :</h3><ul><li><strong>Direct (doğrudan)</strong>: Her hedef adım için ayrı bir model eğitilir (t+1 için bir model, t+2 için başka model…). Dezavantaj: daha çok model, daha çok veri, daha çok enerji gerektirir.</li><li><a href="https://medium.com/@aydogdunurdan/zaman-serilerinde-%C3%A7oklu-multi-output-tahmin-y%C3%B6ntemi-20caa672d7a3"><strong>Multi-output</strong></a><strong> </strong>: Tek bir model, aynı anda çoklu adımları çıktı olarak verir (ör. model çıktısı bir vektör: [t+1, t+2, …, t+24]).</li><li><strong>Sequence-to-sequence</strong> modeller: LSTM seq2seq, Transformer tabanlı modeller doğrudan çok adımlı tahmin yapabilir.</li><li><strong>Bazı hibrid yöntemler:</strong> iteratif + düzeltme, ensembler’lar vb.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*bgMVtTbyuvkr-72ITaiP0A.png" /><figcaption>Which side?</figcaption></figure><h3>3) İteratif yöntemin tercih edildiği durumlar</h3><p><strong>a)</strong> <strong>Hangi</strong> <strong>Durum</strong>: Eğitim verisi azsa; modelin tek-adım performansı iyiyse; veya çoklu adım için ayrı modeller kurmak pratik değilse.</p><p><strong>b)</strong> <strong>Hangi Veri Tipi</strong>: Düzenli zaman aralıklı veriler (aylık/günlük/saatlik gibi.). Özellikle kısa/orta vadeli tahminler için kullanışlıdır. Mevsimsellik veya trend varsa ve tek adım öğrenilebiliyorsa tercih edilir.</p><p><strong>c)</strong> <strong>Hangi</strong> <strong>Modelleme</strong>: Basit regresyon, AR modelleri, veya tek-adım öğrenebilen makine öğrenmesi modelleri ile kullanışlı.</p><p><strong>d)</strong> <strong>Hangi</strong> <strong>Uygulamalar</strong>: Finans (kısa vadeli fiyat tahminleri), enerji talep tahmini (kısa dönem), envanter tahmini, sensör verisi tahmini, vb.</p><h3>4) İterasyon Mantığı :</h3><ol><li>Tercih edilen model eğitilirken, girdi olarak geçmiş son k (lags/adım) değeri (örneğin son 12 ay) kullanılır. Çıktı olarak ise bir adım sonraki (t+1) değer tahmin edilir. Örneğin 13. ayın (12+1) değeri gibi.</li><li>Diğer bir deyişle, çok adımlı tahmin için başlangıç olarak son k (lags/adım) değeri alınır. (Örneğin son 12 ay).</li><li>Model kullanılarak bir sonraki ay (t+1) tahmin edilir ve kaydedilir.</li><li>Geçmiş listesindeki en eski değer atılarak, bu yeni tahmin değeri eklenir. Dolayısıyla örneğimize göre, liste hep 12 elemanlı olarak kalır.</li><li>Listedeki yeni değerlerle tekrar tahmin yapılır(t+2). İstenen adım sayısına ulaşılana kadar 3. adım ve 4. adım tekrarlanır.</li></ol><h3>Genel Sonuç / Öneriler</h3><ul><li>İteratif (one-step-ahead) yöntem <strong>basit</strong>, <strong>anlaşılır</strong>, ve <strong>küçük veri</strong> için uygun. Dezavantajı ise uzun vadede hata birikimi riskidir.</li><li>Eğer uzun vadeli tahmin gerekiyorsa, <strong>direct</strong> veya <strong>seq2seq / multi-output</strong> yaklaşımları da terecih edilebilir.</li><li>Verinin doğası (mevsimsellik, trend, ani değişimler), veri miktarı ve hata toleransı her zaman göz önünde bulundurulmalıdır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C9AxclNbz2FcQBMb.png" /></figure><h3>UYGULAMALI ANLATIMI</h3><p>Daha anlaşılır olmak için bir uygulama örneği le devam edilecektir.<br>Bu amaçla öncelikle, SENTETİK, basit bir aylık fiyat serisi oluşturularak, bir sonraki ayı tahmin eden (<strong>one-step-ahead</strong>), 12 adım gecikmeli (lag 1..12) özellikler girdi olarak kullanılıp model eğitildi. <strong>Basit ve öğretici</strong> olması için Lineer Regresyon modeli tercih edildi. Test performansı hesaplanıp ardından gelecek <strong>24 ay için, iteratif çok adımlı olarak</strong> tahmin modeli oluşturuldu. Yani her adımda bir ay tahmin edilip bu tahmin sonraki adımın girdisi olarak tekrar kullanıldı.<br><br><strong>Çıktının (yapılan tahminin), girdi olarak tekrar sisteme sokulması için, </strong>Seed (başlangıç) listesinde son 12 değer tutulmuştur. Her tahmin, bu seed listesine eklenmiş, sonraki adımda modelin beklediği lag sırasına göre (t−1, t−2, …) bu son tahmin de, yeni tahmin hesaplanmasına dahil edilmiştir. Böylece model “gerçek yerine modelin kendi tahminini” görerek, sonraki adımı hesaplamıştır.</p><p>Kodlamada: seed = last_observed.copy() ile son 12 gözlem alındı.</p><p>Döngüde: x = [t-1, t-2, ..., t-12] oluşturuldu, model.predict ile tahmin alındı, seed.append(pred) ile tahmin geri eklendi.</p><h4>Kod ve kodlamaya ait açıklamar, aşağıda bölüm bölüm anlatılmıştır:</h4><h4>1) Sentetik veri üretimi</h4><pre># ---------- 1) Sentetik veri üretimi ----------<br>import numpy as np<br>import pandas as pd<br><br>np.random.seed(42)<br>periods = 72         # kaç aylık veri üretileceği (72 = 6 yıl)<br>dates = pd.date_range(start=&quot;2019-01-01&quot;, periods=periods, freq=&quot;MS&quot;) # 2019-01-01&#39;den başlayan72 aylık tarih endeksi<br><br>trend = 0.5 * np.arange(periods)                             # basit lineer trend<br>seasonal = 10 * np.sin(2 * np.pi * np.arange(periods) / 12)  # yıllık (12 aylık) mevsimsellik<br>noise = np.random.normal(scale=3.0, size=periods)            # rastgele gürültü (normal dağılım)<br>base = 50<br>prices = base + trend + seasonal + noise<br>series = pd.Series(prices, index=dates, name=&quot;price&quot;)</pre><ul><li><strong>Bu Kısımda Amaç: </strong>örnek göstermek için gerçek dünyaya benzeyen ama kontrol edilebilir bir zaman serisi (fiyat) üretmek.</li><li>np.random.seed(42) — rastgele sayı üreticisinin başlatıcısı (seed). Aynı seed ile çalıştırınca sonuçlar tekrarlanabilir olur. Deneylerin tutarlılığı için kullanılır.</li><li>periods = 72 — toplam gözlem sayısı (ay cinsinden). Bu örnekte 6 yıl * 12 ay = 72.</li><li>pd.date_range(start=&quot;2019-01-01&quot;, periods=periods, freq=&quot;MS&quot;) — baştan ay başlangıçlarını (Month Start) veren tarih dizisi oluşturur. Bu diziyi series’in index’i yapıyoruz ki zaman ekseni doğru olsun.</li><li>np.arange(periods) — 0,1,2,...,periods-1 şeklinde ardışık tamsayı dizisi üretir; trend ve mevsim fonksiyonlarında zaman referansı olarak kullanılır.</li><li>trend = 0.5 * np.arange(periods) — her adımda 0.5 birim artan doğrusal bir trend ekler; böylece zamanla artan fiyat eğilimi oluşturulur.</li><li>seasonal = 10 * np.sin(2 * np.pi * np.arange(periods) / 12) — 12 aylık döngüde sinüs ile mevsimsel dalga üretir (amplitude 10). 2*np.pi/12 bir yıllık periyot sağlar.</li><li>noise = np.random.normal(scale=3.0, size=periods) — normal dağılımdan rastgele gürültü; gerçek verideki rastgelelik/gürültüyü taklit eder.</li><li>Dikkat! trend, seasonal ve noise’a ait çıktıların veri tipi “array’”dir ve her bir array periods ile belirlendiği gibi 72 elemanlıdır.</li><li>base = 50 ve prices = base + trend + seasonal + noise ile nihai fiyat dizisini oluşturuyoruz.</li><li>pd.Series(..., index=dates, name=&quot;price&quot;) — pandas Series, zaman etiketleriyle veriyi saklamak için kullanışlıdır (zaman serisi işlemleri için idealdir).</li></ul><h4>2) Lag (gecikme) özellikleri oluşturma</h4><pre># ---------- 2) Lag özellikleri (1..12) ----------<br>max_lag = 12<br>df = pd.DataFrame(series)<br>for lag in range(1, max_lag + 1):<br>    df[f&quot;lag_{lag}&quot;] = df[&quot;price&quot;].shift(lag)<br>df_clean = df.dropna().copy()  # ilk &#39;max_lag&#39; satırı NaN olur; onları çıkarıyoruz</pre><ul><li><strong>Amaç: </strong>geçmiş değerleri (lag) model girdisi olarak hazırlamak. Autoregresif (AR) tarzı modeller genelde önceki k adet (lag/adım) gözlemi kullanır.</li><li>max_lag = 12 — modelin bir tahmin için kaç geçmiş değeri kullanacağı (burada 12 ay).</li><li>df = pd.DataFrame(series) — Series&#39;i DataFrame&#39;e çeviriyoruz, böylece hem orijinal price hem de lag_* sütunları bir arada olur.</li><li>Döngüde df[&quot;price&quot;].shift(lag) — pandas shift fonksiyonu sütunu yukarı kaydırır; örn. lag_1 t−1, lag_2 t−2 değerini verir. Bu, supervised learning (gözetimli öğrenme) için geçmiş değerler → hedef (next value) şeklinde özellik yaratır.</li><li>df.dropna() — ilk max_lag satırın bazı lag_* değerleri NaN olur (çünkü geriye dönük değer yok), bunları çıkarıyoruz. copy() performans uyarılarını engeller ve bağımsız kopya oluşturur.</li></ul><h4>3) Train / Test split (eğitim ve test verisi ayrımı)</h4><pre># ---------- 3) Train / Test split ----------<br>train_rows_after_dropna = 48  # dropna sonrası kaç satırı train olarak kullanacağımız (örneğin)<br>total_after = df_clean.shape[0]<br><br># basit güvenlik kontrolü<br>if train_rows_after_dropna + 12 &gt; total_after:<br>    raise ValueError(&quot;train_rows_after_dropna + 12 (test) exceed available rows after dropna. Adjust periods or train size.&quot;)<br><br>train = df_clean.iloc[:train_rows_after_dropna]<br>test = df_clean.iloc[train_rows_after_dropna:]<br><br>X_train = train[[f&quot;lag_{i}&quot; for i in range(1, max_lag + 1)]].values<br>y_train = train[&quot;price&quot;].values<br>X_test = test[[f&quot;lag_{i}&quot; for i in range(1, max_lag + 1)]].values<br>y_test = test[&quot;price&quot;].values<br>test_index = test.index</pre><ul><li><strong>Bu Adımda Amaç:</strong> modeli eğitirken geçmiş verileri (train) kullanmak ve eğitilmiş modelin performansını daha önce görmediği veriler (test) üzerinde ölçmek.</li><li>train_rows_after_dropna = 48 — dropna işleminden sonra ilk 48 satırı eğitim, sonraki 12 satırı test olarak kullanıyoruz. Bu, zaman serisine özgü bir ayrıştırmadır (zamana göre sıralı split).</li><li>df_clean.shape[0] — dropna sonrası toplam satır sayısını verir; güvenlik kontrolü ile test ve train boyutlarının uygun olduğundan emin oluyoruz.</li><li>train = df_clean.iloc[:train_rows_after_dropna] — sıralı olarak ilk N satırı alıyoruz (time series&#39;te random shuffle yapmayız çünkü zaman bağımlılığı var).</li><li>X_train = train[[f&quot;lag_{i}&quot; ...]] — modelin girdi matrisi; .values ile NumPy dizisine çeviriyoruz çünkü sklearn NumPy bekler.</li><li>y_train = train[&quot;price&quot;].values — hedef değişken (bir sonraki adımın fiyatı), yine NumPy dizisi.</li><li>test_index = test.index — sonuçları sunarken tarihleri kullanmak için saklıyoruz.</li></ul><h4>4) Model eğitimi (Linear Regression — autoregresif)</h4><pre># ---------- 4) Model eğitimi (Linear Regression - autoregresif) ----------<br>from sklearn.linear_model import LinearRegression<br><br>model = LinearRegression()<br>model.fit(X_train, y_train)</pre><ul><li><strong>Bu Adımda Amaç:</strong> geçmiş lag değerleri ile bir sonraki değeri (one-step-ahead) öğrenen basit doğrusal model eğitmek.</li><li>Basit, yorumlanabilir ve hızlı oması nedeniyle; eğitim amaçlı bu demoda Lineer Regresyon (LinearRegression) tercih edilmiştir. Gerçek veri ve daha karmaşık ilişkiler için ağaç tabanlı veya sinir ağı modelleri denenebilir.</li><li>from sklearn.linear_model import LinearRegression — scikit-learn kütüphanesinden doğrusal regresyon sınıfını getirir.</li><li>model = LinearRegression() — model nesnesi oluşturulur. Bu model girdi (özellikler) ile hedef arasında lineer ilişki varsayar: y ≈ w0 + w1*x1 + ....</li><li>model.fit(X_train, y_train) — eğitim verisiyle model parametreleri öğrenilir (en küçük kareler yöntemiyle katsayılar hesaplanır).</li></ul><h4>5) One-step-ahead test tahminleri (gerçek lagler ile)</h4><pre># ---------- 5) One-step-ahead test tahminleri (gerçek lag değerleri ile) ----------<br>y_pred_test = model.predict(X_test)</pre><ul><li><strong>Amaç:</strong> modelin, “bir sonraki adımı” doğru tahmin edip etmediğini test verisi üzerinde ölçmek.</li><li>model.predict(X_test) — test setindeki her bir satır için modelin öngördüğü bir sonraki fiyat değeri (one-step-ahead) alınır.</li><li>Önemli nokta: X_test burada gerçek gözlemlerden oluşturulan lag değerlerini içerir (yani modeli bir adım ileri tahmin için, gerçek geçmiş verileriyle test ediyoruz). Bu, <strong>one-step-ahead</strong> doğruluğunu ölçer; iteratif (modelin kendi tahminlerini girdiye eklediği) uzun dönem tahmininin davranışı farklı olabilir.</li></ul><p><strong>6) Performans metrikleri hesaplama</strong></p><pre># ---------- 6) Performans metrikleri ----------<br>from sklearn.metrics import mean_squared_error, mean_absolute_error<br>import math<br>import numpy as np<br><br>def mape(y_true, y_pred):<br>    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100<br><br>rmse_test = math.sqrt(mean_squared_error(y_test, y_pred_test))<br>mae_test = mean_absolute_error(y_test, y_pred_test)<br>mape_test = mape(y_test, y_pred_test)<br><br>print(&quot;Test performansı:&quot;)<br>print(f&quot; RMSE: {rmse_test:.4f}&quot;)<br>print(f&quot; MAE : {mae_test:.4f}&quot;)<br>print(f&quot; MAPE (%): {mape_test:.2f}&quot;)</pre><ul><li><strong>Amaç:</strong> Tahminlerin doğruluğunu farklı metrikler ile nicel olarak ölçmek.</li><li>mean_squared_error (MSE) ve mean_absolute_error (MAE) scikit-learn fonksiyonlarıdır; rmse için MSE karekökü alıyoruz.</li><li><strong>RMSE</strong> (Root Mean Squared Error): hataların karelerinin ortalamasının karekökü; büyük hatalara daha ağır ceza verir.</li><li><strong>MAE</strong> (Mean Absolute Error): hataların mutlak değerlerinin ortalaması; daha direkt ve uç değerlere daha az duyarlıdır.</li><li><strong>MAPE</strong> (Mean Absolute Percentage Error): hatanın yüzde olarak ortalamasını verir; hedef değerlerin sıfıra yakın olmadığı durumlarda anlamlıdır.</li><li>math.sqrt(...) — karekök alır.</li><li>np.abs(...) — mutlak değer alır.</li><li>Bu metrikler modelin one-step-ahead doğruluğunu gösterir. İteratif tahminlerin kalitesini değerlendirirken referans olur.</li></ul><p><strong>7) İteratif 24 aylık forecast (tahminleri geri besleyerek çok adımlı tahmin)</strong></p><pre># ---------- 7) İteratif 24 aylık forecast ----------<br>forecast_horizon = 24  # kaç ay ileri tahmin edilecek<br>last_observed = df[&quot;price&quot;].iloc[-max_lag:].values.tolist()  # son max_lag gözlemini seed olarak al<br>iter_preds = []<br>iter_dates = pd.date_range(start=df.index[-1] + pd.offsets.MonthBegin(1), periods=forecast_horizon, freq=&quot;MS&quot;)<br><br>seed = last_observed.copy()<br>for i in range(forecast_horizon):<br>    # modelin beklediği sıra: [t-1, t-2, ..., t-12]<br>    x = np.array([seed[-1 - k] for k in range(max_lag)])<br>    x = x.reshape(1, -1)<br>    pred = model.predict(x)[0]<br>    iter_preds.append(pred)<br>    seed.append(pred)  # tahmini seed&#39;e ekle -&gt; bir sonraki adımda kullanılır<br><br>forecast_series = pd.Series(iter_preds, index=iter_dates, name=&quot;forecast&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vbuqns7W682pgOt1d6MPWw.gif" /></figure><ul><li><strong>Amaç: </strong>Tek adımlık (one-step) modeli kullanarak ardışık 24 aylık tahmin üretmek. Her adımda modelin tahmini <strong>geri beslenir</strong> ve bir sonraki adım için girdi olarak kullanılır — buna <strong>iteratif</strong> (veya recursive) multi-step forecasting denir.</li><li>last_observed = df[&quot;price&quot;].iloc[-max_lag:].values.tolist() — son gözlemleri alıp başlangıç seed’i oluşturuyoruz; seed başlangıçta gerçek gözlemler içerir.</li><li>iter_dates — tahminlerin hangi tarihlere karşılık geldiğini oluşturur (son gözlem tarihinden sonraki aylar).</li><li><strong>Döngü mantığı:</strong></li><li>x = np.array([seed[-1 - k] for k in range(max_lag)]) — modelin beklediği sırada (t-1, t-2, ...) bir girdi vektörü oluşturur. k değeri 1&#39;den 12&#39;ye (yani max_lag’e) kadar. Her seferinde son 12 değer alınıyor.</li><li>x.reshape(1, -1) — ile 1 satır ve 12 (max_lag) sütundan oluşan 2 boyutlu bir Numpy dizisi oluşturuyoruz. Böylece her bir satırdaki x kolonlarına karşılık gelen bir y değeri oluşturup, her bir tarih için alına y değerini öğrenecek şekilde eğitip, tahmin yaparken tek bir adımla periyottaki ilk tarihe karşılık gelen değeri tahmin ettirebileceğiz.</li><li>model.predict(x) ile tek adımlık tahmini alırız.</li><li>Tahmini seed.append(pred) ile seed’e ekleriz; dolayısıyla sonraki adım modelin bir önceki tahminini, geçmiş değer olarak kullanır.</li><li><strong>Dezavantaj :</strong> iteratif stratejide tahmin hataları zamanla birikebilir (öngörü hatası sonraki adımların girdisi olduğundan). Bu yüzden uzun vadede hata artışı beklenebilir.</li></ul><h4>8) Sonuçları tablo ve grafik olarak kaydetme</h4><pre># ---------- 8) Sonuçları tablo ve grafik olarak kaydetme ----------<br>import matplotlib.pyplot as plt<br>import os<br><br># Tablo formatları<br>observed_df = pd.DataFrame({&quot;price&quot;: series})<br>test_results = pd.DataFrame({&quot;actual&quot;: y_test, &quot;predicted_one_step&quot;: y_pred_test}, index=test_index)<br>forecast_df = pd.DataFrame({&quot;forecast&quot;: iter_preds}, index=iter_dates)<br><br># Colab-uyumlu çıktı klasörü<br>output_dir = &quot;./outputs&quot;<br>os.makedirs(output_dir, exist_ok=True)<br><br># CSV olarak kaydet (isteğe bağlı)<br>test_results.to_csv(os.path.join(output_dir, &quot;test_results.csv&quot;), index=True)<br>forecast_df.to_csv(os.path.join(output_dir, &quot;24mo_forecast.csv&quot;), index=True)<br><br># Grafik: orijinal seri, test tahminleri (one-step) ve iteratif forecast<br>plt.figure(figsize=(12,5))<br>plt.plot(observed_df.index, observed_df[&quot;price&quot;], label=&quot;Gerçek&quot;)<br>plt.plot(test_results.index, test_results[&quot;predicted_one_step&quot;], linestyle=&#39;--&#39;, label=&quot;Test one-step tahmin&quot;)<br>plt.plot(forecast_df.index, forecast_df[&quot;forecast&quot;], linestyle=&#39;:&#39;, label=f&quot;{len(iter_preds)}-ay iteratif tahmin&quot;)<br>plt.title(&quot;Fiyat Zaman Serisi — Gerçek, Test Tahmini (one-step) ve İteratif Tahmin&quot;)<br>plt.xlabel(&quot;Tarih&quot;)<br>plt.ylabel(&quot;Fiyat&quot;)<br>plt.legend()<br>plt.tight_layout()<br><br>plot_path = os.path.join(output_dir, &quot;price_forecast_plot.png&quot;)<br>plt.savefig(plot_path)<br>plt.show()<br>plt.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FO9vz5hg60UBbZVeIRcdcA.png" /><figcaption>Tüm Sonuçlar</figcaption></figure><ul><li><strong>Amaç:</strong> sonuçları hem tablo (CSV) hem de grafik olarak saklamak ve görselleştirmek.</li><li>observed_df — tüm orijinal zaman serisini tutar; grafik çiziminde referans.</li><li>test_results — test dönemi için gerçek değerleri ve modelin one-step tahminlerini saklar; CSV olarak kaydedilip detaylı analize açılabilir.</li><li>forecast_df — iteratif olarak üretilen 24 aylık tahminleri tarihleriyle beraber tutar.</li><li>os.makedirs(output_dir, exist_ok=True) — Colab ortamında ./outputs klasörünü oluşturur (varsa hata vermez). /mnt/data uyumsuzluğu nedeni ile Colab’ta bu yol daha güvenlidir.</li><li>to_csv(...) — tabloları CSV dosyası olarak kaydeder; sonrasında indirip Excel veya başka araçlarda analiz edilebilir.</li><li>Grafik çizimi:</li><li>plt.plot ile gerçek seri, test dönemi tahminleri ve iteratif tahminleri aynı grafikte gösteriyoruz; görsel kıyaslama kolay olur.</li><li>plt.savefig(plot_path) — plot ile çizilen grafiği (görseli) dosyaya yazdırır.</li><li>plt.show() — Colab hücresinde görseli anında gösterir.</li><li>Bu bölüm, modelin davranışını hem sayısal (CSV) hem de görsel (PNG) olarak kalıcı hale getirir; böylece sonuçları paylaşmak, raporlamak ya da daha ileri analiz yapmak kolaylaşır.</li></ul><h3>Küçük Sözlük: sık kullanılan objeler / fonksiyonlar ve kısa açıklamalar</h3><ul><li>np.random.seed(seed) — rastgele sayı üretecini başlatır; aynı seed = tekrar üretilebilir sonuçlar.</li><li>pd.date_range(start, periods, freq) — zaman indeksleri oluşturur; freq=&quot;MS&quot; = Month Start.</li><li>np.arange(n) — 0..n-1 şeklinde ardışık tamsayı dizisi.</li><li>np.sin, np.pi — trigonometrik fonksiyonlar; mevsimsel paterni oluşturmak için kullanılır.</li><li>pd.Series(data, index, name) — tek sütunlu zaman serisi veri yapısı; index genelde datetime olursa zaman serisi işlemleri kolay olur.</li><li>df[&#39;col&#39;].shift(k) — sütunu k kaydırır; geçmiş değerleri lag olarak üretmek için kullanılır.</li><li>df.dropna() — NaN içeren satırları kaldırır.</li><li>DataFrame.iloc — satır/kolonları konumsal olarak seçer (zaman serisi için sıralı seçme yapılır).</li><li>sklearn.linear_model.LinearRegression — doğrusal regresyon modeli.</li><li>model.fit(X, y) — modeli eğitir; model.predict(X) — tahmin yapar.</li><li>mean_squared_error, mean_absolute_error — hataları ölçen fonksiyonlar.</li><li>plt.figure, plt.plot, plt.savefig, plt.show — matplotlib ile görselleştirme ve dosyaya kaydetme.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*KiOH4t_SLupCSJa3MwM58g.gif" /><figcaption>I have no idea what you’re saying. But count me in!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=400331812951" width="1" height="1" alt=""><hr><p><a href="https://medium.com/t%C3%BCrkiye/zaman-serilerinde-i%CC%87teratif-yinelemeli-%C3%A7ok-ad%C4%B1ml%C4%B1y%C3%B6ntemle-tahmin-400331812951">Zaman Serilerinde İteratif (Yinelemeli), Çok Adımlı Tahmin Yöntemi</a> was originally published in <a href="https://medium.com/t%C3%BCrkiye">Türkçe Yayın</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Amid Uncertainty: A Machine Learning Approach to Predicting Brent Crude Oil Prices]]></title>
            <link>https://medium.com/the-random-nerdiness-collective/forecasting-amid-uncertainty-a-machine-learning-approach-to-predicting-brent-crude-oil-prices-0ac2a7b64151?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ac2a7b64151</guid>
            <category><![CDATA[brent-crude-oil-price-api]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 18:40:00 GMT</pubDate>
            <atom:updated>2025-12-16T21:18:14.061Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>An empirical, data-driven application of the XGBoost model for forecasting energy prices under economic and geopolitical uncertainty</em></h4><blockquote>👉 <a href="https://medium.com/@aydogdunurdan/belirsizlik-i%CC%87%C3%A7indetahmin-makine-%C3%B6%C4%9Frenmesi-ile-brent-petrol-fiyatlar%C4%B1na-%C3%B6ng%C3%B6r%C3%BCc%C3%BC-bir-yakla%C5%9F%C4%B1m-0db8768f9847"><strong><em>Türkçe için / Turkish</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*iUyGhONL0EHjLq3EDz1CtQ.jpeg" /></figure><h3>Introduction</h3><h4>Economic Importance and Price Volatility of Brent Crude Oil</h4><p><strong>Oil</strong>, as one of the world’s primary energy sources, plays a decisive role in shaping global trade structures, geopolitical risks, energy supply-demand balances, and economic growth indicators. In this context, <strong>Brent Crude (Brent) Oil</strong>— sourced from the North Sea fields of the UK and Norway — serves as a key benchmark for global oil pricing and energy markets. Its price movements directly influence not only energy markets but also financial markets, industrial production, transportation, agriculture, and consumer prices. A significant share of the oil extracted in Europe, Africa, and the Middle East is traded based on Brent price benchmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*1AsfW4UtfRogAELWluKcnA.png" /><figcaption>Daily Brent Oil USD prices from 1987 to the present, obtained from the EIA</figcaption></figure><p>Although oil prices are largely determined by supply and demand dynamics, many other factors — such as economic and political developments, wars, production quotas, supply-demand shocks, security risks, and currency fluctuations — can have a substantial impact on prices. <strong>Because these factors are often unpredictable, difficult to measure, sudden, or highly uncertain, forecasting Brent prices with traditional deterministic models becomes increasingly challenging.</strong> For instance, when a major oil-producing country unexpectedly decides to cut supply, prices fluctuate rapidly — and such unpredictable shocks cannot be incorporated into classical forecasting methods.</p><p><strong>Machine learning methods</strong>, however, stand out as powerful tools for modeling such complex, multivariable, and dynamic problems. But how well can these methods handle the high volatility of Brent oil? How close can the forecasts get to reality? Can they be relied upon as a standalone decision-making tool? And how can these models be further improved?</p><p><strong>In this study, the machine learning-based XGBoost forecasting mode</strong>l was selected among three tested models <strong>to predict the future trajectory of Brent oil prices over a 24-month horizon.</strong> And the results were evaluated and opened for discussion.</p><blockquote><em>👉 </em><a href="https://github.com/nrdnay/Brent_Oil_Price_Prediction"><strong><em>See the full code on GitHub.</em></strong></a></blockquote><h3>Methods : Dataset, Preprocessing, and Model Selection</h3><p>For price forecasting, the dataset included <strong>Brent oil prices</strong> obtained from the U.S. Energy Information Administration (<strong>EIA</strong>) and the <strong>U.S. Dollar Index</strong> from U.S. Federal Reserve (<strong>FED</strong>) via Federal Reserve Economic Data (<strong>FRED</strong>). The data were extracted as daily data from 1987 to the present. Missing values were handled using a forward-backward fill method.</p><p>The two datasets were then aligned on the same time axis, and a common analysis period starting from 1987 was established. The frequency of the data was converted to monthly intervals to create the input structure for the forecasting model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCYkgOb6qvJUyYdRHubcGw.png" /><figcaption>Brent oil prices obtained from the EIA and the Dolar Index values from the FED via FRED. (Data up to 1989 is shown.)</figcaption></figure><p>The inclusion of the Dollar Index is based on the fact that crude oil is priced globally in U.S. dollars. Historically, when the dollar appreciates, oil prices tend to decline, and when the dollar weakens, oil prices tend to rise. This inverse correlation contributes to improved predictive performance in the model.</p><p>A <strong>logarithmic transformation</strong> followed by <strong>differencing (log-diff)</strong> is applied to the data for three main reasons:</p><ul><li>Raw price series are non-stationary; transforming them into log-differenced series makes them stationary, enabling the model <strong>to learn changes</strong> rather than levels.</li><li>The transformation reduces trends and seasonality effects.</li><li>It normalizes the data, improving model learning efficiency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bwkeu00Bs-vS8_m7cjuyhw.png" /><figcaption>After applying log and diff transformations to the data</figcaption></figure><p>Additionally, <strong>feature engineering</strong> is applied to create <strong>lagged features</strong> and <strong>rolling mean variables</strong>, allowing the model to capture temporal dependencies and better learn historical price behaviors.</p><p>Three models are evaluated in this study:</p><ul><li><strong>Scikit-Learn RandomForestRegressor</strong></li><li><strong>TensorFlow-based LSTM</strong></li><li><strong>XGBoost Regressor</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFlQkmfA5vjSBWKG0QBWfw.png" /><figcaption>Comparison of Brent oil price predictions by 3 models for the past 3 years with actual prices</figcaption></figure><p>The Random Forest model performs well in speed but struggles to capture long-term trends. The LSTM model, while powerful, requires meticulous hyperparameter tuning and incurs high computational costs. Ultimately, the <strong>XGBoost model</strong> is selected for its balanced error rate, consistent performance, and practical ease of application.</p><h3>Results : 24-Month Forecasting Process and Challenges</h3><p>After training, the model generates <strong>24-month-ahead forecasts</strong> for Brent crude oil prices. These forecasts are derived using historical patterns in both the dollar index and the log-differenced Brent price series. <strong>Each month’s predicted log-diff value is iteratively added to the previous estimate to generate the next month’s input, forming a chained sequence of forward predictions.</strong> This iterative mechanism allows the model to simulate future price dynamics based on its own evolving outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3jFwtHv3piWLFEm3P5u1A.png" /><figcaption>Brent oil prices from 1987 to the present and forecasts for the next 2 years using XGBoost.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIVZK-ltP1JQfy6Tb6s1MQ.png" /><figcaption>Price predictions for the next two years made with the XGBoost model.</figcaption></figure><p>The results demonstrate that when combined with data preprocessing and feature engineering, the <strong>XGBoost model</strong> provides meaningful forecasts. It performs particularly well in capturing patterns within historical price movements.</p><p>The predicted log-differenced values are converted back to original price levels through inverse transformations, enabling visualization of the forecasts in actual Brent price terms.</p><h3>Discussion : Forecast Reliability and Model Improvement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbgr4tzwHzkRVhwONC6gDg.jpeg" /><figcaption>Can the future be accurately predicted?</figcaption></figure><p>Although the<strong> XGBoost model effectively learns from historical data, it cannot predict future prices with complete accuracy.</strong> Key limitations include:</p><ul><li>Geopolitical developments, supply-demand shocks, and natural disasters cannot be pre-defined in the model.</li><li>The model is limited to past price and dollar index data, restricting its ability to account for unprecedented new events.</li><li>Sudden market disruptions cannot be captured purely from historical statistical behavior.</li></ul><blockquote><em>Thus, the model’s forecasts should be interpreted as </em><strong><em>probabilistic predictions</em></strong><em>, not deterministic outcomes. They tend to be </em><strong><em>more accurate during stable periods</em></strong><em> but exhibit </em><strong><em>higher deviations during times of external shocks</em></strong><em>. For example, an unexpected geopolitical crisis — such as Russia’s invasion of Ukraine — could cause prices to diverge dramatically from model projections.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*i8eqLEZS7HJlpdnW6sdn4A.png" /></figure><p>Future improvements to enhance model accuracy may include:</p><ul><li>Incorporating additional macroeconomic and market variables such as geopolitical risk indices, inventory levels, and supply-demand balances.</li><li>Exploring <strong>hybrid approaches</strong> that combine models like LSTM and XGBoost.</li><li>Implementing <strong>Bayesian or scenario-based forecasting</strong> methods that provide probabilistic distributions of outcomes.</li></ul><h3>Conclusion</h3><p>This study provides a practical example of how machine learning techniques can be structured for forecasting <strong>Brent crude oil prices</strong>. Specifically, when integrated with data preprocessing, logarithmic transformation, differencing, and feature engineering, the <strong>XGBoost model</strong> can produce meaningful forward-looking predictions.</p><p>However, results should be interpreted with caution, acknowledging that the model relies exclusively on historical data and does not incorporate unforeseen shocks.<br> Given the inherent uncertainty of energy markets — driven by geopolitical risks, supply disruptions, and financial crises — the model’s forecasts represent <strong>probabilistic insights rather than absolute predictions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*KfUS1ZV6QT8dtXnga9kClQ.jpeg" /><figcaption>Does past data reflect the future?</figcaption></figure><p>Considering the strategic importance of energy prices, such models can serve as valuable <strong>decision-support tools</strong> for policymakers, investors, and industry planners — yet they should complement, not replace, broader economic judgment and scenario analysis.</p><h4>Sorces &amp; Linkes</h4><ul><li>Federal Reserve Economic Data<strong> (FRED)</strong> — <strong><em>EIA</em></strong><em> Brent Crude Oil Prices (1987–present)</em></li><li><strong>U.S. Federal Reserve (FrED)</strong> — <strong>FED</strong> <em>U.S. Dollar Index</em></li><li>👉 <a href="https://github.com/nrdnay/Brent_Oil_Price_Prediction"><strong>GitHub (Coding)</strong></a></li><li>👉 <a href="https://medium.com/@aydogdunurdan/belirsizlik-i%CC%87%C3%A7indetahmin-makine-%C3%B6%C4%9Frenmesi-ile-brent-petrol-fiyatlar%C4%B1na-%C3%B6ng%C3%B6r%C3%BCc%C3%BC-bir-yakla%C5%9F%C4%B1m-0db8768f9847"><strong>Medium Türkçe Versiyon (Turkish Method Discussion)</strong></a></li></ul><p><strong>Modeling Methodology:</strong><br> Feature Engineering + Log-Differencing + XGBoost Regressor + Iterative 24-Month Forecast Chain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*KAggSJDrOolX-Ru-sADUzw.gif" /><figcaption>You’re absolutely right.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ac2a7b64151" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-random-nerdiness-collective/forecasting-amid-uncertainty-a-machine-learning-approach-to-predicting-brent-crude-oil-prices-0ac2a7b64151">Forecasting Amid Uncertainty: A Machine Learning Approach to Predicting Brent Crude Oil Prices</a> was originally published in <a href="https://medium.com/the-random-nerdiness-collective">The Creative Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Belirsizlik Ortamında Tahmin: Makine Öğrenmesi ile Brent Petrol Fiyat Öngörüsü]]></title>
            <link>https://medium.com/t%C3%BCrkiye/belirsizlik-i%CC%87%C3%A7indetahmin-makine-%C3%B6%C4%9Frenmesi-ile-brent-petrol-fiyatlar%C4%B1na-%C3%B6ng%C3%B6r%C3%BCc%C3%BC-bir-yakla%C5%9F%C4%B1m-0db8768f9847?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0db8768f9847</guid>
            <category><![CDATA[brent-petrol-fiyat]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[veri-bilimi]]></category>
            <category><![CDATA[türkçe]]></category>
            <category><![CDATA[makine-öğrenmesi]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 17:38:11 GMT</pubDate>
            <atom:updated>2025-10-17T14:54:31.317Z</atom:updated>
            <content:encoded><![CDATA[<h4>XGBoost modeli kullanılarak ekonomik ve jeopolitik belirsizlik ortamında enerji fiyatlarının öngörülmesine yönelik, veriye dayalı bir uygulama</h4><blockquote>👉 <a href="https://medium.com/@aydogdunurdan/forecasting-amid-uncertainty-a-machine-learning-approach-to-predicting-brent-crude-oil-prices-0ac2a7b64151"><strong>For English / İngilizce</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*iUyGhONL0EHjLq3EDz1CtQ.jpeg" /></figure><h4><strong>Giriş : Brent Petrolün Ekonomik Önemi ve Fiyat Değişkenliği</strong></h4><p><strong>Petrol</strong>, temel enerji kaynaklarından biri olarak küresel ticaretin işleyişi, jeopolitik dengeler, arz-talep dinamikleri ve ekonomik büyüme üzerinde belirleyici bir rol oynuyor. Bu çerçevede, kaynağı kuzey denizi (İngiltere, Norveç sahaları) <strong>Brent (Brent Ham) Petrol</strong> fiyatları, dünya genelinde enerji piyasaları için referans niteliğinde bir gösterge olarak yakından izleniyor. Fiyat hareketleri yalnızca enerji sektörünü değil; finansal piyasaları, sanayi üretimini, ulaştırma, tarım ve tüketici fiyatlarını da doğrudan etkiliyor. Özellikle Avrupa, Afrika ve Orta Doğu bölgelerinde üretilen petrolün önemli bir bölümü Brent fiyatlarına endeksli olarak işlem görüyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*1AsfW4UtfRogAELWluKcnA.png" /><figcaption>EIA’dan alınan, 1987‘den günümüze kadar olan günlük Brent Petrol USD/varil fiyatları</figcaption></figure><p>Fiyatlar büyük oranda arz-talep dengesine dayansa da, savaşlar, ekonomik — politik gelişmeler, üretim kotaları, güvenlik riskleri, döviz hareketleri gibi faktörler fiyatlar üzerinde etkili olabiliyor. <strong>Bu öngörülemeyen, ölçülemeyen, ani gelişen, yüksek belirsizlik taşıyan faktörler nedeniyle, Brent petrol fiyatlarının geleneksel kural tabanlı, lineer yöntemlerle tahmin edilmesi oldukça zorlaşıyor. </strong>Örneğin, büyük bir petrol üreticisi ülke beklenmedik bir şekilde arzı kısmaya karar verdiğinde, fiyatlar hızla dalgalanmalar görülür, ancak tahminleme yapılırken bu kısıtlama öngörülemediği için tahmin yöntemlerine dahil edilemez.</p><p>Bu tür karmaşık, çok değişkenli ve dinamik problemlerin modellenmesinde <strong>makine öğrenmesi yöntemleri,</strong> önemli bir araç olarak öne çıkıyor. Peki yüksek volatilite gösteren brent petrol için bu yöntemler ne kadar iyi çalışır? Tahminler gerçeğe ne kadar yakın olabilir? Bağımsız bir karar alma aracı olarak kullanılabilirler mi? Bu modeller daha da geliştirilebilir mi?</p><p><strong>Bu çalışmada</strong>, <strong>Brent petrol fiyatlarının 24 aylık gelecekteki seyri</strong> hakkında öngörüde bulunmak amacıyla, oluşturulan <strong>3 model </strong>arasından öne çıkan makine öğrenmesi tabanlı <strong>XGBoost tahmin modeli kullanılmış</strong> ve sonuçlar değerlendirilerek tartışmaya açılmıştır.</p><blockquote>👉 <a href="https://github.com/nrdnay/Brent_Oil_Price_Prediction"><strong>Kodlamaların tamamı için GitHub.</strong></a></blockquote><h4><strong>Yöntem : Veri Seti, Ön İşleme ve Model Seçimi</strong></h4><p>Fiyat tahmini için veri seti olarak, <strong>FRED</strong> (Federal Reserve Economic Data) aracılığıyla, <strong>EIA</strong>’dan<strong> </strong>(U.S. Energy Information Administration) alınan <strong>Brent Petrol Fiyat</strong>ları ve <strong>FED </strong>‘den (U.S. Federal Reserve)<strong> </strong>alınan U.S. <strong>Dolar Index</strong> verileri kullanılmıştır. Veriler 1987 yılından günümüze kadar, günlük veriler olarak alınmıştır. Eksik değerler için ileri-geri doldurma (forward-backward fill) yöntemi uygulanmıştır.</p><p>İki veri seti zaman ekseninde uyumlu hale getirilerek 1987 sonrası ortak bir analiz periyodu elde edilmiş ve veri periyodu aylık frekansa dönüştürülerek tahmin modeline girdi oluşturulmuştur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCYkgOb6qvJUyYdRHubcGw.png" /><figcaption>FRED aracılığıyla EIA’dan alınan Brent Petrol ve FED’den alınan Dolar İndeksi değerleri (1989&#39;a kadar olan kısım görülüyor.)</figcaption></figure><p>Dolar endeksinin modele dahil edilmesinin nedeni, petrol fiyatlarının küresel ölçekte <strong>ABD Doları cinsinden</strong> fiyatlanmasıdır. Genel olarak doların küresel değeri arttığında petrol fiyatlarının düşme, dolar zayıfladığında ise artma eğiliminde olduğu gözlenmiştir. Bu ters korelasyon, modelin daha iyi bir tahmin performansı göstermesine katkı sağlamıştır.</p><p>Veri setine <strong>logaritmik dönüşüm</strong> ve ardından <strong>fark alma (log-diff)</strong> işlemi uygulanmıştır. Bunun temel gerekçesi:</p><ul><li>Ham fiyat serilerinin durağan olmaması; (<strong>log ve diff</strong> serileri durağan hale getirerek modelin fiyat seviyesinden ziyade <strong>değişimleri</strong> öğrenmesini sağlıyor)</li><li>Trend ve mevsimsellik etkilerini azaltmak,</li><li>Modelin daha iyi öğrenebilmesi için veriyi normalize etmek.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bwkeu00Bs-vS8_m7cjuyhw.png" /><figcaption>Veriye log ve diff dönüşümleri uygulandıktan sonra</figcaption></figure><p>Ayrıca <strong>özellik mühendisliği (feature engineering)</strong> uygulanarak gecikmeli değişkenler (lag features) ve hareketli ortalama (rolling mean) değişkenleri üretilmiştir. Bu, modelin geçmiş fiyat davranışlarını öğrenebilmesi ve zaman serisi dinamiklerini daha iyi yakalayabilmesi için kritik önem taşıyor.</p><p><strong>Çalışmada üç model incelenmiştir:</strong></p><ul><li><strong>scikit-learn RandomForestRegressor</strong></li><li><strong>TensorFlow tabanlı LSTM</strong></li><li><strong>XGBoost Regressor</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFlQkmfA5vjSBWKG0QBWfw.png" /><figcaption>Kurulan 3 modelin, geçtiğimiz 3 yıl için yaptığı tahminlerin, gerçek fiyatlarla karşılaştırılması</figcaption></figure><p>Random Forest modeli hızlı ama uzun dönemli trendleri yakalamada sınırlı performans göstermiştir. LSTM modeli daha karmaşık yapısı nedeniyle dikkatli hiperparametre ayarı gerektirmiş ve yüksek hesaplama maliyeti yaratmıştır. Nihayetinde <strong>XGBoost modeli</strong>, daha dengeli hata oranı, istikrarlı performansı ve pratik uygulama kolaylığı nedeniyle tercih edilmiştir.</p><h4><strong>Bulgular : 24 Aylık Tahmin Süreci ve Karşılaşılan Zorluklar</strong></h4><p>Model eğitimi tamamlandıktan sonra, geleceğe yönelik <strong>24 aylık Brent petrol fiyat tahmini</strong> üretilmiş, bu tahminlerde dolar endeksinin geçmiş hareketleri ve Brent fiyatlarının log fark serisi üzerinden oluşturulan özellikleri kullanılmıştır. Her bir ay için tahmin edilen log-diff değerleri, önceki tahminlerin üzerine eklenerek bir sonraki ayın girdisi haline getirilmiştir. Böylece gelecekteki fiyat davranışları <strong>tahmini verilerden beslenen zincirleme bir yapı</strong> ile üretilmiştir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3jFwtHv3piWLFEm3P5u1A.png" /><figcaption>1987&#39;den günümüze kadar olan brent petrol fiyatları ve XGBoost ile gelecek 2 yıl için yapılan tahminler.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIVZK-ltP1JQfy6Tb6s1MQ.png" /><figcaption>XGBoost modeli ile gelecek 2 yıl için yapılan fiyat tahminleri</figcaption></figure><p>Elde edilen sonuçlar, XGBoost modelinin veri ön işleme ve özellik mühendisliği adımlarıyla birlikte kullanıldığında anlamlı öngörüler sağlayabildiğini göstermiştir. Model, özellikle geçmiş fiyat hareketlerindeki desenleri yakalama konusunda güçlü bir performans sergiliyor.</p><p>Tahmin edilen fiyatlar, log fark değerlerinden ters dönüşüm uygulanarak orijinal fiyat seviyesine çevrilmiş, böylece tahminler Brent petrolün gerçek fiyat düzeyinde görselleştirilmiştir.</p><h4><strong>Tartışma : Tahminlerin Güvenilirliği ve Modelin Geliştirilmesi</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbgr4tzwHzkRVhwONC6gDg.jpeg" /><figcaption>Geleceği doğru tahmin edilebilir mi?</figcaption></figure><p>XGBoost modeli geçmiş veri davranışlarını yüksek doğrulukla öğrenebilse de <strong>gelecek fiyatları %100 doğrulukla tahmin etmesi mümkün değildir</strong>. Bunun başlıca nedenleri:</p><ul><li>Jeopolitik gelişmelerin, arz-talep şoklarının veya doğal afetlerin modele önceden tanımlanamaz olması,</li><li>Modelin yalnızca geçmiş fiyat ve dolar endeksi verileriyle sınırlı kalması (beklenmeyen yeni durumları öngörme kabiliyeti kısıtlı),</li><li>Ani piyasa kırılmalarının geçmiş istatistiksel davranışlara dayanarak tahmin edilememesi.</li></ul><blockquote><em>Model, tarihsel veri temelli öngörüler üretmektedir. Bu nedenle sonuçlar </em><strong><em>olasılıksal bir tahmin</em></strong><em> niteliği taşır. Tahminler özellikle </em><strong><em>istikrarlı dönemlerde</em></strong><em> daha isabetli olurken, </em><strong><em>ani dış şoklarda</em></strong><em> sapma payı artabilir. Örneğin beklenmedik bir Rusya’nın Ukrayna’yı işgali benzeri jeopolitik kriz, fiyatların model öngörülerinden tamamen sapmasına neden olabilir.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*i8eqLEZS7HJlpdnW6sdn4A.png" /></figure><p>Modelin doğruluğunu artırmak için aşağıdaki yöntemler ilerleyen çalışmalarda uygulanabilir:</p><ul><li>Jeopolitik risk endeksleri, stok seviyeleri, arz-talep dengeleri gibi yeni makroekonomik değişkenlerin eklenmesi,</li><li>LSTM ve XGBoost gibi modellerin birleştirildiği <strong>hibrit modelleme yaklaşımları</strong>,</li><li>Olasılık dağılımı üreten Bayesyen modeller veya senaryo tabanlı tahmin yöntemleri.</li></ul><h4><strong>Sonuç</strong></h4><p>Bu çalışma, Brent petrol fiyatlarının tahmininde makine öğrenmesi tekniklerinin nasıl yapılandırılabileceğine dair pratik bir örnek sunuyor. Özellikle XGBoost modeli, veri ön işleme, logaritmik dönüşüm, fark alma ve özellik mühendisliği adımlarıyla birlikte kullanıldığında, geleceğe yönelik anlamlı tahminler üretebiliyor.</p><p>Ancak sonuçlar, modelin yalnızca geçmiş verilerden beslendiği ve beklenmedik şokları içermediği dikkate alınarak değerlendirilmelidir. petrol piyasalarındaki yüksek belirsizlik (jeopolitik riskler, arz şokları, finansal krizler gibi) nedeniyle modelin tahminleri kesinlik taşımaz; yalnızca <strong>olasılıksal bir öngörü</strong> niteliğindedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*KfUS1ZV6QT8dtXnga9kClQ.jpeg" /><figcaption>Geçmiş veriler geleceğe ayna tutar mı?</figcaption></figure><p>Enerji fiyatlarının stratejik önemi göz önünde bulundurulduğunda, bu tür modeller karar vericiler, yatırımcılar ve politika yapıcılar için kıymetli bir yol gösterici olabilir; ancak nihai karar süreçlerinde tek başına bir belirleyici olarak değil, <strong>destekleyici</strong> olarak kullanılmalıdır.</p><h4>Kaynaklar &amp; Linkler</h4><ul><li>Federal Reserve Economic Data (<strong>FRED</strong>) — <strong>EIA</strong> Brent Petrol Fiyatları (1987–günümüz)</li><li>U.S. Federal Reserve (<strong>FED</strong>) — Dolar Endeksi</li></ul><p><em>👉</em><a href="https://github.com/nrdnay/Brent_Oil_Price_Prediction"><strong>GitHub (Coding)</strong></a></p><p><em>👉</em> <a href="https://medium.com/@aydogdunurdan/forecasting-amid-uncertainty-a-machine-learning-approach-to-predicting-brent-crude-oil-prices-0ac2a7b64151"><strong>Medium — English Article (İngilizce Versiyon)</strong></a></p><p><strong>Modelleme Yöntemi:</strong></p><p>Özellik Mühendisliği + log-diff Dönüşümü + XGBoost Regressor + İteratif 24 aylık tahmin zinciri.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*KAggSJDrOolX-Ru-sADUzw.gif" /><figcaption>You’re absolutely right.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0db8768f9847" width="1" height="1" alt=""><hr><p><a href="https://medium.com/t%C3%BCrkiye/belirsizlik-i%CC%87%C3%A7indetahmin-makine-%C3%B6%C4%9Frenmesi-ile-brent-petrol-fiyatlar%C4%B1na-%C3%B6ng%C3%B6r%C3%BCc%C3%BC-bir-yakla%C5%9F%C4%B1m-0db8768f9847">Belirsizlik Ortamında Tahmin: Makine Öğrenmesi ile Brent Petrol Fiyat Öngörüsü</a> was originally published in <a href="https://medium.com/t%C3%BCrkiye">Türkçe Yayın</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overfitting Problem in Deep Learning Models and Prevention Techniques]]></title>
            <link>https://medium.com/curie-co/overfitting-problem-in-deep-learning-models-and-prevention-techniques-afd82a86ab48?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd82a86ab48</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 10:29:35 GMT</pubDate>
            <atom:updated>2025-12-06T08:13:48.533Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Deep Learning and Overfitting</strong></h4><blockquote>In an era where we are almost overwhelmed by data, <strong>deep learning models</strong> have become one of the most powerful prediction tools today, thanks to their ability to learn the most complex patterns in large datasets.<br> However, it’s important to remember that one of their biggest weaknesses is the issue of <strong>overfitting</strong>.</blockquote><p>🔗 <a href="https://medium.com/t%C3%BCrkiye/derin-%C3%B6%C4%9Frenme-modellerinde-a%C5%9F%C4%B1r%C4%B1-%C3%B6%C4%9Frenme-sorunu-ve-%C3%B6nleme-y%C3%B6ntemleri-f23bda912eb7"><strong>Türkçe için</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ApaYMOiuPnwu1CuglhnLMw.png" /><figcaption>Here it is! Overfitting begins right at the point where the colorful curve starts to rise.</figcaption></figure><p>In this article, we will discuss what overfitting is, why it occurs in deep learning (artificial neural networks) models, how it can be identified and prevented, and which parameters should be carefully considered during modeling — presented in a clear, itemized format.</p><h4><strong>What Is Overfitting?</strong></h4><p><strong>Overfitting</strong> occurs when a model, instead of learning the underlying patterns in the data during training, memorizes the data — including noise and randomness — by fitting too closely to it. As a result, the model performs poorly on new, unseen data.</p><p>In other words, overfitting weakens a model’s ability to generalize, which is a critical requirement for robust predictions.</p><p>An Example of an Optimal vs. Overfitted Model in a Classification Problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*8an1rXHvV2EzO-7k6MHRDg.png" /><figcaption>An example of an optimal and overfitting model from a classification problem.</figcaption></figure><h4><strong>How to Detect Overfitting?</strong></h4><p>Overfitting is typically identified by comparing the model’s performance on the training and validation datasets. Some of the common indicators include:</p><ol><li>A significant and widening gap between the accuracy on the training set and the accuracy on the validation set.</li><li>While training progresses, the validation loss initially decreases in parallel with the training loss, but at some point, it starts to increase. This turning point is generally considered the beginning of overfitting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jDpYOGlvdocUlpMe7D00NQ.png" /></figure><h4><strong>What Causes Overfitting?</strong></h4><p>We will discuss the parameters that can lead to overfitting when misconfigured under the section <strong>“How to Prevent Overfitting?”</strong>, in itemized form.</p><p>However, the most common causes of overfitting in deep learning models include:</p><ul><li>Insufficient training data</li><li>An overly complex model (with too many parameters)</li><li>Prolonged training duration</li><li>High learning rate</li><li>Lack of control mechanisms such as regularization</li></ul><h4><strong>How Can Overfitting Be Prevented?</strong></h4><p>The importance of techniques and parameters used to prevent overfitting may vary depending on the dataset, model, model architecture, and other factors. That said, the most effective methods and parameters can be listed as follows.</p><p>Let’s start with the good news:<br> Even applying just one or two of the techniques listed below correctly can lead to notable improvements in reducing overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*0BjefcwCitFcXjrrrep7WA.gif" /></figure><p><strong>1.Dataset Size and Quality:</strong><br>Deep learning models generally perform better with large and high-quality datasets. Small or noisy datasets increase the risk of overfitting. Techniques such as data augmentation, data cleaning, and preprocessing can be used to improve the size and quality of the dataset.</p><p><strong>2.Regularization (L1/L2) Method:</strong><br>With L1 and L2 regularization techniques, penalties are applied to the model by imposing constraints on the weights, thereby reducing model complexity. Regularization parameters determine the strength of these constraints.</p><pre>from tensorflow.keras import regularizers<br><br>model.add(Dense(64, kernel_regularizer=regularizers.l2(0.01), activation=&#39;relu&#39;))</pre><p><strong>3.Dropout Rate:</strong><br>Dropout is a technique used during training where some neurons (inputs) are randomly deactivated. This prevents the model from becoming overly dependent on specific features. The chosen dropout rate determines the percentage of neurons to be deactivated.</p><pre>from tensorflow.keras.layers import Dropout<br><br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*3hbkxN1TXhxf-HqHjBrIlg.png" /><figcaption>Dropout After and Before</figcaption></figure><p><strong>4.Model Architecture:</strong><br>The architecture and complexity of the model are related to the number of parameters and the structural design of the model. Highly complex models are more prone to overfitting. Model complexity can be reduced by selecting a simpler architecture that fits the dataset or by applying techniques such as regularization and dropout.</p><p><strong>5.Learning Rate:</strong><br>The learning rate determines how quickly the model updates its weights during training. A learning rate that is too high may cause the model to miss the optimal solution and lead to overfitting, while a learning rate that is too low can slow down training. Trial and error methods or learning rate schedulers can be used to find an appropriate learning rate.</p><p><strong>6.Early Stopping:</strong><br>Early stopping prevents overfitting by halting the training process when the validation loss begins to increase (i.e., when performance on the validation set starts to degrade).</p><pre>from tensorflow.keras.callbacks import EarlyStopping<br><br>early_stop = EarlyStopping(monitor=&#39;val_loss&#39;, patience=3)<br>model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=50, callbacks=[early_stop])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*-__pAqaJWahPYVlNAK63xQ.png" /></figure><p><strong>7.</strong> <strong>Number of Epochs:</strong><br>The number of epochs determines how many times the model will be trained over the entire training dataset. Too many epochs can cause the model to overfit the training data. Techniques such as early stopping can be used to determine the optimal number of epochs.</p><p><strong>8.</strong> <strong>Batch Size:</strong><br>Batch size refers to the number of data samples provided to the model in each training step. A batch size that is too small can make training unstable and lead to overfitting, while a very large batch size may increase memory usage. A suitable batch size can be determined through trial and error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6uBgDa8-c7graaAfFB1DQ.jpeg" /><figcaption>Feature Engineering; Feature (input) Selection</figcaption></figure><p><strong>9.</strong> <strong>Activation Functions:</strong><br>Activation functions influence the model’s learning capacity and tendency to overfit. Common activation functions include ReLU, sigmoid, and tanh. It is important to choose activation functions that best suit the dataset and model architecture.</p><p><strong>10.</strong> <strong>Optimization Algorithm:</strong><br>The optimization algorithm defines how the model’s weights are updated during training. There are various options such as Adam, SGD, and RMSprop. Selecting the most appropriate optimization algorithm for your dataset and model architecture is essential.</p><p><strong>11.</strong> <strong>Initialization Method:</strong><br>The initial values of the model’s weights can affect the training process and model performance. Methods like Xavier and He initialization are commonly used. Choosing the right initialization technique helps the model learn faster and more effectively.</p><p><strong>12.</strong> <strong>Data Preprocessing Steps:</strong><br>These include cleaning, transforming, and scaling the data before training. Applying appropriate preprocessing steps to the dataset can significantly influence model performance and its tendency to overfit.</p><p>Feature Engineering; Feature (input) Selection</p><p><strong>13.</strong> <strong>Feature Engineering — Feature Selection and Extraction:</strong><br>A large number of irrelevant or unnecessary features can increase the complexity of the model and lead to overfitting. Therefore, selecting important features (<strong>feature selection</strong>) or creating new ones (<strong>feature extraction</strong>) can improve the model’s ability to generalize.</p><p><strong>14.</strong> <strong>Cross-Validation:</strong><br>Cross-validation evaluates the model’s performance on different subsets of the data, providing more reliable predictions. It is especially useful when working with small datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*qxDd0V_NGpR0usmYHnqZMQ.gif" /></figure><p><strong>15.</strong> <strong>Ensemble Methods:</strong><br>Ensemble methods combine predictions from multiple models to create a more robust model with better generalization. These techniques can help reduce overfitting.</p><p><strong>16.</strong> <strong>Data Distribution:</strong><br>If the distribution of the training and test data differs significantly, the model may overfit. Analyzing the data distribution and applying techniques such as data augmentation or resampling can help resolve this issue.</p><p><strong>17.</strong> <strong>Characteristics of the Target Variable:</strong><br>The properties of the target variable (e.g., number of classes, value range) can influence model selection and the risk of overfitting. It is essential to choose a model architecture and training strategy appropriate to the target variable’s characteristics.</p><p><strong>18.</strong> <strong>Hardware and Software Constraints:</strong><br>Factors such as memory, processing power, and available software libraries can affect model selection and the risk of overfitting. These limitations must be carefully considered.</p><p><strong>19.</strong> <strong>Weight Initialization:</strong><br>The initial values of the model’s weights can influence the training process and final performance. Trying different weight initialization methods can help the model learn faster and more effectively.</p><p><strong>20.Layer Normalization and Batch Normalization:</strong><br>These techniques improve training stability and performance by reducing overfitting and helping the model converge more effectively.</p><p><strong>21.Transfer Learning:</strong><br>Training a new model by leveraging the pre-trained weights of an existing model can help prevent overfitting, especially when the available dataset is small.</p><h4><strong>Conclusion:</strong></h4><p>Overfitting is a common issue in deep learning models, but it can be prevented with the right techniques and strategies.</p><p>Methods such as data augmentation, regularization, dropout, early stopping, using simpler models, and tuning hyperparameters like learning rate, number of epochs, and batch size are among the primary techniques used to reduce overfitting.</p><p>Upon closer inspection, most of these methods and parameters aim either to simplify the model or to increase the dataset size and improve learning processes.</p><p>And most importantly, the significance of each parameter can vary depending on the dataset and model architecture.<br> Therefore, the best results can only be achieved by experimenting with different combinations of parameters and carefully evaluating model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*TDJX56KiE47Fp_KQMaCXKw.gif" /><figcaption>Unfiltered information is not information.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd82a86ab48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/curie-co/overfitting-problem-in-deep-learning-models-and-prevention-techniques-afd82a86ab48">Overfitting Problem in Deep Learning Models and Prevention Techniques</a> was originally published in <a href="https://medium.com/curie-co">Curie &amp; Co.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API in 10 Points]]></title>
            <link>https://medium.com/@aydogdunurdan/api-in-10-points-4b473d6463b8?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b473d6463b8</guid>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data-extraction-api]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 20:15:27 GMT</pubDate>
            <atom:updated>2025-09-03T10:39:44.987Z</atom:updated>
            <content:encoded><![CDATA[<p>What is an API? What is it used for? Where is it used? How is it used? Are all APIs used the same way? Does every web page have its own API? What’s the difference between it and web scraping?</p><p><a href="https://medium.com/@aydogdunurdan/10-maddede-api-719bc4784706"><strong>Türkçe için</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*rV5ISA8oLEJMBLF7CVeAuA.png" /></figure><p>This article aims to provide a simple overview of APIs and explain them in a way that everyone can understand.</p><p>To further clarify and illustrate the topic, <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb">an API application example for the EIA page is cited.</a> In this application example, data is extracted from the EIA (the US Department of Energy’s data service) website using Python, visualized, analyzed, and a predictive model is created. For the full code:</p><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/tree/main">GitHub - nrdnay/eia-Petroleum-Products-Consumption-Production: This project examined Global Production and Consumption Quantities of Refined Petroleum Products using EIA data. The data was visualized, yielding meaningful results. Deep learning and machine learning predict models were developed to predict US future consumption. For Turkish Article : https://medium.com/@aydogdunurdan</a></p><h4>🔍 1. What is an API? What is it used for?</h4><p>API stands for Application Programming Interface. It can be defined as the connection interface used by an application to access data, server software, or other programs. In other words, API is a bridge that allows one software to communicate with another software, and this communication is established in a standard way within the framework of certain definitions and protocols.</p><p><strong>📌 What is it used for?</strong></p><p>🖊 Retrieving data without visiting websites</p><p>🖊 Accessing data faster and more systematically</p><p>🖊 Automating analysis</p><p>🖊 Creating applications or visualization dashboards</p><p>An API essentially allows users to automate manual tasks.</p><p><strong>The most common API uses are:</strong></p><ul><li>In social media applications, when login permission is granted</li><li>When retrieving personal data from Facebook servers</li><li>When contacting banks for e-commerce payments</li><li>In weather applications</li><li>To track real-time stock market data</li><li>To distribute software updates in applications</li><li>To provide location data</li></ul><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Application Example:</strong></a> Instead of going to the EIA website each time to communicate with EIA and downloading data as CSV, requests are sent directly with Python, accessing EIA servers through the API, and the data is retrieved as a DataFrame.</p><h4>🔍 2. What Can Be Done Differently with the API?</h4><p>Here’s a summary of what we can do differently with the API than without it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ja8BuEsoyRBvkbLDks0Lag.png" /></figure><p><strong>🔹 </strong><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Application Example:</strong></a></p><p>Using the EIA website’s API, data for the requested Series ID was requested, the received data was cleaned, and visualized.</p><h4>🔍 3. Does Every Website Have Its Own API?</h4><p>Not every website has an API. However, many data services, applications, or government agencies do.</p><p>📌 Common institutions/domains with APIs:</p><p>🖊 Government institutions (EIA, NASA, TUIK)</p><p>🖊 Social media (Twitter, Reddit, YouTube)</p><p>🖊 Weather services</p><p>🖊 Finance (Stock Exchange APIs, CoinMarketCap)</p><p>💡 To see if an API is available: Simply type “[site name] API documentation” (e.g., “EIA API documentation”) into Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Q1NzZm8phifsAvcKU84c5A.png" /></figure><h4>🔍 4. What is an API Key? How to Obtain It? How to Use It?</h4><p>An API Key is a password that identifies a user. It is provided to developers to protect the API from misuse.</p><p>🔐 <strong>Where is it used? </strong>It is typically used in headers or params when making data requests.<br>🔍<strong> How to Obtain It? </strong>How to obtain an API key varies for each API.</p><p>🔹 <strong>According to the </strong><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Application Example:</strong></a></p><p>You visit <a href="https://www.eia.gov/opendata/">https://www.eia.gov/opendata/</a> and register,<br>You request an API key for access,<br>And the system issues an API key.<br>📌 <strong>Coding Usage:</strong></p><pre>API_KEY = &quot;Vd3wFJayLszsK4K8dH9tvYfpWPKSbk30UnxWWCna&quot;<br>headers = {&quot;X-API-KEY&quot;: API_KEY}<br>response = requests.get(url, headers=headers)</pre><h4>🔍 5. Are There APIs Accessible Without an API Key?</h4><p>Yes, some APIs are password-free and open-access. These APIs do not require authentication. Typically:</p><p>🖊 They offer training, sample applications, or publicly available data.</p><p>🖊 They have a low data rate limit.</p><p>🔓 <strong>Examples of Password-Free APIs:</strong></p><p><strong>Open-Meteo: </strong>Weather API (no API key required)</p><p><strong>Rest Countries:</strong> Country information (population, flag, language, etc.)</p><p><strong>CoinGecko:</strong> Cryptocurrency prices (no API key required)</p><p><strong>Public-APIs: </strong>List of open APIs</p><p>💡 However, most major APIs (Google, Twitter, EIA, NASA) require API keys to monitor and control access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*QFsVB9GFcjiM4aR-pTS8RA.gif" /></figure><h4>🔍 6. Does API Usage Differ for Each Site? How to Learn How to Use the API?</h4><p>Each API has different rules. Most REST APIs follow this structure:</p><p>BASE_URL + /endpoint + ?param1=…&amp;param2=…</p><p>📘 The API documentation is always the primary source. Just like a device’s user manual, every API has its own official documentation, a user guide.</p><p>📌<strong> The API documentation includes:</strong></p><p>🖊 What endpoints are there?</p><p>🖊 How are parameters written?</p><p>🖊 Where is the API key placed?</p><p>🖊 What is the response structure?</p><p>🔹 <strong>E</strong><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>IA API Implementation Example:</strong></a><br>The EIA API documentation describes several ways to query data:</p><ul><li>Retrieving data using series_id</li><li>Retrieving data by filtering with the data endpoint</li><li>Querying groups using category_id</li></ul><p>Querying using series_id was preferred because it is the most direct and simple method. The EIA document (<a href="https://www.eia.gov/opendata/documentation.php">https://www.eia.gov/opendata/documentation.php</a>) explicitly states:</p><p>“You can request a specific series using <a href="https://api.eia.gov/v2/seriesid/%7Bseries_id">https://api.eia.gov/v2/seriesid/{series_id</a>}”</p><p>In other words, the series_id endpoint is used to retrieve a specific time series data from the EIA. The documentation demonstrates how this endpoint works, along with a sample URL.</p><p>🔑 In short, the document specifies what is required (such as series_id) and provides examples of the URL structure. The correct series_id values ​​were identified using <a href="https://www.eia.gov/opendata/browser/">https://www.eia.gov/opendata/browser/</a>.</p><p>🔹 To summarize the flow in the EIA API Implementation Example:</p><ol><li>API key defined</li></ol><pre>headers = {&quot;X-API-KEY&quot;: API_KEY}</pre><p><strong>2. After learning the Series ID from the EIA page</strong></p><pre>series = {<br>&quot;Tüketim&quot;: &quot;INTL.54–2-RUS-TBPD.A&quot;,<br>&quot;Üretim&quot;: &quot;INTL.54–1-RUS-TBPD.A&quot;<br>}</pre><p><strong>3. The URL is prepared correctly</strong></p><pre>url = f&quot;https://api.eia.gov/v2/seriesid/{series_id}&quot;</pre><p><strong>4. Data was requested with requests and the JSON response was read</strong></p><pre>response = requests.get(url, headers=headers)</pre><p><strong>5. Data was converted to DataFrame and analyzed with pandas</strong></p><p>df = pd.DataFrame(data[“response”][“data”])</p><h4>🔍 7. What is an Endpoint?</h4><p>An endpoint is a special URL extension that provides access to one of the data services offered by an API. It is the path segment following the base address and determines which dataset the API will access.</p><p>📌 <strong>Base URL (usually fixed):</strong><br><a href="https://api.eia.gov/v2/">https://api.eia.gov/v2/</a> ← This is the base address of the EIA API.</p><p>🔹 <strong>Explained with an EIA API Application Example:</strong></p><p>🔸 <strong>1. Series ID endpoint</strong></p><pre>url = f&quot;https://api.eia.gov/v2/seriesid/{series_id}&quot;</pre><ul><li>This provides direct access to a predefined data series.</li><li>Example series_id: “INTL.54–2-IRN-TBPD.A” → Iran’s oil consumption.</li><li>When this endpoint is used, a single time series is extracted as is.</li></ul><p>🔸 <strong>2. Data endpoint (For example: oil price dataset)</strong></p><pre>url = &quot;https://api.eia.gov/v2/petroleum/pri/spt/data/&quot;</pre><p>🖊 This endpoint is a large dataset containing all EIA oil price data.</p><p>🖊 This type of endpoint requires specifying details with params:</p><ul><li>Which series?</li><li>Which date range?</li><li>Which frequency? (monthly, yearly, etc.)</li><li>Which columns? (data[0]=value)</li></ul><p>📌 <strong>Comparative Summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KASRjsmvr_WmllRj1iYcPA.png" /></figure><p>🔑 To explain it with an analogy: <strong>API = Menu, Endpoint = Meal on the Menu</strong></p><ul><li>To order “Chicken,” you need to know the correct meal (endpoint)</li><li>To order “Spicy Chicken,” you need to add a parameter.</li></ul><h4>🔍 8. Is the request.get() Module Always Used to Retrieve Data from an API?</h4><p>In Python, the requests module is a common standard for communicating with APIs. Its most basic usage is as follows:</p><pre>response = requests.get(<br>url=&quot;https://api.example.com/endpoint&quot;,<br>headers={&quot;X-API-KEY&quot;: &quot;senin_keyin&quot;},<br>params={&quot;param1&quot;: &quot;deger1&quot;, &quot;param2&quot;: &quot;deger2&quot;} # opsiyonel<br>)</pre><p>📌 <strong>requests.get() function:</strong></p><p>🖊 Sends a GET request to the URL.</p><p>🖊 headers: for authentication, content type, etc.</p><p>🖊 params: for parameters to be added to the URL.</p><p>📌 T<strong>here are also alternative methods:</strong></p><p><strong>requests.post()</strong> → to send data<br><strong>requests.put()</strong> → to update<br><strong>requests.delete()</strong> → to delete</p><h4>🔍 9. What is params? What does it do?</h4><p><strong>params </strong>→ allows query parameters to be added to the URL. It is used to send specific filtering or selection criteria to an API endpoint.</p><p>📌 <strong>General Syntax:</strong></p><pre>response = requests.get(<br>url=&quot;https://api.example.com/data&quot;,<br>params={&quot;year&quot;: &quot;2023&quot;, &quot;country&quot;: &quot;USA&quot;, &quot;sort&quot;: &quot;desc&quot;}<br>)</pre><p>The URL this code calls is:</p><p><a href="https://api.example.com/data?year=2023&amp;country=USA&amp;sort=desc">https://api.example.com/data?year=2023&amp;country=USA&amp;sort=desc</a></p><p>So, params, after the ?, forms the dynamic part of the URL.</p><p>🎯 <strong>What is it used for?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUld6az0r-m1dweMs4X6_w.png" /></figure><p>🔹 <strong>Using params in the EIA API Application Example</strong></p><p>In the EIA API, filtering can be done using params at some endpoints. In the code example below, we see that;</p><ul><li>A specific time range (start, end)</li><li>Specific series (facets)</li><li>A specific order (sort) is requested.</li></ul><pre>url = &quot;https://api.eia.gov/v2/petroleum/pri/spt/data/&quot;<br>params = {<br>&quot;frequency&quot;: &quot;monthly&quot;,<br>&quot;data[0]&quot;: &quot;value&quot;,<br>&quot;start&quot;: &quot;2020–01&quot;,<br>&quot;end&quot;: &quot;2023–01&quot;,<br>&quot;facets[series]&quot;: [&quot;PET.RWTC.D&quot;],<br>&quot;sort[0][column]&quot;: &quot;period&quot;,<br>&quot;sort[0][direction]&quot;: &quot;desc&quot;<br>}<br>response = requests.get(url, headers=headers, params=params)</pre><p>✅ Summary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YINXSHCLYJd4nvE51GH30w.png" /></figure><h4>🔍 10. What are the Differences Between API Applications and Web Scraping? What are their Purposes?</h4><p>API data extraction and Web Scraping are different methods. Let’s compare them:</p><p><strong>📊 1. DEFINITIONS</strong></p><p>✅ <strong>API (Application Programming Interface)</strong></p><p>🖊 A way for websites to present data in a formal and structured manner.</p><p>🖊 Data is typically returned via a URL in formats such as JSON and XML.</p><p>🖊 Authorization (API key) may be required.</p><p><strong>Example: </strong>Retrieving annual oil consumption data with the EIA API.</p><p>✅ <strong>Web Scraping</strong></p><p>🖊 This is the process of scraping the HTML content of web pages and extracting data from them.</p><p>🖊 The page is visually appealing (e.g., data is extracted from HTML elements such as &lt;table&gt;, &lt;div&gt;, &lt;span&gt;).</p><p>If the page design changes, the code must also change.</p><p><strong>Example:</strong> Seeing the table on the EIA page with your eyes and then trying to extract it with Python.</p><p><strong>2. Differences — Comparative Table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtgnLyrQnVcTZOxMZ2pxRg.png" /></figure><p>📊<strong> 3. When and Which?</strong></p><p><strong>When to Use an API?</strong></p><p>🖊 If the website offers an API: API is always preferred first.</p><p>🖊 If the data is clean, structured, and up-to-date.</p><p><strong>Example: </strong>Weather data, exchange rates, energy statistics.</p><p><strong>When to Use Web Scraping?</strong></p><p>🖊 If the website doesn’t have an API.</p><p>🖊 If you need to access visual data (product names, prices).</p><p><strong>Example:</strong> Car sales websites, news headlines, forum comments.</p><p><strong>🔹 Practical Example:</strong></p><p>🧪 <strong>With an API:</strong></p><pre>import requests<br>url = &quot;https://api.eia.gov/v2/petroleum/sum/snd/data/&quot;<br>params = {&quot;frequency&quot;: &quot;annual&quot;, &quot;facets[series]&quot;: [&quot;MLUUPUS1&quot;]}<br>headers = {&quot;X-API-KEY&quot;: &quot;YOUR_API_KEY&quot;}<br>r = requests.get(url, headers=headers, params=params)<br>data = r.json()</pre><p><strong>🧪 With Web Scraping:</strong></p><pre>import requests<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://example.com/lubricants-data&quot;<br>r = requests.get(url)<br>soup = BeautifulSoup(r.text, &quot;html.parser&quot;)<br>rows = soup.find_all(&quot;tr&quot;)</pre><p>✅ <strong>CONCLUSION:</strong></p><p>🚩If available: Use the API.<br>🚩If not available: Scraping may be an option.<br>🚩 However, web scraping can be sensitive, fragile, and carry legal risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*aHd0H9VJHyet8Wio18QPJQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b473d6463b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Maddede API]]></title>
            <link>https://medium.com/t%C3%BCrkiye/10-maddede-api-719bc4784706?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/719bc4784706</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[veri-madenciliği]]></category>
            <category><![CDATA[veriçekme]]></category>
            <category><![CDATA[api-nedir]]></category>
            <category><![CDATA[api-uygulama]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 15:47:28 GMT</pubDate>
            <atom:updated>2025-09-21T20:46:17.919Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>API Nedir? Ne İçin Kullanılır? Nerelerde Kullanılır? Nasıl Kullanılır? Her API Aynı Şekilde mi Kullanılır? Her Web Sayfasının Kendi API’si Var Mıdır? Web Scrapping’le Farkı Nedir?</strong></h4><p><a href="https://medium.com/@aydogdunurdan/api-in-10-points-4b473d6463b8"><strong>For English</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*rV5ISA8oLEJMBLF7CVeAuA.png" /></figure><p>Bu makalede API konusunun basit bir şekilde ele alınıp, herkesin anlayabileceği şekilde anlatılması hedeflenmiştir.</p><p>Konuyu daha anlaşılır kılmak ve örneklendirmek için <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production">EIA sayfasına yönelik API uygulama örneğine</a> atıf yapılmıştır. Bu uygulama örneğinde, EIA’nın (ABD Enerji Bakanlığı’nın veri servisi) web sayfasından Python kullanılarak, veriler çekilmiş ve görselleştirilip analiz edilerek, tahmin modeli oluşturulmuştur. Kodlamanın tamamı için :</p><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production">GitHub - nrdnay/eia-Petroleum-Products-Consumption-Production: This project examined Global Production and Consumption Quantities of Refined Petroleum Products using EIA data. The data was visualized, yielding meaningful results. Deep learning and machine learning predict models were developed to predict US future consumption. For Turkish Article : https://medium.com/@aydogdunurdan</a></p><h4>🔍<strong> 1. API Nedir? Ne İçin Kullanılır?</strong></h4><p>API’nin açılımı Application Programming Interface, Türkçesi ise Uygulama Programlama Arayüzeyi’dir.</p><p>Bir uygulamanın verilere, sunucu yazılımına veya diğer programlara ulaşabilmek için kullandığı bağlantı arayüzüdür denilebilir. Diğer bir deyişle API, bir yazılımın başka bir yazılımla iletişim kurmasına olanak tanıyan bir köprüdür ve bu iletişim belirli tanımlar ve protokoller çerçevesinde standart bir şekilde kurulur.</p><p>📌 <strong>Ne için kullanılır?</strong></p><p>🖊 Web sitelerine gitmeden, veri çekmek</p><p>🖊 Veriye daha hızlı ve sistematik erişmek</p><p>🖊 Analizleri otomatikleştirmek</p><p>🖊 Uygulamalar veya görselleştirme panoları yapmak</p><p>API temel olarak, kullanıcının manuel olarak yaptığı işleri otomatikleştirmeyi sağlar.</p><p><strong>API’nin en yaygın kullanıldığı alanlar:</strong></p><ul><li>Oturum açma izni verildiğinde, sosyal medya uygulamalarında</li><li>Facebook sunucularından kişisel veriler çekilirken</li><li>E-ticaret ödemelerinde banka ile iletişime geçildiğinde</li><li>Hava durumu uygulamalarında</li><li>Anlık borsa verilerinin takibinde</li><li>Uygulamalardaki yazılım güncellemelerinin dağıtılmasında</li><li>Konum verilerinin sağlanmasında</li></ul><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Uygulama Örneğinde:</strong></a> EIA ile iletişim için her seferinde EIA sitesine gidip verileri CSV olarak indirmek yerine, Python ile direkt requests yollanıp API vasıtasıyla EIA’nın sunucularına ulaşılmış ve veriler DataFrame olarak çekilmiştir.</p><h4>🔍<strong> 2. API ile Farklı Olarak Neler Yapılabilir?</strong></h4><p>API ile, API olmadan yaptığımız işlemlerden farklı olarak neleri yapabileceğimizin özet tablosu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*7iAXHJ5-A5IFZWhXyotAgA.png" /></figure><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Uygulama Örneğinde:</strong></a></p><p>EIA’ya ait web sayfasının API’si kullanılarak, talep edilen Series ID’ye ait veriler istenmiş, alınan veriler temizlenmiş ve görselleştirilmiştir.</p><h4>🔍<strong> 3. Her Web Sitesinin Kendi API’si Var Mıdır?</strong></h4><p>H<strong>er web sitesinin API’si yoktur.</strong> Ancak birçok veri servisinin, uygulamanın ya da devlet kurumunun API’si vardır.</p><p>📌 Yaygın olarak API’si olan kurumlar / alanlar:</p><p>🖊 Devlet kurumları (EIA, NASA, TUIK, TÜBA)</p><p>🖊 Sosyal medya (Twitter, Reddit, YouTube)</p><p>🖊 Hava durumu servisleri</p><p>🖊 Finans (Borsa API’leri, CoinMarketCap)</p><p>💡 <strong>API’si olup olmadığını anlamak için</strong>: Google’a “[site adı] API documentation” (“EIA API documentation” gibi) yazmak yeterlidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Q1NzZm8phifsAvcKU84c5A.png" /></figure><h4>🔍<strong> 4. API Key Nedir? Nasıl Alınır? Nasıl Kullanılır?</strong></h4><p><strong>API Key</strong>, kullanıcıyı tanımlayan bir şifredir. API’yi kötüye kullanımlardan korumak için, geliştiricilere verilir.</p><p>🔐 <strong>Nerede kullanılır?</strong></p><ul><li>Veri isteği yaparken, genelde headers ya da params içine yazılırak kullanılır.</li></ul><p>🔍 <strong>Nasıl Alınır?</strong></p><p>API key’in nasıl alınacağı her API için farklılık gösterir.</p><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Uygulama Örneğine göre:</strong></a></p><ol><li><a href="https://www.eia.gov/opendata/">https://www.eia.gov/opendata/</a> adresine girilip kayıt olunmuş,</li><li>Erişim için API key talep edilmiş,</li><li>Ve sistem tarafından API Key verilmiştir.</li></ol><p>📌 <strong>Kodlamadaki Kullanımı:</strong></p><pre>API_KEY = &quot;Vd3wFJayLszsK4K8dH9tvYfpWPKSbk30UnxWWCna&quot;<br>headers = {&quot;X-API-KEY&quot;: API_KEY}<br>response = requests.get(url, headers=headers)</pre><h4>🔍<strong> 5. API Key Gerekmeden Erişilen API’ler Var mıdır?</strong></h4><p><strong>Evet, bazı API’ler şifresiz ve açık erişimlidir. </strong>Bu API’lerde kimlik doğrulaması (authentication) gerekmez. Genellikle:</p><p>🖊 Eğitim, örnek uygulama, ya da kamuya açık veriler sunulur,</p><p>🖊 Veri sınırı (rate limit) düşüktür.</p><p><strong>🔓 Şifresiz API Örnekleri:</strong></p><p><a href="https://open-meteo.com/"><strong>Open-Meteo</strong></a><strong> : </strong>Hava durumu API’si (API key gerekmez)</p><p><a href="https://restcountries.com/"><strong>Rest Countries</strong></a><strong> :</strong> Ülke bilgileri (nüfus, bayrak, dil…)</p><p><a href="https://restcountries.com/"><strong>CoinGecko</strong></a><strong> : </strong>Kripto fiyatları (API key gerekmez)</p><p><a href="https://github.com/public-apis/public-apis"><strong>Public-APIs</strong></a><strong> :</strong> Açık API’lerin listesi</p><p>💡 <strong>Ancak</strong> çoğu büyük API (Google, Twitter, EIA, NASA), erişimi izlemek ve kontrol etmek için API key ister.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*QFsVB9GFcjiM4aR-pTS8RA.gif" /></figure><h4>🔍<strong> 6. API Kullanımı </strong>Her Site için <strong>Farklı mıdır? API’nin Nasıl Kullanılacağı Nasıl Öğrenilir?</strong></h4><p>H<strong>er API’nin kuralları farklıdır</strong>. Çoğu REST API şu yapıyı takip eder:</p><p>BASE_URL + /endpoint + ?param1=…&amp;param2=…</p><p>📘 API kullanım kılavuzu (documentation) her zaman temel kaynaktır. Tıpkı bir cihazın kullanım kılavuzu gibi, her API’nin bir resmi dokümantasyonu yani bir kullanım kılavuzu olur.</p><p>📌 <strong>API dökümanında şunlar yer alır:</strong></p><p>🖊 Hangi endpoint’ler var?</p><p>🖊 Parametreler nasıl yazılır?</p><p>🖊 API key nereye konur?</p><p>🖊 Yanıt yapısı nasıl?</p><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Uygulama Örneğinde:</strong></a><br> EIA API dökümanında, veri sorgulamak için birkaç yol tarif ediliyor:</p><ul><li>series_id ile veri çekme</li><li>data endpoint’i ile filtreleme yaparak veri çekme</li><li>category_id ile grup sorgulama</li></ul><p>En doğrudan ve sade yol olduğu için, series_id ile sorgulamak tercih edilmiştir. EIA dökümanında (<a href="https://www.eia.gov/opendata/documentation.php">https://www.eia.gov/opendata/documentation.php</a>) açıkça yazan şudur:</p><p>“You can request a specific series using <a href="https://api.eia.gov/v2/seriesid/%7Bseries_id%7D">https://api.eia.gov/v2/seriesid/{series_id}</a>”</p><p>Yani series_id endpoint’i, EIA’dan <strong>belirli bir zaman serisi</strong> verisini almak için kullanılıyor. Ve bu endpoint’in nasıl çalıştığı, örnek URL ile birlikte dökümanda gösterilmiş.</p><p>🔑 Kısacası neyin gerekli olduğu (series_id gibi) ve URL yapısının nasıl olacağı dökümanda belirtilmiş ve örnekler verilmiştir. İhtiyaç duyulan doğru series_id’ler <a href="https://www.eia.gov/opendata/browser/">https://www.eia.gov/opendata/browser/</a> vasıtasıyla tespit edilmiştir.</p><p>🔹 <a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb"><strong>EIA API Uygulama Örneğindeki</strong></a><strong> akışı özetlersek:</strong></p><p><strong>1. API key’in tanımlandı</strong></p><pre>headers = {&quot;X-API-KEY&quot;: API_KEY}</pre><p><strong>2. Önce EIA sayfasından Series ID öğrenildi</strong></p><pre>series = {<br>&quot;Tüketim&quot;: &quot;INTL.54–2-RUS-TBPD.A&quot;,<br>&quot;Üretim&quot;: &quot;INTL.54–1-RUS-TBPD.A&quot;<br>}</pre><p><strong>3. URL doğru biçimde hazırlandı</strong></p><pre>url = f&quot;https://api.eia.gov/v2/seriesid/{series_id}&quot;</pre><p><strong>4. requests ile veri istendi ve JSON yanıtı okundu</strong></p><pre>response = requests.get(url, headers=headers)</pre><p><strong>5. pandas ile veri DataFrame’e çevrildi ve analiz edildi</strong></p><pre>df = pd.DataFrame(data[&quot;response&quot;][&quot;data&quot;])</pre><h4><strong>🔍 7. Endpoint Nedir?</strong></h4><p><strong>Endpoint</strong>, bir API’nin sunduğu veri hizmetlerinden birine erişim sağlayan özel bir URL uzantısıdır. Ana adresten sonra gelen yol parçasıdır ve API’de hangi veri kümesine erişeceğini belirler.</p><p>📌 <strong>Temel URL</strong> (genellikle sabittir):<br> <a href="https://api.eia.gov/v2/">https://api.eia.gov/v2/</a> ← bu EIA API’sinin ana adresidir.</p><p>🔹 <strong>EIA API Uygulama Örneğiyle Açıklarsak:</strong></p><p><strong>🔸 1. Series ID endpoint’i</strong></p><pre>url = f&quot;https://api.eia.gov/v2/seriesid/{series_id}&quot;</pre><ul><li>Bu, önceden tanımlanmış bir veri serisine doğrudan erişim sağlar.</li><li>Örnek series_id: “INTL.54–2-IRN-TBPD.A” → İran’ın petrol tüketimi.</li><li>Bu endpoint kullanıldığında, <strong>“tek bir zaman serisi”</strong> olduğu gibi çekilir.</li></ul><p><strong>🔸 2. Data endpoint </strong>(Örneğin: petrol fiyatı veri kümesi)</p><pre>url = &quot;https://api.eia.gov/v2/petroleum/pri/spt/data/&quot;</pre><p>🖊 Bu endpoint, EIA’nın petrol fiyatlarına dair tüm verilerini içeren büyük bir veri kümesidir.</p><p>🖊 Bu tip endpoint’lerde params ile detay belirtmek gerekir:</p><ul><li>Hangi seri?</li><li>Hangi tarih aralığı?</li><li>Hangi sıklık? (monthly, yearly vs.)</li><li>Hangi sütunlar? (data[0]=value)</li></ul><p><strong>📌 Karşılaştırmalı Özet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ea8IRGnb0fyhZQAu0e6quQ.png" /></figure><p><strong>🔑 Benzetme yaparak açıklarsak: API </strong>=<strong> Menü, Endpoint</strong> =<strong> Menüdeki Yemek</strong></p><ul><li>“Tavuk” sipariş etmek istersen, doğru yemeği (endpoint’i) bilmelisin.</li><li>“Baharatlı Tavuk” istersen, parametre eklemelisin.</li></ul><h4>🔍<strong> 8. API ile Veri Çekmek İçin Her Zaman request.get() Modülü mü Kullanılır?</strong></h4><p>Python’da API’lerle iletişim kurmak için, yaygın bir standart olarak requests modülü kullanılır. En temel kullanımı şöyledir:</p><pre>response = requests.get(<br>url=&quot;https://api.example.com/endpoint&quot;,<br>headers={&quot;X-API-KEY&quot;: &quot;senin_keyin&quot;},<br>params={&quot;param1&quot;: &quot;deger1&quot;, &quot;param2&quot;: &quot;deger2&quot;} # opsiyonel<br>)</pre><p><strong>📌</strong> <strong>requests.get() fonksiyonu:</strong></p><p>🖊 URL’ye bir GET isteği yollar.</p><p>🖊 <strong>headers:</strong> kimlik doğrulama, içerik tipi vs. içindir.</p><p>🖊<strong>params:</strong> URL’ye eklemek istenen parametreler içindir.</p><p><strong>📌 Alternatif metotlar da vardır:</strong></p><ul><li><strong>requests.post()</strong> → veri göndermek için</li><li><strong>requests.put()</strong> → güncellemek için</li><li><strong>requests.delete()</strong> → silmek için</li></ul><h4>🔍<strong> 9. params Nedir? Ne İşe Yarar?</strong></h4><p><strong>params →</strong> URL’ye <strong>sorgu parametrelerinin</strong> (query parameters) eklenmesini sağlar. Bir API endpoint’ine belirli <strong>filtreleme veya seçim kriterlerini</strong> göndermek için kullanılır.</p><p><strong>📌 Genel Yazım Şekli:</strong></p><pre>response = requests.get(<br>url=&quot;https://api.example.com/data&quot;,<br>params={&quot;year&quot;: &quot;2023&quot;, &quot;country&quot;: &quot;USA&quot;, &quot;sort&quot;: &quot;desc&quot;}<br>)</pre><p><strong>Bu kodun çağırdığı URL:</strong></p><p><a href="https://api.example.com/data?year=2023&amp;country=USA&amp;sort=desc">https://api.example.com/data?year=2023&amp;country=USA&amp;sort=desc</a></p><p>Yani<strong> params, </strong>? sonrası URL’nin dinamik kısmını oluşturur.</p><p><strong>🎯 Ne Amaçla Kullanılır?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ER9MYcwXo5nefZJ4gGqrJw.png" /></figure><p>🔹 <strong>EIA API Uygulama Örneğinde params Kullanımı</strong></p><p>EIA API’de bazı endpoint’lerde params ile filtreleme yapılabiliyor. Aşağıdaki kod örneğinde</p><ul><li>Belirli bir zaman aralığında (start, end)</li><li>Belirli serilerin (facets)</li><li>Belirli bir sıralama (sort) ile istendiğini görüyoruz.</li></ul><pre>url = &quot;https://api.eia.gov/v2/petroleum/pri/spt/data/&quot;<br>params = {<br>&quot;frequency&quot;: &quot;monthly&quot;,<br>&quot;data[0]&quot;: &quot;value&quot;,<br>&quot;start&quot;: &quot;2020–01&quot;,<br>&quot;end&quot;: &quot;2023–01&quot;,<br>&quot;facets[series]&quot;: [&quot;PET.RWTC.D&quot;],<br>&quot;sort[0][column]&quot;: &quot;period&quot;,<br>&quot;sort[0][direction]&quot;: &quot;desc&quot;<br>}<br>response = requests.get(url, headers=headers, params=params)</pre><p><strong>✅ Özet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1TOVqXn28m0a1WOHQejHQ.png" /></figure><h4>🔍 <strong>10. API uygulaması ile Web Scrapping Arasındaki Farklar Nelerdir? Kullanım Amaçları Nelerdir</strong>?</h4><p><strong>API ile veri çekme</strong> ve <strong>Web Scraping </strong>farklı yöntemlerdir. Karşılaştırırsak;</p><p><strong>📊 1. TANIMLAR</strong></p><p><strong>✅ API (Application Programming Interface)</strong></p><p>🖊 Web sitelerinin <strong>resmi ve yapılandırılmış</strong> bir şekilde veri sunma yoludur.</p><p>🖊 Genellikle bir <strong>URL üzerinden</strong>, <strong>JSON</strong>, <strong>XML</strong> gibi formatlarda veri döner.</p><p>🖊 Yetkilendirme (API key) gerekebilir.</p><p><strong>Örnek:</strong> EIA API ile yıllık petrol tüketim verisi çekmek.</p><p><strong>✅ Web Scraping</strong></p><p>🖊 Web sayfalarının <strong>HTML içeriğini kazıyıp</strong> (scrape), oradan veri <strong>ayıklama</strong> işlemidir.</p><p>🖊 Sayfa <strong>insan gözüne</strong> hitap eder (örneğin &lt;table&gt;, &lt;div&gt;, &lt;span&gt; gibi HTML elementlerinden veri alınır).</p><p>🖊 Sayfa tasarımı değişirse, kodun da değişmesi gerekir.</p><p><strong>Örnek:</strong> EIA sayfasında tabloyu gözle görüp Python ile onu çekmeye çalışmak.</p><p><strong>📊 2. Farklar — Karşılaştırmalı Tablo</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UqNJuc4UhQWVQmQaJWPgg.png" /></figure><p><strong>📊 3. Ne Zaman Hangisi?</strong></p><p><strong>API Ne Zaman Kullanılır?</strong></p><p>🖊 Web sitesi API sunuyorsa: <strong>her zaman önce API tercih edilir.</strong></p><p>🖊 Veriler temiz, yapılandırılmış ve güncelse.</p><p><strong>Örnek: </strong>Hava durumu verisi, döviz kuru, enerji istatistikleri.</p><p><strong>Web Scraping Ne Zaman Kullanılır?</strong></p><p>🖊 Web sitesinde API yoksa.</p><p>🖊 Görsel veriye (ürün isimleri, fiyatlar) ulaşmak gerekiyorsa.</p><p><strong>Örnek:</strong> Otomobil satış siteleri, haber başlıkları, forum yorumları.</p><p>🔹<strong> Uygulamalı Örnek:</strong></p><p><strong>🧪 API ile:</strong></p><pre>import requests<br>url = &quot;https://api.eia.gov/v2/petroleum/sum/snd/data/&quot;<br>params = {&quot;frequency&quot;: &quot;annual&quot;, &quot;facets[series]&quot;: [&quot;MLUUPUS1&quot;]}<br>headers = {&quot;X-API-KEY&quot;: &quot;YOUR_API_KEY&quot;}<br>r = requests.get(url, headers=headers, params=params)<br>data = r.json()</pre><p><strong>🧪</strong> <strong>Web Scraping ile:</strong></p><pre>import requests<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://example.com/lubricants-data&quot;<br>r = requests.get(url)<br>soup = BeautifulSoup(r.text, &quot;html.parser&quot;)<br>rows = soup.find_all(&quot;tr&quot;)</pre><p><strong>✅ SONUÇ:</strong></p><p>🚩Eğer varsa: API kullan.<br>🚩 Eğer yoksa: Scraping bir opsiyon olabilir.<br>🚩 Ancak Web scraping <strong>hassas</strong>, <strong>kırılgan olabilir </strong>ve <strong>hukuki risk</strong> taşıyabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*aHd0H9VJHyet8Wio18QPJQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719bc4784706" width="1" height="1" alt=""><hr><p><a href="https://medium.com/t%C3%BCrkiye/10-maddede-api-719bc4784706">10 Maddede API</a> was originally published in <a href="https://medium.com/t%C3%BCrkiye">Türkçe Yayın</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In the Shadow of Petroleum (Oil): Analyzing Energy Dependency Through Data]]></title>
            <link>https://medium.com/@aydogdunurdan/in-the-shadow-of-petroleum-oil-analyzing-energy-dependency-through-data-e5db3f3bbbc4?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5db3f3bbbc4</guid>
            <category><![CDATA[carbon-emissions]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[petroleum]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 12:52:02 GMT</pubDate>
            <atom:updated>2025-09-03T12:25:48.485Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Why Is Oil Consumption So High in Developed Countries?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*5e4uEhRmyVOgJZW_ibmNdQ.png" /></figure><blockquote>In this article, through data, we uncover how oil has long been the invisible driver of U.S. economic growth. However, we also recognize it as a critical vulnerability — both due to finite resources and the long-term sustainability of our planet — bringing alternative strategies in energy to the forefront of global priorities.<br> Because the heavy dependence on refined petroleum products results in the burning of billions of barrels of oil each year, leading to frightening levels of carbon emissions into the atmosphere, which in turn cause climate crises and environmental disasters. Furthermore, as the global energy map is redrawn based on oil reserves, we observe that countries with a high appetite for petroleum products play a key role in shaping international relations and geopolitical interventions.</blockquote><p>🔗 <a href="https://medium.com/t%C3%BCrkiye/petrol%C3%BCn-g%C3%B6lgesinde-verilerle-enerjide-ba%C4%9F%C4%B1ml%C4%B1l%C4%B1%C4%9F%C4%B1n-i%CC%87ncelenmesi-313b7d8ec09d"><strong>Türkçe / Turkish için</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*KZBvWqJhisHUmbqOM4v35g.png" /></figure><blockquote>Within the scope of this article, refined petroleum production and consumption data were visualized using the API provided by the U.S. Department of Energy’s Energy Information Administration (EIA). Through this visualization, the degree of dependency on petroleum across countries was analyzed. Forecasting models were developed and compared for refined petroleum product consumption in the United States using deep learning and machine learning methods. Forecasting models used include: Linear Regression, Random Forest, Polynomial Regression, XGBoost, LSTM, and Prophet.</blockquote><p><strong>Detailed information about the dataset</strong> is provided at the end of the article.<br>For the API, data visualizations, and all modeling code, refer to the GitHub:</p><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb?source=post_page-----313b7d8ec09d---------------------------------------">eia-Petroleum-Products-Consumption-Production/API_issue_eng.ipynb at main · nrdnay/eia-Petroleum-Products-Consumption-Production</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*fFQ65evmo0hlgIeErr6lVg.png" /></figure><h3>Results from Data Visualization:</h3><ul><li>According to 2014 data, the U.S., India, Russia, and Turkey produced more refined petroleum products than they consumed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVAYzHlscRiPjV89oq7EMQ.png" /></figure><ul><li>According to 2023 consumption data:<br> Surprisingly, although Saudi Arabia has a population of only 33 million, it ranks 4th in total petroleum product consumption. In per capita consumption, it ranks first.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syf_ACXkdIZjJJKEnAu71g.png" /></figure><ul><li>With a population of 335 million, the U.S. has roughly one-quarter the population of China and India. Yet, its total refined petroleum product consumption is 1.25 times higher than China’s and 3.25 times higher than India’s.<br> In per capita terms, the disparity is even more striking: an average person in the U.S. consumes 5.26 times more petroleum products than a person in China, and 15.35 times more than someone in India.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nifN9RBWr1YYoXIV_X8fQ.png" /></figure><ul><li>Canada’s per capita consumption of petroleum products is very close to that of the U.S., ranking 3rd.</li><li>Over the years, China has shown by far the largest increase in petroleum product consumption. India follows in second place, while other countries have shown relatively stable growth.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHS6WXzTVQOiT8Yzf1UYqA.png" /></figure><ul><li>Since the U.S. overwhelmingly dominates total annual consumption share, a separate visualization excluding the U.S. was used to better compare other countries. It shows China’s dominance, while India, Russia, and Saudi Arabia display similar levels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKEV6pUALy3R4WT71VBhQg.png" /></figure><h3>Comparison of Forecasting Models</h3><ul><li>Forecasting was conducted using six different models, and the accuracy of their results was evaluated.<br> While Linear Regression and LSTM showed similar curves, Random Forest and XGBoost also provided close results.<br> Based on forecasts for the last 5 years, the Random Forest model delivered the most accurate predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*A-A5YBh3arORLd1RqSN3EQ.png" /></figure><h3>Conclusion:</h3><p>The data reveal two striking insights:</p><ol><li>The U.S. is by far the largest consumer of petroleum products.</li><li>China is the country with the fastest-growing petroleum product consumption.<br> (However, an average person in the U.S. still consumes 5.26 times more petroleum products than someone in China.)</li></ol><h3>1. The U.S.: The World’s Leading Consumer of Petroleum Products</h3><h4>1.1. Oil Dependency in Energy</h4><p>The U.S.’s heavy reliance on petroleum products for energy creates not only an economic vulnerability but also weakens the country from foreign policy and national security perspectives.<br> This high demand for energy and, consequently, petroleum determines the U.S.’s political and geopolitical actions in the Middle East and other oil-rich regions.<br> In other words, securing access to oil resources is one of the primary reasons behind the U.S.’s intensified global military and diplomatic activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*SfgMMlbi2aFd1KBzFBjGCw.jpeg" /></figure><h4>1.2. Environmental Impact and Carbon Emissions</h4><p>The U.S.’s leadership in petroleum-based energy use makes it the world’s largest carbon emitter and environmental polluter.<br> This positions the U.S. with a global responsibility to lead the fight against climate change.</p><p>Therefore:<br> 🍃 In order to create a more livable environment and planet, the U.S. must rapidly reduce its dependence on oil, reshape its national and global policies accordingly, expand the use of renewable energy sources, and commit to zero-carbon goals.<br> 🍃 This is not just an environmental or moral obligation — it is a strategic necessity for national security, economic sustainability, and technological advancement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*VWtUvMxrlBNnw1mR85PisA.jpeg" /></figure><h3>2. China: The Country with the Fastest Growing Petroleum Consumption</h3><p>The second key finding from the data is that, especially since the 1990s, the pace of refined petroleum production and consumption in China has surpassed that of other nations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ijE6olExDs_ArE1yoEWmtw.jpeg" /></figure><p><strong>Key drivers of this rapid increase include:</strong></p><p><strong>1-</strong> China’s rapid growth following the “reform and opening up” policy in the late 1980s, and its rise as a global manufacturing hub in the 1990s — causing soaring energy demand, especially for refined petroleum in transportation.</p><p><strong>2-</strong> Rapid urbanization and improved living standards over the past 40 years, along with a sharp increase in vehicle ownership, leading to higher energy and transport fuel demand.</p><p><strong>3-</strong> Growth in road transportation, aviation, and shipping sectors since the 1990s, boosting consumption of diesel, gasoline, and jet fuel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*j_093uq8YxcT53W1TULeUQ.png" /></figure><p><strong>4-</strong> To ensure energy security, China has increased crude oil imports and expanded refinery capacity through investments.</p><p><strong>5-</strong> Its export-driven growth model has increased global trade volume, driving up demand for petroleum products in logistics and transportation.</p><p><strong>6-</strong> Despite recent efforts toward energy transformation since the 2000s, petroleum product demand has remained high due to rapid growth, alongside increased use of oil products in power and heating sectors.</p><h4><strong>Detailed Information About the Dataset</strong></h4><ul><li>The data were retrieved from the EIA (U.S. Energy Information Administration) using an API under the name global_petroleum_production_consumption and saved in CSV format.</li><li>Since the API key is personal and time-limited, this dataset was used for consistency. A sample API code implementation is also provided for reference.</li><li>The dataset includes annual production and consumption quantities of refined petroleum products across 10 countries:<br> Turkey, USA, Russia, China, India, Iran, Saudi Arabia, Canada, UK, and France.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*8Gfjt6lRYSlZClsh2zkBhg.png" /></figure><ul><li>Depending on the country, production data generally cover the years 1985–2014, while consumption data span 1980–2023.</li><li>The unit used for production and consumption is <strong>1,000 barrels per day</strong>.</li><li>Population data are in millions (<strong>population × 1⁰⁶</strong>).</li></ul><h4>🛢️ What Is Meant by Refined Petroleum Products? Refined petroleum products refer to the derivatives obtained from processing crude oil in refineries and generally include:</h4><p>🛢️<strong>Gasoline</strong>: The main fuel for motor vehicles; also referred to as “motor gasoline” in the U.S.</p><p>🛢️<strong>Diesel Fuel</strong>: Used in road and off-road vehicles, trucks, and heavy machinery.</p><p>🛢️<strong>Jet Fuel</strong>: Fuel used in aircraft (kerosene types).</p><p>🛢️<strong>Fuel Oil</strong>: Heavy oils used in industry and power plants (e.g., №2 and №6 fuel oils).</p><p>🛢️<strong>LPG (Liquefied Petroleum Gases)</strong>: Includes propane and butane, used in heating and transportation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*5z2JOGpIEiGZ1stTXRNfaA.png" /></figure><p>🛢️<strong>Naphtha</strong>: Used as feedstock in petrochemicals or as a solvent.</p><p>🛢️<strong>Petroleum Coke</strong>: A solid fuel used in power generation and industry.</p><p>🛢️<strong>Asphalt and Bitumen</strong>: Heavy residues used in road construction.</p><p>🛢️<strong>Others</strong>:<br> • Paraffin, waxes, white spirit<br> • Lubricants<br> • Solvents<br> • Other refined products</p><p><strong>What Is Not Included in Refined Petroleum Products?</strong></p><ul><li>Crude oil itself is not included — only processed derivatives.</li><li>Natural gas and natural gas liquids (NGLs) are tracked separately (though in some EIA tables, LPG from NGL may be included).</li></ul><p>The EIA typically categorizes this as “Total petroleum products” or “Refined petroleum products”.</p><p>For all coding details related to the API application, data visualization, and modeling:<br> 🔗 GitHub link:</p><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb?source=post_page-----313b7d8ec09d---------------------------------------">eia-Petroleum-Products-Consumption-Production/API_issue_eng.ipynb at main · nrdnay/eia-Petroleum-Products-Consumption-Production</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lZJLTZ6TU-Lg0VLsT9Ar_w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5db3f3bbbc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Petrolün Gölgesinde: Verilerle Enerjide Bağımlılığın İncelenmesi]]></title>
            <link>https://medium.com/t%C3%BCrkiye/petrol%C3%BCn-g%C3%B6lgesinde-verilerle-enerjide-ba%C4%9F%C4%B1ml%C4%B1l%C4%B1%C4%9F%C4%B1n-i%CC%87ncelenmesi-313b7d8ec09d?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/313b7d8ec09d</guid>
            <category><![CDATA[veri-bilimi]]></category>
            <category><![CDATA[sürdürülebilirlik]]></category>
            <category><![CDATA[enerji]]></category>
            <category><![CDATA[karbon-salınımı]]></category>
            <category><![CDATA[petrol]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 15:10:54 GMT</pubDate>
            <atom:updated>2025-09-03T12:41:23.468Z</atom:updated>
            <content:encoded><![CDATA[<h4>Gelişmiş ülkelerde petrol tüketimi neden çok yüksek?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*5e4uEhRmyVOgJZW_ibmNdQ.png" /></figure><blockquote>Bu makalede verilerle, petrolün ABD ekonomisindeki büyümenin görünmeyen kahramanı olduğunu keşfederken, bunun aynı zamanda kaynakların kısıtlılığı ve gezegenimizin geleceği açısından bir zaafiyet olduğunu görerek, enerjide alternatif stratejiler geliştirme gereğinin önemli bir gündem maddesi olarak karşımızda durduğuna şahitlik ediyoruz.</blockquote><blockquote>Çünkü, rafine petrol ürünlerine olan bağımlılık nedeniyle her yıl milyarlarca varil petrolün yakılması, atmosfere salınan karbon miktarının korkutucu boyutlara ulaşmasına, dolayısıyla iklim krizlerine ve çevre felaketlerine neden oluyor. <strong>Bununla birlikte, dünya enerji haritası petrol rezervlerine göre yeniden çizilirken, petrol ürünlerine iştahı yüksek olan ülkelerin, uluslararası ilişkilerin ve müdahalelerin şekillenmesinde de baş rol oynadığını gözlemleyebiliyoruz.</strong></blockquote><p>🔗 <a href="https://medium.com/@aydogdunurdan/in-the-shadow-of-petroleum-oil-analyzing-energy-dependency-through-data-e5db3f3bbbc4"><strong>For English / İngilizce</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*KZBvWqJhisHUmbqOM4v35g.png" /></figure><blockquote>Bu makale kapsamında, API ile ABD Enerji Bakanlığı’na bağlı Enerji Bilgi İdaresi (EIA : Energy Information Administration) kurumundan alınan güncel verilerin görselleştirilmesiyle ülkelerin rafine petrol üretim — tüketim miktarları incelenerek petrole olan bağımlılıkları analiz edilmiştir. Derin öğrenme (deep learning) ve makine öğrenmesi (machine learning) metodlarıyla ABD’deki rafine petrol ürünleri tüketim miktarları için tahminleme modelleri oluşturulmuş ve karşılaştırılmıştır. Tahmin modelleri: Lineer Regresyon (Linear Regression), Rastgele Orman (Random Forest), Polinom Regresyonu (Polynomial Regression), XGBoost, LSTM, Prophet.</blockquote><p>“Veri Seti Hakkında Detaylı Bilgi” makalenin sonunda yer alıyor. API uygulaması, veri görselleştirme ve tüm modelleme kodları için github link:</p><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb">eia-Petroleum-Products-Consumption-Production/API_issue_eng.ipynb at main · nrdnay/eia-Petroleum-Products-Consumption-Production</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*fFQ65evmo0hlgIeErr6lVg.png" /></figure><h4>Veri Görselleştirme ile Alınan Sonuçlar:</h4><blockquote><strong><em>2014 yılı verilerine göre ; </em></strong><em>Amerika, Hindistan, Rusya ve Türkiye, tükettiğinden daha fazla rafine petrol ürünü üretmiştir.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVAYzHlscRiPjV89oq7EMQ.png" /></figure><blockquote><strong><em>2023 yılı tüketim verilerine göre;</em></strong></blockquote><p>📚 İlginç bir şekilde Suudi Arabistan nüfusu 33 milyon olmakla birlikte, petrol ürünleri toplam tüketim miktarıyla 4. Sırada yer alıyor. Kişi başı tüketimde ise birinci sırada yer alıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syf_ACXkdIZjJJKEnAu71g.png" /></figure><p>📚 Amerika 335 milyon nüfusuyla Çin ve Hindistan nüfusunun yaklaşık dörtte biri. Buna karşın Rafine Petrol Ürünleri toplam tüketim miktarı Çin’in 1,25 katı, Hindistan’ın ise 3,25 katı.</p><p>Kişi başı tüketim miktarlarını karşılaştırdığımızda, durum çok daha çarpıcı: Amerika’da yaşayan bir kişi, Çin’de yaşayan bir kişinin tükettiği petrol ürününün 5,26 katını, Hindistan’da yaşayan bir kişinin tükettiği petrol ürününün 15,35 katını tüketiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nifN9RBWr1YYoXIV_X8fQ.png" /></figure><p>📚 Kanada’daki kişi başı petrol ürünleri tüketim miktarı ise Amerika’yla çok yakın bir değer gösteriyor. Sıralamada 3.</p><p>📚<strong> </strong>Yıllara göre değişim incelendiğinde, petrol ürünleri tüketim miktarındaki en yüksek artışın belirgin bir farkla Çin’e ait olduğu gözleniyor. Hindistan 2. Sırada sayılabilirken, diğer ülkeler daha stabil düzeylerde artış gösteriyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHS6WXzTVQOiT8Yzf1UYqA.png" /></figure><p>📚<strong> </strong>Yıllık toplam tüketim payının en büyüğü açık ara farkla Amerika’ya ait olduğu için, diğer ülkeleri daha iyi kıyaslamak amacıyla, Amerika hariç tutularak diğer ülkelerin yıllara göre % tüketim payları değişimi görselleştirildiğinde, iyine Çin farkı görülebilirken, Hindistan, Rusya ve Suudi Arabistan’ın yakın değerler gösterdiğini söyleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKEV6pUALy3R4WT71VBhQg.png" /></figure><h4>Tahmin Modellerinin Karşılaştırılması</h4><p>📚<strong> </strong>6 farklı model ile tahminleme yapılarak, sonuçların doğruluk dereceleri ölçülmüştür. Liner Regresyon ve LSTM model tahminleri birbirine yakın eğrilere sahipken, Random Forest ve XGBoostingin birbirine yakın sonuçlar verdiği görülüyor. Son 5 yıl tahmin sonuçlarına göre en iyi sonucun Random Forest modeliyle alındığı söylenebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*A-A5YBh3arORLd1RqSN3EQ.png" /></figure><h3>Sonuç Değerlendirme :</h3><h4><strong>Veriler 2 çarpıcı sonuç aktarıyor :</strong></h4><blockquote><strong>1- ABD, Petrol ürünleri tüketiminin, açık ara farkla en yüksek olduğu ülke konumundadır.</strong></blockquote><blockquote><strong>2- Çin, petrol ürünleri tüketiminin en hızlı yükseliş gösterdiği ülke konumundadır. (Ancak hala, ABD’de yaşayan bir kişinin tükettiği petrol ürünü miktarı, Çin’deki bir kişinin tükettiği miktarın 5.26 katıdır.)</strong></blockquote><h4><strong>1-ABD : Petrol Ürünleri Tüketiminin En Yüksek Olduğu Ülke :</strong></h4><p><strong>1.1 Enerjide Petrol Bağımlılığı</strong></p><p>Petrol ürünlerine olan yüksek bağımlılık stratejik bir zafiyet oluştururken, yalnızca ekonomik açıdan değil, dış politika ve ulusal güvenlik açısından da kırılgan hale getiriyor ABD’yi.</p><p>Bu yüksek enerji ve dolayısıyla petrol arzı, ABD’nin Ortadoğu ve diğer petrol rezervi zengin bölgelerdeki, politika ve jeopolitik hamlelerini belirliyor. Diğer bir ifadeyle, petrol kaynaklarına erişimi garanti altına almak, ABD’nin küresel ölçekteki askeri ve diplomatik faaliyetlerini yoğunlaştırmasının en temel nedenlerinden birini oluşturuyor.</p><p><strong>1.2. Çevresel Etki ve Karbon Salınımı</strong></p><p>ABD’nin petrol ürünlerine, dolayısıyla fosil yakıtlara dayalı enerji kullanımındaki liderliği, ABD’yi aynı zamanda atmosfere en fazla karbon salınımı yapan ve çevreyi en çok kirleten ülke konumuna getiriyor ve dolayısıyla ABD’ye, iklim değişikliğiyle mücadelede küresel düzeyde liderlik ve sorumluluk yüklüyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*SfgMMlbi2aFd1KBzFBjGCw.jpeg" /></figure><p>O nedenle;</p><p>🍃Daha yaşanılabilir bir çevre ve dünya için, öncelikle ABD’nin petrol bağımlılığını hızla azaltması, ülke ve dünya politikalarını buna uygun olarak belirlemesi, yenilenebilir enerji kaynaklarını yaygınlaştırma ve sıfır karbon hedeflerine kararlılıkla yönelmesi bir tercih değil, bir zorunluluk haline geliyor.</p><p>🍃Bu zorunluluk sadece dünya ve çevre için değil, aynı zamanda ABD’nin kendi ulusal güvenliği, ekonomik sürdürülebilirliği ve teknolojik ilerlemesi için de, hızlandırılması gereken acil eylem planı olarak önlerinde duruyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*VWtUvMxrlBNnw1mR85PisA.jpeg" /></figure><h4>2. <strong>Çin : Petrol Ürünleri Tüketiminin En Hızlı Yükseldiği Ülke</strong></h4><p>Verilerin gösterdiği 2. Çarpıcı bulgu, Özellikle 1990’lardan itibaren “Çin’deki rafine petrol üretim ve tüketim miktarlarındaki ivmenin, diğer ülkelere oranla çok daha yüksek olmasıdır. Bu hızlı artışın başlıca nedenlerini şu şekilde sıralayabiliriz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ijE6olExDs_ArE1yoEWmtw.jpeg" /></figure><p><strong>1. </strong>1980’lerin sonundan itibaren Çin, “reform ve dışa açılma” politikasıyla çok hızlı bir şekilde büyümeye başlarken, 1990’lardan itibaren dünya çapında üretim merkezi haline gelmesi; böylece enerji ihtiyacı ve özellikle taşımacılık için rafine petrol ürünlerine olan talebin hızla artması,</p><p><strong>2. </strong>Nüfustaki artışın yanı sıra, son 40 yılda yaşanan hızlı kentleşme ve yaşam standartlarının yükselmesi ve otomobil sahipliğinin ciddi biçimde artması,</p><p><strong>3.</strong> Otomobil üretimi ve kullanım artışıyla birlikte,<strong> </strong>kara, hava, deniz taşımacılığı sektörlerindeki büyüme nedeniyle motorin, benzin ve jet yakıtı tüketiminin artması.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*j_093uq8YxcT53W1TULeUQ.png" /></figure><p><strong>4. </strong>Enerji arz güvenliği için hem ham petrol ithalatını artırması, hem de yatırımlarla rafineri kapasitesini genişletmesi.</p><p><strong>5. </strong>İhracat odaklı büyüme modeliyle küresel ticaret hacmini arttırarak, lojistik ve ulaşımda petrol ürünlerine olan talebin yükselmesi.</p><p><strong>6. </strong>Modernleşme kapsamında elektrik ve ısınmada, kömürün yanında petrol ürünlerinin kullanılmasındaki artış, 2000’lerden itibaren enerjideki dönüşüm çabalarına rağmen, hızlı büyüme nedeniyle petrol ürünleri talebinin yüksek kalması.</p><h3><strong>***Veri Seti Hakkında Detaylı Bilgi</strong></h3><p><strong>*</strong>Veriler, API uygulaması ile EIA’nın (US Energy Information Administration) web sayfasından “global_petroleum_production_consumption” adıyla çekilerek, csv formatında kaydedilmiştir.</p><p><strong>*</strong>API Key number kişisel olduğu ve süreli olduğu için bu veri setiyle devam edilmiştir. Bununla birlikte örnek API kod uygulaması bilgi olarak yer almaktadır.</p><p><strong>*</strong>Veri setinde <strong>Rafine Petrol Ürünlerinin </strong>yıllara göre üretim ve tüketim miktarlarının yer aldığı 10 ülke: Türkiye, Amerika, Rusya, Çin, Hindistan, İran, Suudi Arabistan, Kanada, İngiltere ve Fransa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*8Gfjt6lRYSlZClsh2zkBhg.png" /></figure><p><strong>*Ülke bazında değişiklik göstermekle birlikte, üretim verileri genel olarak 1985–2014 yılları arasını, tüketim verileri ise <em>ağırlıklı olarak </em>1980–2023 yılları arasını kapsıyor.</strong></p><p><strong>*Üretim ve Tüketim miktarı için kullanılan birim 1000 varil/gün’dür.</strong></p><p><strong>*Ülkelerin nüfusu milyondur. (nüfus*10⁶)’dır.</strong></p><h4>🛢️<strong>Rafine Petrol Ürünleri ile kast edilen; ham petrolün rafinerilerde işlenmesi sonucu elde edilen çeşitli petrol türevlerinin toplamıdır ve çoğunlukla aşağıdaki ürünleri kapsar:</strong></h4><p>🛢️<strong>Benzin (Gasoline):</strong> Motorlu taşıtlarda kullanılan bu ana yakıt; Amerika’da “motor gasoline” olarak da geçer.</p><p>🛢️<strong>Dizel Yakıtı (Diesel Fuel):</strong> Karayolu ve dışı taşıtlarda, kamyonlarda, iş makinelerinde kullanılır.</p><p>🛢️<strong>Jet Yakıtı (Jet Fuel):</strong> Uçaklarda kullanılan yakıt (kerosen türleri).</p><p>🛢️<strong>Fuel Oil (Yakıt Yağları):</strong> Sanayi ve enerji santrallerinde kullanılan ağır yakıt yağları (№2 fuel oil, №6 fuel oil gibi).</p><p>🛢️<strong>LPG (Liquefied Petroleum Gases):</strong> Propan, bütan gibi sıvılaştırılmış gazlar; hem ısınmada hem de ulaşımda kullanılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*5z2JOGpIEiGZ1stTXRNfaA.png" /></figure><p>🛢️<strong>Naphtha:</strong> Petrokimya sanayinde hammadde olarak veya solvent olarak kullanılan ürünler.</p><p>🛢️<strong>Petrol Koku (Petroleum Coke):</strong> Elektrik üretimi ve sanayide kullanılan katı bir yakıt.</p><p>🛢️<strong>Asfalt ve Bitüm:</strong> Yol yapımında kullanılan ağır kalıntılar.</p><p>🛢️<strong>Diğerleri:</strong></p><ul><li>Parafin, mum, white spirit gibi özel ürünler</li><li>Madeni yağlar (lubricants)</li><li>Solventler</li><li>Diğer rafine ürünler</li></ul><p><strong>Rafine Petrol Ürünleri Neyi Kapsamaz?</strong></p><ul><li>Ham petrolün kendisi bu kategoriye dahil değildir; sadece işlenmiş ürünler kapsanır.</li><li>Doğal gaz ve doğal gaz sıvıları (NGLs) ayrı kategoride izlenir (bazı EIA tablolarında ise NGL’den elde edilen LPG dahil edilebilir).</li></ul><p>EIA, bu başlığı genellikle “<strong>Total petroleum products</strong>” veya “<strong>Refined petroleum products</strong>” olarak tanımlar.</p><blockquote><strong>API uygulaması, veri görselleştirme ve modellemeye ait tüm kodlama detayları için github link:</strong></blockquote><p><a href="https://github.com/nrdnay/eia-Petroleum-Products-Consumption-Production/blob/main/API_issue_eng.ipynb">eia-Petroleum-Products-Consumption-Production/API_issue_eng.ipynb at main · nrdnay/eia-Petroleum-Products-Consumption-Production</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lZJLTZ6TU-Lg0VLsT9Ar_w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=313b7d8ec09d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/t%C3%BCrkiye/petrol%C3%BCn-g%C3%B6lgesinde-verilerle-enerjide-ba%C4%9F%C4%B1ml%C4%B1l%C4%B1%C4%9F%C4%B1n-i%CC%87ncelenmesi-313b7d8ec09d">Petrolün Gölgesinde: Verilerle Enerjide Bağımlılığın İncelenmesi</a> was originally published in <a href="https://medium.com/t%C3%BCrkiye">Türkçe Yayın</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[India’s Energy Pulse: Shifting Trends in Petroleum Products and the Power of Data Science]]></title>
            <link>https://medium.com/the-random-nerdiness-collective/indias-energy-pulse-shifting-trends-in-petroleum-products-and-the-power-of-data-science-9b226297419c?source=rss-2c9d96df88e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b226297419c</guid>
            <category><![CDATA[oil-consumption-in-india]]></category>
            <category><![CDATA[lstm-time-series]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[petroleum-products]]></category>
            <category><![CDATA[indiaoiltrends]]></category>
            <dc:creator><![CDATA[Nurdan Aydogdu]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 14:50:23 GMT</pubDate>
            <atom:updated>2026-03-13T00:20:06.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*xhibA8dlMLtdQVtPArGgdQ.gif" /><figcaption>The image of the exploding petroleum (oil) well is from the successful petroleum-themed movie “There Will Be Blood” <em>A must-watch.</em></figcaption></figure><p><em>Is diesel the most consumed petroleum product in India? Why are industrial lubricants on an upward trend? Why has LPG gained significance in rural areas?</em></p><blockquote>Despite alternative energy sources, oil and its products continue to be the world’s most strategic and decisive energy source. In this context, India’s oil consumption trends, which attract attention with its 1.4 billion population, both its growing economy and its huge market potential, are of great importance. In this article, we will analyze oil consumption data for the period April 2020 — February 2023, evaluate economic and political effects, and develop a deep learning forecasting model.</blockquote><blockquote>The dataset reflects the consumption trends of oil products in India over time. Using this data suitable for time series analysis, we will reveal consumption dynamics by segment and year and create a Deep Learning LSTM forecasting model with future projections. In this way, it will be possible to understand both the current situation and shed light on future strategies.</blockquote><p>🔗 <a href="https://medium.com/t%C3%BCrkiye/petrol-ve-petrol-%C3%BCr%C3%BCnlerinin-hindistandaki-t%C3%BCketim-trendlerinin-analizi-84aed2d427d4"><strong>Türkçe / Turkish için</strong></a></p><p><strong>A look at the Dataset:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*jWbTmeGviwNv3dcN14poPA.png" /><figcaption><strong>Table 1 </strong>—<strong> Original Dataset</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*LTcyhKRge_A6Kl_HbAVzUw.png" /><figcaption><strong>Table 2</strong> —<strong> Annual consumption amounts of dataset according to product segments</strong></figcaption></figure><p><strong>You can access the complete code for the project at the following link:</strong> <a href="https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb">https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb</a></p><p><strong>🛢️Petroleum Product Categories in the Data Set for India</strong></p><p>Located at the center of the oil industry, these product categories play a critical role in a wide range of areas from daily life to heavy industry. These 12 main petroleum product categories that stand out in India’s energy consumption data are summarized below, along with their areas of use:</p><p><strong>1. ✈️ ATF (Aviation Turbine Fuel): </strong>A highly refined jet fuel designed for turbine engines.<br> <strong>Main Uses:</strong> Commercial passenger aircraft, military aviation, cargo planes and private jets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*rdQT4mA_8R0KiDjgY4qWsw.png" /><figcaption><strong>Locations of Oil Refineries in India</strong></figcaption></figure><p><strong>2. 🛣️Bitumen: </strong>A dense, black, viscous substance obtained from crude oil distillation; often the residue from vacuum distillation.<br> <strong>Main Uses:</strong> Road construction (asphalt), waterproofing systems, roofing and construction adhesives</p><p><strong>3. 🔥 FO &amp; LSHS (Furnace Oil &amp; Low-Sulphur Heavy Stock):</strong> Heavy petroleum fuels used in high-temperature industrial operations.<br> <strong>Main Uses:</strong> Power generation in thermal plants, steam production in factories, fuel for cement, steel, and glass industries</p><p><strong>4. 🚛 HSD (High-Speed Diesel):</strong> A refined diesel fuel used in high-speed diesel engines.<br> <strong>Main Uses:</strong> Heavy vehicles like buses, trucks, and trains, diesel generators, agricultural and construction machinery</p><p><strong>5. ⚙️LDO (Light Diesel Oil):</strong> A lighter, less refined diesel variant compared to HSD.<br> <strong>Main Uses:</strong> small-scale industrial boilers, agricultural engines, generators and burners</p><p><strong>6. 🔄 LPG (Liquefied Petroleum Gas):</strong> A pressurized mix of propane and butane gases, known for its versatility and clean combustion.<br> <strong>Main Uses:</strong> Domestic cooking and heating, automotive fuel (autogas), industrial kitchens and production processes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*xg_XcS8u4Ngk769RUYAXeA.png" /><figcaption><em>India’s petroleum consumption is greatly influenced by the Make In India Program (Logo pictured)</em></figcaption></figure><p><strong>7. 🛠️Lubricants &amp; Greases:</strong> Petroleum-based products that reduce friction and wear in machinery.<br> <strong>Main Uses:</strong> Engines of cars and motorcycles, industrial equipment, bearings, gears, and hydraulic systems</p><p><strong>8. 🚗 MS (Motor Spirit / Petrol):</strong> A volatile fuel used in internal combustion engines.<br> <strong>Main Uses:</strong> Passenger cars and two-wheelersm, small marine engines, portable generators</p><p><strong>9. 🧪 Naphtha: </strong>A light, flammable hydrocarbon mixture obtained from crude oil distillation.<br> <strong>Main Uses:</strong> Feedstock in petrochemical industries (e.g., ethylene, propylene), production of solvents and thinners, raw material for gasoline blending</p><p><strong>10. 📦 Others: </strong>Includes petroleum products that do not fall under the primary categories but serve specialized industrial needs.<br> <strong>Main Uses:</strong> White spirit, solvents, and liquids used in inks and paints, additives in laboratories and specialty chemical production</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*8f9XS64CCg0jwsIxU_sC9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*iDN2kTVSI5jtS1nOsqLmQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*JHrovDbVqELqxb556QSHaA.png" /><figcaption>I highly recommend the magnificent movie about oil exploration: “There Will Be Blood” with the images of the explosion and fire of the oil (petroleum) well and the extraordinary performance of Daniel Day-Lewis. 😎</figcaption></figure><p><strong>11. 🧱Petroleum Coke (Petcoke):</strong> A solid carbon-rich byproduct of oil refining, resembling coal.<br> <strong>Main Uses:</strong> Fuel in cement kilns, anode material in aluminum smelting, carbon source in metallurgical processes</p><p><strong>12. 🪔 SKO (Superior Kerosene Oil):</strong> A light, refined fuel commonly known as kerosene, especially in rural households.<br> <strong>Main Uses:</strong> Domestic lighting and heating, camping stoves and lanterns, backup generators for military and emergency use</p><p>Each product category contributes critically to India’s energy infrastructure and supports national initiatives like <strong>Make in India</strong>. Understanding this diversity is not only essential for energy professionals but also for anyone interested in the country’s sustainable industrial growth.</p><h3><strong>Annual Consumption Trends by Petroleum Product</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykRWB27MG5-BqXjpxeXYEA.png" /><figcaption><strong>Chart 1: Annual Consumption Trend Graph</strong></figcaption></figure><p>Chart 1 shows the increase, decrease, or stagnation trends in these product categories. It’s important to consider that the 2020 data reflects the impact of COVID-19, while the 2021 and 2022 data represent the return to normalcy and economic recovery. <em>(The Coding Source: </em><a href="https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb"><em>https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb</em></a><em>)</em></p><p>While Motor Spirit (gasoline) is the most consumed petroleum product globally, <strong>in India, HSD (diesel) clearly dominates.</strong> A deeper look reveals why 🚛 HSD (High-Speed Diesel) consumption is leading :</p><ul><li>The primary reason for this is that freight transportation in India is primarily road-based.</li><li>Diesel usage in trucks and buses</li><li>Widespread use of diesel in tractors and water pumps in agriculture</li><li>Diesel use in generators and industries due to power outages</li><li>Use of diesel in heavy machinery in construction and industry</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*JA4qXZplGbp23WoftFYYBw.png" /><figcaption><strong>Chart 2: </strong>Petroleum Product Consumption — Pie Chart</figcaption></figure><p>Until 2014, diesel prices in India were subsidized by the government. After these subsidies ended, gasoline vehicles became more popular, increasing gasoline consumption. According to reports from automakers, the share of gasoline vehicles rose from around 40 % to 80 %, while diesel vehicles dropped from 50 % to 10–15 %.</p><p>As seen in <strong>Chart 1</strong> and <strong>Chart 2</strong>, the second most consumed product is gasoline (MS), followed by LPG in third place. At this point, it’s worth detailing the government policies behind the high LPG consumption.</p><p><strong>🔄 LPG </strong>In rural India, where people traditionally used wood, coal, dung, and crop waste, indoor air pollution caused health issues, especially among women and children. In 2016, the government launched the <strong>Pradhan Mantri Ujjwala Yojana (PMUY)</strong> to promote LPG usage as an alternative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*m_ZBZ70v2sR6OAlHMwMEmw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*vftSHO7KmpTNWvwELOHO8A.jpeg" /><figcaption><strong><em>PMUY promotional posters encouraging rural LPG use</em></strong></figcaption></figure><p>The program provided free LPG connections to low-income rural families and women below the poverty line. As of 2025, active LPG connections have reached 90 million, significantly increasing LPG consumption. In return, invaluable social benefits were achieved:</p><ul><li>Empowerment of women</li><li>Reduced respiratory and eye diseases</li><li>Time saved in fuel collection redirected toward education and other activities</li></ul><h3>Monthly Consumption Trends</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*X8XyHA_BgBL9nRybMU37Tg.png" /></figure><p>To observe seasonal effects and monthly fluctuations, we analyzed monthly consumption graphs. As of 2022, there is a noticeable decline in SKO, LDO, Naptha, and Lubricants &amp; Greases. Bitumen, used in 90% of road construction, shows a seasonal drop during July, August, and September. <em>(Graphs are available at the end of the article.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nVPVa1AmtxbjyOC-y1v1Xw.png" /></figure><p><strong>🛠️ Lubricants &amp; Greases</strong> are generally in growth mode, with automotive oils dominating the market, especially engine oils.<br>In the <strong>Industrial Oils</strong> category, hydraulic oils have the highest consumption. Due to rapid industrialization, government incentives like like Make in India, Industry 4.0 adoption, and new infrastructure projects, consumption of industrial oils and greases is expected to increase sharply. Metalworking fluids are forecasted to be the fastest-growing group.</p><p>Given my industry experience, I’ll leave the detailed discussion of “Industrial Oil Consumption in India” to a future article.</p><p>As for other declining products:</p><p><strong>🪔 SKO</strong> usage has dropped due to the spread of LPG</p><p><strong>⚙️ LDO</strong> consumption, once used in small industries and some farm machinery, is declining due to cleaner fuel alternatives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OVWkYpffY3U6DIFB9KUyiQ.png" /></figure><p><strong>🧪 Naptha</strong> usage is decreasing in the petrochemical sector, replaced by natural gas/LPG due to energy diversification and environmental policies</p><p><strong>🔥 FO &amp; LSHS</strong> use is declining, particularly in energy-intensive sectors like cement and steel, due to environmental regulations</p><p><strong>🧱 Petroleum Coke (Petcoke)</strong>, though widely used in India (especially in cement), is facing restrictions due to environmental concerns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*K1plrU3Ltln5SALNE6zIsw.png" /></figure><h3>Final Thoughts</h3><p>All these findings reveal the dynamic nature of petroleum product consumption in India. While dependency on products like HSD remains high, overall consumption is shaped by policy shifts, macroeconomic trends, environmental impacts, and technological developments. Monthly data fluctuations indicate seasonal patterns or the influence of short-term factors in some product categories.</p><h3>Forecast Modeling with Deep Learning LSTM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*H5Ts-LEvbsAtCLjzthI-HQ.png" /><figcaption>Prediction model codes</figcaption></figure><p>Lastly, we convert the data into a time series to build a simple Deep Learning LSTM forecasting model. Due to the limited data, we apply <strong>data augmentation</strong> by adding noise, then normalize and reshape the data to fit the LSTM model. We train the model and measure accuracy using <strong>r² score</strong>, which is <strong>0.3947</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tLLDEj8-WzxL7LAYCqZzg.png" /><figcaption><strong>Graph 3 — Comparison of model estimated values ​​with real values <em>(Source for the codes : </em></strong><a href="https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb"><strong><em>https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb</em></strong></a><strong><em>)</em></strong></figcaption></figure><p>Model performance can be improved by trying different parameters, models or data preprocessing methods; the estimation accuracy rate can be increased by increasing the amount of data. Instead of increasing the amount of data synthetically, it can be increased by adding the actual amounts of data. However, this article aims to present a simple estimation model example.</p><h4>To see all coding details:</h4><p><a href="https://github.com/nrdnay/India_Petroleum_Consumption/blob/main/Petroleum_Consuption_India.ipynb">India_Petroleum_Consumption/Petroleum_Consuption_India.ipynb at main · nrdnay/India_Petroleum_Consumption</a></p><p><strong>Monthly Consumption Trend Graphs Based on Other Products (Data Visualization)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ECi5mnVQHHoispTVzFi0gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IzS3uw_3MBPb4Z17z9qUeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Krx8Iov_abLbkFf-96vt_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0NzDQ9d8juhMkPAvd2w_-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7KIzVFiYQ5laWz8X1sCTMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OjInPiSm0WqpHy-7BeLPnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*r-q4-YLRs_NQgTfko24u4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JRW-TCIwmCeuBrPkji9o6w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b226297419c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-random-nerdiness-collective/indias-energy-pulse-shifting-trends-in-petroleum-products-and-the-power-of-data-science-9b226297419c">India’s Energy Pulse: Shifting Trends in Petroleum Products and the Power of Data Science</a> was originally published in <a href="https://medium.com/the-random-nerdiness-collective">The Creative Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>