<?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 Alper Demirel on Medium]]></title>
        <description><![CDATA[Stories by Alper Demirel on Medium]]></description>
        <link>https://medium.com/@alperdemirel?source=rss-d468c57b14db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xGnYq2W7Yy1UAUCrO9-INQ.jpeg</url>
            <title>Stories by Alper Demirel on Medium</title>
            <link>https://medium.com/@alperdemirel?source=rss-d468c57b14db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 19:51:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alperdemirel/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[Running SQL Queries on Pandas DataFrames: A Performance Comparison]]></title>
            <link>https://medium.com/insiderengineering/running-sql-queries-on-pandas-dataframes-a-performance-comparison-3b1f40a66157?source=rss-d468c57b14db------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b1f40a66157</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Alper Demirel]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 07:01:50 GMT</pubDate>
            <atom:updated>2025-07-28T07:01:50.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qL3Vqzz_3SH9gu-aHJBiUA.png" /><figcaption>Generated with AI</figcaption></figure><p>In a recent project at <a href="https://useinsider.com/"><strong>Insider</strong></a>, we needed an efficient way to run <strong>SQL</strong> <strong>queries</strong> directly on <strong>Pandas DataFrames. </strong>We conducted a benchmark study to compare popular libraries in the <strong>Python</strong> ecosystem and identify the most suitable technology for our needs. Using datasets of different sizes and queries of varying complexity, we evaluated these libraries across multiple dimensions, including <strong>execution speed</strong>, <strong>memory efficiency</strong>, and <strong>reliability</strong>.</p><p>In this post, we share our findings and insights to help others facing similar challenges.</p><h3>Used Technologies</h3><p>Here’s a quick overview of the libraries included in our benchmark:</p><ol><li><a href="https://www.sqlalchemy.org/"><strong>SQLAlchemy</strong></a>: A versatile SQL toolkit and ORM (Object Relational Mapper) with broad database support.</li><li><a href="https://duckdb.org/"><strong>DuckDB</strong></a>:<strong> </strong>An in-memory, column-oriented database management system tailored for OLAP (Online Analytical Processing) use cases.</li><li><a href="https://www.sqlite.org/"><strong>SQLite</strong></a>: A lightweight and transactional SQL database engine requiring minimal configuration and including built-in Python support.</li><li><a href="https://pypi.org/project/pandasql/"><strong>Pandasql</strong></a>: A simple library that enables SQL queries on Pandas DataFrames, combining the strengths of Pandas and SQL.</li><li><a href="https://pola.rs/"><strong>Polars</strong></a>: A high-performance DataFrames library with SQL capabilities, optimized for parallel processing and lazy evaluation.</li></ol><h3>Benchmark Methodology</h3><h4>1. Evaluation Metrics</h4><p>Our benchmarks focused on several key performance indicators:</p><ul><li><strong>Query Execution Time (seconds)</strong>: The duration is taken to execute a SQL query from start to finish.</li><li><strong>Cold Start Time (seconds)</strong>: The total time required for initial setup and execution when starting from scratch.</li><li><strong>Memory Usage (MB)</strong>: The memory footprint observed during the query execution.</li><li><strong>SQL Compatibility</strong>: The frequency of query failures due to syntax or compatibility issues.</li><li><strong>Ease of Use: </strong>The simplicity of integrating the library into a Python workflow.</li></ul><h4>2. Used Datasets and Queries</h4><p>We evaluated the metrics using datasets of various sizes and configurations, including both single and combined <strong>Pandas DataFrames</strong>. The datasets and queries were generated using <strong>LLMs</strong> and supplemented with a <strong>Kaggle</strong> dataset, ensuring a diverse mix of synthetic and real-world data.</p><ul><li><strong>Data Sizes</strong><br>- <strong>Small Scale</strong>: 1,000 and 10,000 rows<br>- <strong>Medium Scale</strong>: 100,000 and 270,000 rows<br>- <strong>Large Scale</strong>: 1,000,000 rows</li><li><strong>Query Types</strong><br>- <strong>Simple Operations</strong>: Basic filters, sorts, and aggregations with a single dataset.<br>- <strong>Complex Operations</strong>: Joins, subqueries, CTEs, and window functions with single and combined datasets.</li></ul><h3>Benchmark Results</h3><h4>1. Speed — Query Execution Time and Cold Start Time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNK7EzLgwzemg90-a51fFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBv12PgYqtZw2rLI45mD2A.png" /></figure><p>The above graphs show the average query execution time for each technology across different data sizes. Our observations:</p><ul><li><strong>DuckDB</strong> and <strong>Polars</strong> consistently outperform other technologies, especially as data size increases. They demonstrated minimal performance degradation, maintaining consistent low latency for both simple and complex queries, even with data scaled to 1M rows.</li><li><strong>SQLite</strong> performs well for smaller datasets but starts to lag for larger ones.</li><li><strong>SQLAlchemy</strong> and <strong>Pandasql</strong> show similar performance patterns, with both struggling more as data size grows. These libraries are the slowest.</li><li>All libraries perform comparably well for small data sizes.</li></ul><p>We also analyzed the cold start times of these technologies. The cold start time reflects the initial overhead required to set up the query environment before execution, particularly relevant for technologies with a significant initialization phase. All technologies exhibit fast initialization times, with no notable differences, highlighting that cold start time is not a distinguishing factor in their performance.</p><h4>2. Memory Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvNW0q7j4LISE5N1_crZjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dyocy2pGyzrsyKu9-Xl7tg.png" /></figure><p>Memory usage across all technologies was largely consistent, with only slight variations. On average, <strong>Polars</strong> showed slightly higher memory usage, while <strong>SQLAlchemy</strong> had the lowest. However, these differences are marginal and unlikely to significantly influence the choice of technology.</p><p>Additionally, memory usage scales predictably with increasing data size across all technologies. The line chart demonstrates that the growth in memory usage is linear and uniform, indicating efficient memory handling by all technologies for larger datasets. This suggests that memory usage is not a critical differentiator when selecting technology from the evaluated options.</p><h4>3. SQL Compatibility</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ato6wWxfVvoJvO7cDv_39A.png" /></figure><p>SQL compatibility varied significantly across the libraries. <strong>Polars</strong> encountered more exceptions, potentially due to compatibility issues with specific SQL operations. Conversely, <strong>DuckDB</strong>, <strong>SQLite</strong>, <strong>SQLAlchemy</strong>, and <strong>Pandasql</strong> demonstrated better robustness, handling a broader range of queries without issues.</p><p>These results suggest that <strong>Polars</strong> may exhibit some unexpected behavior in our specific use case involving SQL queries. While this indicates some limitations for <strong>Polars</strong> in this scenario, it may perform better in workflows outside SQL query execution. On the other hand, the remaining technologies demonstrated more consistent performance in executing SQL queries, making them reliable options for this particular scenario.</p><h4>4. Ease of Use</h4><p>All evaluated libraries offer straightforward integration into <strong>Python</strong> workflows. Their intuitive structures make executing SQL queries seamless, requiring minimal setup or configuration.</p><p>Here’s a simple example of running a SQL query using <strong>DuckDB</strong>:</p><pre>import duckdb<br>import pandas as pd<br><br>data = {&#39;name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;], <br>        &#39;sales&#39;: [100, 200, 150], <br>        &#39;region&#39;: [&#39;East&#39;, &#39;West&#39;, &#39;East&#39;]}<br>df = pd.DataFrame(data)<br><br>query = &quot;SELECT region, SUM(sales) FROM df GROUP BY region&quot;<br>result = duckdb.query(query).df()<br><br>print(result)</pre><p>This code demonstrates the simplicity of using <strong>DuckDB</strong> to query a <strong>Pandas DataFrame</strong> with just a few lines of code. Similar simplicity can be found in other libraries we evaluated.</p><h3>Polars vs DuckDB</h3><p>When comparing <strong>Polars</strong> and <strong>DuckDB</strong>, it is crucial to consider their unique strengths and intended use cases rather than relying solely on benchmark results. For instance, choosing the fastest runner for a swimming race — like a chimpanzee against a fish — can lead to misleading conclusions when the context is overlooked.</p><p><strong>DuckDB</strong> is an in-memory, columnar database management system optimized for OLAP (Online Analytical Processing) scenarios. It offers extensive SQL support, including advanced features like window functions, complex joins, and Common Table Expressions (CTEs). Designed specifically for SQL-heavy workflows, <strong>DuckDB</strong> aligns well with projects like ours, where running SQL queries on Pandas DataFrames is a primary requirement.</p><p><strong>Polars</strong>, on the other hand, is a high-performance DataFrame library optimized for data manipulation and computation. Built with Rust, it leverages parallel processing and lazy evaluation for exceptional speed. Although it supports SQL queries, its SQL features are less comprehensive compared to <strong>DuckDB</strong>. <strong>Polars</strong> is better suited for workflows centered around data transformations rather than extensive SQL operations.</p><p>Ultimately, this comparison highlights the importance of aligning tools with specific project requirements. <strong>DuckDB</strong> and <strong>Polars</strong> cater to distinct needs: SQL-heavy analytics versus raw data manipulation performance.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*_CiG3HVQmLRoGBdqkxm0MQ.png" /></figure><p>Our benchmarks highlight <strong>DuckDB</strong> as the most well-rounded option for executing <strong>SQL queries</strong> on <strong>Pandas DataFrames</strong>, excelling in performance, ease of use, and functionality. <strong>SQLite</strong> remains a solid choice for small-scale, lightweight operations. While <strong>Polars</strong> offers remarkable speed, its SQL limitations warrant careful consideration. For simpler workflows where speed is less critical, <strong>Pandasql</strong> and <strong>SQLAlchemy</strong> provide accessible and convenient alternatives.</p><p>We’re leaning towards adopting <strong>DuckDB</strong> as our primary solution for our project. However, the choice may vary depending on specific project requirements, such as data size, query complexity, and required SQL features.</p><p>We hope this benchmark study offers valuable insights to those addressing similar challenges in the Python ecosystem. Feel free to share your experiences and thoughts in the comments.</p><p>Stay updated with our latest engineering insights and stories — follow us on the <a href="https://medium.com/insiderengineering">Insider Engineering Blog</a> for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b1f40a66157" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insiderengineering/running-sql-queries-on-pandas-dataframes-a-performance-comparison-3b1f40a66157">Running SQL Queries on Pandas DataFrames: A Performance Comparison</a> was originally published in <a href="https://medium.com/insiderengineering">Insider One Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Makine Öğrenmesi Modelinizi Kaydetmenin 3 Yolu]]></title>
            <link>https://alperdemirel.medium.com/makine-%C3%B6%C4%9Frenmesi-modelinizi-kaydetmenin-3-yolu-dc970298c45a?source=rss-d468c57b14db------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc970298c45a</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Alper Demirel]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 18:46:33 GMT</pubDate>
            <atom:updated>2021-08-03T08:05:31.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PpU03aViQ-ogkCGBExODiQ.png" /><figcaption>Kaynak: <a href="https://skrift.io/">https://skrift.io</a></figcaption></figure><p>Makine öğrenmesi projelerinde hedeflerden bir tanesi, problem ve veri için en doğru modeli bulmaktır. Bu hedefe yinelemeli bir şekilde farklı modeller denenerek ulaşılmaya çalışılır. Yapılan çalışmalarda elde edilen modellerden iyi olduğu düşünülenleri yeni bir veri üzerinde test etmek, canlıda kullanmak veya başka bir amaç için kaydetmek gerekir. Ayrıca projelerde kullanılan verilerin büyüklüğünden eğitim süreleri uzun sürmektedir, aynı eğitimi her defasında tekrarlamamak adına model daha sonrası için saklanabilmektedir. Oluşturulan modeli kaydetmek için farklı kütüphaneler farklı kaydetme seçenekleri sunmaktadır. Ben bu yazıda sizlere Python’da Scikit-Learn kütüphanesi ile oluşturulmuş modelinizi kaydetmenin ve tekrar kullanmak için yüklemenin 3 farklı yolundan bahsedeceğim.</p><h3>1. JSON</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8J889IhbSanJQBe3FmoYA.png" /><figcaption>Kaynak: <a href="https://www.nylas.com/">https://www.nylas.com</a></figcaption></figure><p>JSON, günümüzde en çok tercih edilen veri saklama formatlarından bir tanesidir. Python’da JSON kütüphanesi yerleşik bir şekilde gelmektedir. Bu kütüphanenin birçok bileşeni ve kullanım durumları bulunmaktadır. Ancak ben bu yazıda sadece JSON kütüphanesini kullanarak Scikit-Learn modelinizi nasıl kaydedebileceğinize odaklanacağım. Bu kütüphane ile Scikit-Learn modelinizi kaydetmeniz için model parametrelerinizin erişilebilir ve sezgisel olması gerekmektedir. Yani modelinizin parametreleri gözle görülür olmak durumunda ve kaydetmek istediğiniz parametreler ile ilgili bilgiye rahatça ulaşabilmeniz beklenmektedir. Ayrıca verilerinizi modelinize beslemeden önce ön işleme adımlarınızı da kaydetmek isterseniz bu yöntem sizin için zor bir seçenek haline gelmektedir. Tüm bunlar sonucunda JSON kütüphanesinin doğrusal regresyon gibi basit modeller dışında çok uygun bir yöntem olmadığı ortaya çıkmaktadır.</p><p>Şimdi JSON’ı kullanarak bir modeli nasıl kaydedeceğinizi bir örnek ile anlatmaya çalışacağım. Örneğimiz bir regresyon problemi olup, Scikit-Learn’de yerleşik olarak gelen boston veri setini kullanarak bir ev fiyatı tahmini yapmayı hedefliyorum.</p><blockquote>Yazı amacının model kaydetme ve saklama ile ilgili yöntemlerin nasıl uygulandığı olduğu için diğer makine öğrenmesi adımları basit bir şekilde ele alınmıştır.</blockquote><p>İlk olarak örneğimiz için gerekli olan kütüphaneleri kodumuza aktararak başlayalım. Örnek problemimiz için gerekli olan veri seti<strong> load_boston</strong>’ı, veri setimizi eğitmek ve test etmek için <strong>train_test_split</strong>’i, doğrusal regresyon algoritmamız için <strong>LinearRegression</strong>’u ve model performansımızı ölçmek için <strong>r2_score</strong>’u Scikit-Learn kütüphanesini kullanarak kodumuza aktardık. Model olarak yukarıda da bahsettiğim üzere açıklanabilirliği ve parametrelerinin okunabilirliği nedeniyle doğrusal regresyon kullandım.</p><pre>import json</pre><pre>import numpy as np <strong># Matematiksel operasyonlar için</strong><br>from pathlib import Path <strong># Otomatik klasör oluşturmak için</strong></pre><pre>from sklearn.linear_model import LinearRegression </pre><pre>from sklearn.datasets import load_boston<br>from sklearn.model_selection import train_test_split <br>from sklearn.metrics import r2_score </pre><p>Daha sonra modelimizi eğitip hazırlıyoruz. Önce özelliklerimizi <strong>X</strong> değişkenine, hedef değerlerimizi de <strong>y </strong>değişkenine atayarak başlıyoruz. Sonrasında <strong>X </strong>ve <strong>y </strong>değişkenlerini eğitim ve test verisi olarak ayırıyoruz. Son olarak model performansımızı test verisinde test ederek ekrana yazdırıyoruz.</p><pre>X, y = load_boston(return_X_y=<strong>True</strong>)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=28)</pre><pre>linear_model = LinearRegression().fit(X_train, y_train)<br>y_pred_test = linear_model.predict(X_test)<br>print(&quot;Test score: &quot;, r2_score(y_test, y_pred_test))</pre><pre><strong>Output: Test score:  0.682129695744708</strong></pre><p>Şimdi de modelin kesişim ve katsayı değerlerini ekrana yazdırarak devam ediyoruz. Burada görüldüğü üzere modelin parametre bilgilerine çok rahat bir şekilde ulaşabiliyoruz.</p><pre>print(&quot;Coefficient parameters:&quot;, linear_model.coef_)<br>print(&quot;\nIntercept: &quot;,linear_model.intercept_)</pre><pre><strong>Output:<br>Coefficient parameters: [-9.35992075e-02  3.92793258e-02  1.92925522e-02  2.50621955e+00<br> -1.77097508e+01  4.32898476e+00  3.29173281e-03 -1.24431560e+00<br>  3.02390932e-01 -1.15848174e-02 -9.81842087e-01  1.00781696e-02<br> -4.77152997e-01]<br><br>Intercept:  31.67177332226347</strong></pre><p>Daha sonra parametreleri saklayabileceğim bir sözlük oluşturdum. Sonra katsayı ve kesişim değerlerini bir listeye çevirerek sözlüğe aktarıyorum. Sonrasında parametrelerimizi JSON kütüphanesinin <strong>dump </strong>fonksiyonunu kullanarak JSON formatına dönüştürüp bir değişkene atıyorum. Sonra dönüştürülmüş formatın nasıl göründüğünü görmek için nesneyi ekrana yazdırıyorum.</p><pre>model_param = {}</pre><pre>model_param[&#39;coef&#39;] = list(linear_model.coef_)<br>model_param[&#39;intercept&#39;] = linear_model.intercept_.tolist()</pre><pre>json_txt = json.dumps(model_param, indent=4)<br>print(json_txt)</pre><pre><strong>Output:</strong></pre><pre><strong>{<br>    &quot;coef&quot;: [<br>        -0.0935992074979253,<br>        0.03927932575945889,<br>        0.01929255223927326,<br>        2.506219545038105,<br>        -17.70975084096846,<br>        4.328984755094672,<br>        0.0032917328144949935,<br>        -1.2443156002329776,<br>        0.3023909315161962,<br>        -0.011584817400845417,<br>        -0.9818420869612504,<br>        0.010078169637325596,<br>        -0.47715299685209916<br>    ],<br>    &quot;intercept&quot;: 31.67177332226347</strong></pre><p>Sonrasında modelimizi kaydetmek için “<em>models”</em> adında bir klasör oluşturdum. Sonrasında parametrelerimizi tuttuğumuz <strong>json_txt</strong> değişkenini bu klasörün altında yeni oluşturmuş olduğum dosyanın içine yazıp kaydediyorum. Artık model parametrelerimiz daha sonra kullanılmak üzere hazır duruma gelmiş oldu.</p><pre>Path(&quot;models&quot;).mkdir(parents=True, exist_ok=True)<br>with open(&#39;models/regressor_param.txt&#39;, &#39;w&#39;) as file:<br>    <br>    file.write(json_txt)</pre><p>Şimdi kaydetmiş olduğumuz parametreleri kodumuza aktarmak için bulunduğu dosyayı okuyup JSON kütüphanesinin <strong>load</strong> fonksiyonu aracılığıyla bir değişkene atıyorum.</p><pre>with open(&#39;models/regressor_param.txt&#39;, &#39;r&#39;) as file:<br>    <br>    json_text=json.load(file)</pre><p>Son olarak yeni bir doğrusal regresyon modeli oluşturup bu modele eski modelin katsayı ve kesişim değerlerini atıyorum. Son olarak test verilerimle yüklediğim modeli test ediyorum. Ve sonuç olarak aynı test veriler ile tahmin yaptığım için yine aynı sonucu alıyoruz. JSON yöntemi ile model parametrelerinizi kaydedip daha sonra kullanmak işte bu kadar :) Hadi şimdi Pickle’da bu işlerin nasıl yürütüldüğüne bakalım.</p><pre>json_model = LinearRegression()</pre><pre>json_model.coef_ = np.array(json_text[&#39;coef&#39;])<br>json_model.intercept_ = np.array(json_text[&#39;intercept&#39;])</pre><pre>y_pred_test = json_model.predict(X_test)</pre><pre>print(&quot;Test score: &quot;, r2_score(y_test, y_pred_test))</pre><pre><strong>Output: Test score:  0.682129695744708</strong></pre><h3>2. Pickle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Oms5Jktao5Hb5XWBX4rUAA.gif" /><figcaption>Kaynak: <a href="https://dribbble.com/">https://dribbble.com</a></figcaption></figure><p>Pickle, Python’da yerleşik olarak gelen standart bir kütüphanedir. Pickle kullanarak herhangi bir Python nesnesini kaydedebilir ve tekrar kullanabilirsiniz. Scikit-Learn modelinizi deploy etmek veya daha sonra gelen test verileri ile denemek isterseniz model parametreleriniz için Pickle kullanmak çok yaygın bir seçenektir.</p><p>Yukarıda JSON yöntemini anlatırken tüm yöntemlerimiz için ortak olan kütüphaneleri içeri aktarmıştım. Şimdi burada sadece Pickle kütüphanesini içeri aktarmakla başlıyorum. Sonra eğer yoksa <em>“models”</em> adında klasör oluşturup bu klasörün içine Pickle’n <strong>dump </strong>fonksiyonunu kullanarak “<em>.pkl”</em> uzantılı olacak şekilde kaydediyorum ve hepsi bu kadar :) Şimdi bir sonraki adımda kaydetmiş olduğumuz modeli nasıl kullanabileceğimize bakalım.</p><pre>import pickle</pre><pre>Path(&quot;models&quot;).mkdir(parents=<strong>True</strong>, exist_ok=<strong>True</strong>)<br>pickle.dump(linear_model, open(&#39;models/model.pkl&#39;, &#39;wb&#39;))</pre><p>Kaydetmiş olduğumuz modeli Pickle’n <strong>load </strong>fonksiyonunu kullanarak içeri aktarıyorum ve modeli <strong>pickle_model </strong>adında bir değişkene atıyorum. Ve son olarak modeli JSON yönteminde yapmış olduğumuz gibi test verisi ile tahminler yapıyorum. Modelimiz yine ilk ürettiği sonucu döndürdü ve başarılı oldu. Pickle’daki işler bu kadar, hadi son olarak Joblib ile bu yollardan nasıl geçildiğine bakalım.</p><pre>pickle_model = pickle.load(open(&#39;models/model.pkl&#39;, &#39;rb&#39;))</pre><pre>y_pred_test = pickle_model.predict(X_test)</pre><pre>print(&quot;Test score: &quot;, r2_score(y_test, y_pred_test))</pre><pre><strong>Output: Test score:  0.682129695744708</strong></pre><h3>3. Joblib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*qggh8qqEzzA2W6lcilA89g.png" /><figcaption>Kaynak: <a href="https://joblib.readthedocs.io/">https://joblib.readthedocs.io/</a></figcaption></figure><p>Son yöntem olan Joblib’e gelecek olursak, Joblib genellikle Python fonksiyonlarınızı bir pipeline içerisinde belirli bir sırayla çalıştırmak için çeşitli seçenekler sunan bir kütüphanedir. Bu durum uzun süren işlemlerin hızlanmasına yardımcı olmaktadır. Ayrıca Joblib, Pickle gibi Python nesnelerinizi kaydetmeniz için güzel seçenekler sunmaktadır. Joblib’in Pickle’dan en büyük farkı büyük boyutlu NumPy arraylerini depolamakta daha hızlı ve etkili olmasıdır. Scikit-Learn’de model parametreleri genelde NumPy arraylerinde tutulmaktadır. Bu sebeple büyük boyutlu verilerinizde Joblib’i tercih etmeniz daha doğru olacaktır.</p><p>İlk olarak Python’da yerleşik olarak gelmediği için Joblib kütüphanesini yükleyerek başlayalım. Kütüphaneyi isterseniz kendi ortamınıza isterseniz Anaconda ortamına isterseniz farklı bir ortama indirebilirsiniz. Eğer jupyter not defterinizde kütüphaneyi indirmek isterseniz aşağıdaki kodun başına ünlem eklemeniz yeterli olacaktır.</p><pre>pip install joblib</pre><p>İkinci olarak Joblib için gerekli kütüphaneleri içere aktarıyorum. JSON yöntemi ile farkını anlamak için burada basit bir modelden farklı olarak biraz daha karmaşık bir model olan ağaç tabanlı gradient boosting algoritmasını kullanacağım. İşlerin Pickle’da olduğu gibi ne kadar basit bir şekilde halledildiğini göreceksiniz.</p><pre>import joblib</pre><pre>from sklearn.ensemble import GradientBoostingRegressor</pre><p>Gerekli kütüphaneleri koda aktardıktan sonra önceden ayırmış olduğum eğitim verileri ile modeli eğitiyorum. Sonrasında test verisi ile tahminlerimi alıp modelin performansını ölçüp ekrana yazdırdım. Doğrusal modele göre bu modelin daha iyi bir sonuç ürettiğini görüyoruz. En son modeli kaydedip içe aktardıktan sonra yine birebir aynı sonucu almayı umuyoruz.</p><pre>tree_model = GradientBoostingRegressor().fit(X_train, y_train)<br>y_pred_test = tree_model.predict(X_test)<br>print(&quot;Test score: &quot;, r2_score(y_test, y_pred_test))</pre><pre><strong>Output: Test score:  0.8180312663162715</strong></pre><p>Bu aşamada önce yukarıda diğer yöntemlerde yaptığım gibi önce “<em>models”</em> adında bir klasör yoksa onu oluşturuyorum. Sonra modeli kaydedeceğim yolu bir değişkene atıyorum. Daha sonra, Joblib kütüphanesinin <strong>dump </strong>fonksiyonunu kullanarak <em>“.joblib”</em> uzantısı ile modeli kaydediyorum. Gördüğünüz üzere işlemler Pickle ile hemen hemen aynı!</p><pre>Path(&quot;models&quot;).mkdir(parents=<strong>True</strong>, exist_ok=<strong>True</strong>)</pre><pre>filename = &#39;models/model.joblib&#39; <br>joblib.dump(tree_model, filename)</pre><pre><strong>Output: [&#39;models/model.joblib&#39;]</strong></pre><p>Son olarak kaydettiğim modeli Joblib’in <strong>load </strong>fonksiyonunu kullanarak <em>“.joblib”</em> uzantılı oluşturduğum dosyadan bir değişkene atıyorum. Sonrasında modeli yine aynı test verisi ile test ederek çıktı olarak aynı sonucu aldığımızı görüyoruz ve son yötemimizi de burada noktalıyoruz.</p><pre>joblib_model = joblib.load(filename)</pre><pre>y_pred_test = joblib_model.predict(X_test)</pre><pre>print(&quot;Test score: &quot;, r2_score(y_test, y_pred_test))</pre><pre><strong>Output: Test score:  0.8180312663162715</strong></pre><h3>Özet</h3><p>Sonuç olarak Scikit-Learn’de modelinizi kaydetmenin üç yönteminden bahsettik. Bu üç yöntemin kendine has özellikleri ve kullanım durumları bulunmaktadır. İlk olarak JSON’ı daha çok basit modellerde kullanmamız gerektiğini ve parametrelerinin okunabilir olmasını gerektiğini dile getirdik. İkinci olarak Pickle ile her Python nesnesini kaydedebileceğinizi ve en çok tercih edilen yöntemlerden biri olduğunu, sonuncu yöntem olan Joblib’in ise daha çok pipeline (sıralı işlemler) oluşturmak için kullanıldığını ve Pickle ile benzer olduğunu fakat büyük veri setlerinde Pickle’dan daha performanslı olacağını ele aldık. Ve son.</p><p>Umarım bu yazının size faydası olur ve bu yöntemlerden herhangi birini projelerinizde kullanırsınız. Ayrıca bu yöntemler haricinde sizin kullandığınız farklı yöntemler varsa yorumlarda belirtmekten lütfen çekinmeyin. Aynı şekilde eksik veya hatalı gördüğünüz yerler için de geri dönüşlerinizi bekliyorum. Okuduğunuz için çok teşekkür ederim. Bir sonraki yazımda görüşmek dileğiyle, bol sağlıklı ve öğrenmeli günler!</p><p><strong>Yöntemlere ait kodlara bu bağlantıdan ulaşabilirsiniz:</strong> <a href="https://github.com/alperdem1rel/serializing-deserializing-demo">https://github.com/alperdem1rel/serializing-deserializing-demo</a></p><h4>KAYNAKLAR</h4><ul><li><a href="https://app.pluralsight.com/library/courses/deploying-machine-learning-solutions/table-of-contents">https://www.pluralsight.com/</a></li><li><a href="https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/">https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/</a></li><li><a href="https://www.geeksforgeeks.org/saving-a-machine-learning-model/">https://www.geeksforgeeks.org/saving-a-machine-learning-model/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc970298c45a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Veri Bilimi ve ALTIn Kenarları]]></title>
            <link>https://medium.com/deep-learning-turkiye/veri-bilimi-ve-altin-kenarlar%C4%B1-e1ec4fdce728?source=rss-d468c57b14db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ec4fdce728</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Alper Demirel]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 18:22:28 GMT</pubDate>
            <atom:updated>2021-03-24T16:47:42.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Veri Bilimi ve ALTIn Kenarları" src="https://cdn-images-1.medium.com/max/769/1*cWDHQy3HqTvgNArqDtj81g.png" /></figure><p>Bu yazımda sizlere genel olarak veri biliminden ve <strong>ALTI</strong>n kenarlarından bahsedeceğim. Öncelikle “<strong>Veri</strong>” ve “<strong>Veri Bilimi</strong>” hakkında bildiklerimi paylaşarak başlamak istiyorum.</p><blockquote><strong>Veri</strong> (<a href="https://tr.wikipedia.org/wiki/%C4%B0ng.">İng.</a> ve <a href="https://tr.wikipedia.org/wiki/Latince">Lat.</a> datum; <em>ç.</em> data), ham (işlenmemiş) gerçek <a href="https://tr.wikipedia.org/wiki/Enformasyon">enformasyon</a> parçacığına verilen addır. Veriler <a href="https://tr.wikipedia.org/wiki/%C3%96l%C3%A7%C3%BCm">ölçüm</a>, <a href="https://tr.wikipedia.org/w/index.php?title=Say%C4%B1m&amp;action=edit&amp;redlink=1">sayım</a>, <a href="https://tr.wikipedia.org/wiki/Deney">deney</a>, <a href="https://tr.wikipedia.org/wiki/G%C3%B6zlem">gözlem</a> ya da <a href="https://tr.wikipedia.org/wiki/Ara%C5%9Ft%C4%B1rma">araştırma</a> yolu ile elde edilmektedir.</blockquote><p><strong>Veri</strong>; 21. yüzyılın petrolü ve gelecekteki başarının anahtarı olarak görülmektedir. Veriler, günümüzde çoğu yapay zeka uygulamalarında merkezi ve kritik rol oynamaktadır. Bu kavram artık hayatımızın vazgeçilmez bir parçasıdır. Bu madeni çıkarmayı, kullanmayı ve bu madenden benzin, asfalt, LPG gibi değerler üretmeyi öğrenmemiz gerekmektedir. Yani bu dönüşüme kendimizi hazırlamalıyız. Üstümüze üstümüze gelen değişime veya dönüşüme ayak uydurmamız gerektiğini güzel aktaran sevdiğim bir sözü sizlerle paylaşmak istiyorum.</p><blockquote><strong>“Dalgaları durduramazsın belki, ama sörf yapmayı öğrenebilirsin.”</strong><br> — Jon Kabat-Zinn, Massachusetts Üniversitesi Tıp Profesörü</blockquote><p><strong>Veri bilimi</strong> ise 10 insana “Veri Bilimi Nedir?” diye sorup 10 farklı cevap aldığımız bir alandır. Benim bu alan için en sevdiğim tanım ise şudur:</p><blockquote>Verileri analiz etme, yapılandırma, temizleme ve işleme aynı zamanda değerlendirme ve yorumlama sanatına “<strong>Veri Bilimi”</strong> denmektedir.</blockquote><p>Ayrıca bu alanı anlatan ve en çok alıntı yapılan diyagramlardan bir tanesi, veri biliminin <strong><em>bilgisayar bilimi yetenekleri</em></strong>, <strong><em>matematik ve istatistik bilgisi</em></strong><em> </em>ve <strong><em>belirli bir alanda uzmanlık bilgisi</em></strong>nin kesişimi olduğunu söyleyen Veri Bilimci Drew Conway tarafından öne sürülmüştür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsMvgc76ubKQpWSXwgF21w.png" /><figcaption>Kaynak: <a href="http://drewconway.com/zia/2013/3/26/the-data-science-venn-diagram">Drew Conway, Veri Bilimi Venn Diyagramı</a></figcaption></figure><p>Veri ve onun bizlere sunduğu teknolojik gelişmelere farklı bir boyut kazandıran veri bilimi alanına yukarıda sizlere kısaca bahsettim. Şimdi ise veri bilimi alanının <strong>ALTI</strong>n kenarları diye adlandırdığım parçaları basit tanımlamalarla aktarmak istiyorum.</p><h4>1. Veri Keşfi ve Hazırlanması</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JMeZ8_19iGy6DujE4x5TFQ.gif" /><figcaption>Kaynak: <a href="https://wiki.smu.edu.sg/1718t1isss608g1/img_auth.php/b/b8/Data_prep.gif">https://wiki.smu.edu.sg/1718t1isss608g1/img_auth.php/b/b8/Data_prep.gif</a></figcaption></figure><p>Bu kenar, elimizdeki kirli olan veriyi temizlemeyi ve veri içerisinde yapılacak analiz için manipülasyon işlemleri yapmamızı içermektedir. Veriye dayalı olarak yürütülen herhangi bir proje, temizlik esnasında dikkatli şekilde ele almayı ve tanımlamayı gerektirmektedir. Bu işlemleri gerçekleştirmek için genellikle farklı programlama dillerinin (Python, R, vs.) farklı ve geniş matematik araçları içeren kütüphaneleri bulunmaktadır. Bazı veri bilimciler, veri bilimine ayrılan çabanın %80&#39;inin verinin araştırılmasına ve kirli verilerle uğraşma ile geçirilmesi gerektiğini ve bu sayede verinin daha fazla kullanıma hazır hale getirilebileceğini söylemektedir.</p><h4>2. Veri Gösterimi ve Dönüşümü</h4><p>Diğer bir kenarımız olan bu uzmanlık ise veriyi temsil etmenin farklı biçimlerine (metin verileri, grafik tabanlı veriler, vs.) göz atmaktadır. Veri bilimciler kariyerleri boyunca birçok veri kaynaklarıyla çalışmaktadırlar. Bu kaynaklardaki çalışmalarında merkezi bir adımın, orijinal formatlarıyla verilen verileri yeni ve daha açıklayıcı bir biçime yeniden yapılandıran uygun bir dönüşümden geçmesi gerektiği düşünülmektedir.</p><h4>3. Verilerle Hesaplama</h4><p>Üçüncü kenar ise veri ile hesaplamalar yapmaktır. David Donoho yazmış olduğu “<a href="https://courses.csail.mit.edu/18.337/2015/docs/50YearsDataScience.pdf"><strong>50 years of Data Science</strong></a>” adlı makalesinde özellikle R ve Python programlama dillerinin verilerle hesaplama yapmak için temel olduğundan bahsetmiştir. Veri bilimcilerin bu dilleri verimli bir şekilde kullanmak için yeni ifadeleri güncel tutmaları ve hesaplama verimliliği ile ilgili daha derin sorunları anlamaları istenmektedir. Özellikle son yıllarda çok popüler olan bulut bilişim hesaplama verimliliğinin artırılmasında çok güçlü bir bileşen haline gelmiştir. İhtiyacımız olan tüm işlevselliği uygulamak için tek bir programlama dili kullanılması gerekilen kurumsal yazılım projeleri aksine, modern veri bilimi projeleri birçok programlama dili ve hesaplama paradigmasını kapsayabilmektedir. Bu uzmanlıkta farklı işler için doğru aracı ne zaman kullanacağımızı bilmek önemli bir özellik olarak gösterilmektedir.</p><h4>4. Veri Modelleme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRAF9Y5tCwb1uvpoEiMT9A.gif" /><figcaption>Kaynak: <a href="https://www.ml.cmu.edu/">https://www.ml.cmu.edu/</a></figcaption></figure><p>Dördüncü kenarımız ise verilerin çeşitli işlemler yapmak için uygun modellere sokulma işlemidir. Bu alan oldukça büyük bir alandır ve günümüzde özellikle “<strong>Makine Öğrenmesi</strong>” ve onun alt disiplini olan “<strong>Derin Öğrenme</strong>” algoritmalarıyla hayatımızı kolaylaştıran oldukça güçlü sonuçlar ve değerler üretilmektedir.</p><blockquote>“Veri bilimi, deney, modelleme ve hesaplamaya ek olarak bilimsel keşif için dördüncü bir yaklaşım haline geldi.”<br>- Martha E. Pollack, Bilgisayar Bilimci</blockquote><h4>5. Veri Görselleştirme ve Sunumu</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReFMfRwtfs3B5Q4xDBaxzg.jpeg" /><figcaption>Kaynak: <a href="https://boostlabs.com/blog/10-types-of-data-visualization-tools/">https://boostlabs.com/blog/10-types-of-data-visualization-tools/</a></figcaption></figure><p>Görselleştirme kelimesi, tablolar, grafikler ve haritalar gibi 2D ve 3D görselleştirmeler ve etkileşimli ortamlar gibi kafamızda birçok gösterim şekline çağrışım yapmaktadır. Bu bölüm bize karmaşık ve büyük boyutlu verilerin görsel bir anlatım ile veriyi daha net kavramamıza olanak sağlamaktadır. Veriyi görselleştirip sunmamızın temel amaçlarından bazıları <em>veri ile ilgili </em><strong><em>soruları cevaplandırmak</em></strong>, <strong><em>karar vermek</em></strong>, <strong><em>görsel hesaplamalar yapmak</em></strong>, <strong><em>model oluşturmak</em></strong> ve <strong><em>hikayeler anlatmak</em></strong> istemektir. Ayrıca görselleştirme yaparken dikkat etmemiz gereken bazı hususlar bulunmaktadır. Bunlar <em>s</em><strong><em>adelik ön planda olmalı</em></strong>, <strong><em>veri ile bir anlam veya hikaye oluşturmaya odaklanmalı</em></strong> ve<strong><em> tasarım ile işlev arasında denge</em></strong> kurulmalıdır.</p><h4>6. Veri Bilimi Hakkında Bilim</h4><p>Bilim kelimesini belirli bir alanda kullanma hakkına sahip olabilmek için, sürekli gelişen, kanıta dayalı bir yaklaşıma sahip olunmasının gerekliliği söylenmektedir. Bu kapsamda sonuncu kenar olan ve yine David Donoho’nun “<a href="https://courses.csail.mit.edu/18.337/2015/docs/50YearsDataScience.pdf"><strong>50 years of Data Science</strong></a>” makalesinde söz ettiği bu bölüm veri biliminde neyin işe yarayıp neyin yaramadığını ve bu veri keşiflerinden nasıl yararlanılacağını anlamayı ve araştırmayı içermektedir.</p><p>Son olarak sizlere <strong>veri bilimi</strong> hakkındaki ülkemizdeki gözle görülür artış için bilgi vermek istemekteyim. Bu artan ilgiyi görmenin eğlenceli bir yolu “<a href="https://trends.google.com.tr/trends/?geo=TR"><strong>Google Trends</strong></a>” sitesine göz atmaktır. Google Trends, bizlere zaman içinde aratılan anahtar kelime bilgisini ve bu anahtar kelimenin belirli zaman aralıklarındaki değişimini göstermektedir. Veri Bilimi teriminin ülkemizde oldukça popüler ve büyük bir çıkışta olduğunu bu yöntem ile rahatça gözlemleyebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*NdL5SYo86G5ZcdUZMdYaQQ.png" /><figcaption>Kaynak: <a href="https://trends.google.com.tr/trends/explore?date=2013-09-29%202020-09-29&amp;geo=TR&amp;q=%2Fm%2F0jt3_q3">Google Web Aramada aratılan “Veri Bilimi” alanının 2013–2020 yılları arası büyük değişimi</a></figcaption></figure><p>İkinci olarak ülkemizde yer alan Yeditepe, Sabancı, Koç, İTÜ, Bahçeşehir gibi üniversiteler son yıllarda popülaritesi artan “Veri Bilimi” alanı ile ilgili yüksek lisans programlarını duyurdular. Vermek istediğim son örnek ise ABD’de bulunan Michigan Üniversitesi 8 Eylül 2015&#39;te 35 yeni öğretim üyesini işe alarak bu alanla ilgili 100 milyon dolarlık bir “<a href="https://news.umich.edu/u-michigan-launches-100-million-data-science-initiative/"><strong>Veri Bilimi Girişimi</strong></a>”ni duyurmuştur.</p><p>Gördüğünüz gibi veri bilimi yeni ve büyüyen bir olgudur. Sizde bu hızla artan alanla ilgilenmek, kendinizi geliştirmek veya bilgi edinmek istiyorsanız hiç zaman kaybetmeden internet aleminde yer alan tonlarca kurs, makale ve diğer bütün kaynaklara göz atabilirsiniz.</p><p>Umarım yardımcı olmuştur, tekrar görüşmek dileğiyle!</p><blockquote>Veri Bilimi’nin <strong>ALTI</strong>n kenarları olarak bahsettiğim bölümler Stanford Üniversitesi İstatistik Profesörü David Donoho’nun 2015 yılında yazmış olduğu “<strong>50 years of Data Science</strong>” makalesinden referans alınarak yazılmıştır.</blockquote><h4>KAYNAKLAR</h4><ul><li><a href="https://courses.csail.mit.edu/18.337/2015/docs/50YearsDataScience.pdf"><strong>50 years of Data Science, David Donoho</strong></a></li><li><a href="https://www.coursera.org/programs/0d2aa567-9698-4b52-805a-9b6c25332ef3/browse?currentTab=CATALOG&amp;productId=RZ1S0B0MEeacvQ6cODzg5Q&amp;productType=course&amp;query=Introduction+to+Data+Science+in+Python&amp;showMiniModal=true"><strong>Introduction to Data Science in Python, University of Michigan</strong></a></li><li><a href="http://drewconway.com/zia/2013/3/26/the-data-science-venn-diagram"><strong>http://drewconway.com/zia/2013/3/26/the-data-science-venn-diagram</strong></a></li><li><a href="https://tr.wikipedia.org/wiki/Veri"><strong>https://tr.wikipedia.org/wiki/Veri</strong></a></li><li><a href="https://medium.com/@analiyzer/en-i%CC%87yi-veri-bilimi-y%C3%BCksek-lisans-ve-lisans-programlar%C4%B1-57a86b0884c6"><strong>https://medium.com/@analiyzer/en-i%CC%87yi-veri-bilimi-y%C3%BCksek-lisans-ve-lisans-programlar%C4%B1-57a86b0884c6</strong></a></li><li><a href="https://news.umich.edu/u-michigan-launches-100-million-data-science-initiative/"><strong>https://news.umich.edu/u-michigan-launches-100-million-data-science-initiative/</strong></a></li><li><a href="https://aibusinessschool.com/yapay-zekaya-ilk-adim/"><strong>https://aibusinessschool.com/yapay-zekaya-ilk-adim/</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ec4fdce728" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deep-learning-turkiye/veri-bilimi-ve-altin-kenarlar%C4%B1-e1ec4fdce728">Veri Bilimi ve ALTIn Kenarları</a> was originally published in <a href="https://medium.com/deep-learning-turkiye">Deep Learning Türkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>