<?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 Yusuf J Khan on Medium]]></title>
        <description><![CDATA[Stories by Yusuf J Khan on Medium]]></description>
        <link>https://medium.com/@yusuf-jkhan1?source=rss-4e2670156d5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GMVVwZzeleKnzJlXNZ3AAg.png</url>
            <title>Stories by Yusuf J Khan on Medium</title>
            <link>https://medium.com/@yusuf-jkhan1?source=rss-4e2670156d5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:04:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yusuf-jkhan1/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[A Gentle Introduction to Prompt Engineering for GPT-Based Models]]></title>
            <link>https://yusuf-jkhan1.medium.com/a-gentle-introduction-to-prompt-engineering-for-gpt-based-models-6a615680ed5?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a615680ed5</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpt-3]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 03:33:16 GMT</pubDate>
            <atom:updated>2023-03-15T03:33:16.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uP0JxaSCVGwGLshe" /><figcaption>Photo by <a href="https://unsplash.com/@zlucerophoto?utm_source=medium&amp;utm_medium=referral">Zach Lucero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>GPT-based models, such as OpenAI’s GPT-3, have revolutionized natural language processing and AI applications. One of the reasons these models have become so powerful is their ability to generate highly contextual and coherent responses based on the input, or prompt, they receive. In this article, we’ll dive into the concept of prompt engineering for GPT-based models, discuss why these models respond well to carefully crafted prompts, and explore techniques to get the most out of these incredible AI tools.</p><h3>The Power of GPT-Based Models: A Brief Overview</h3><p>GPT-based models are pretrained on massive amounts of text data from diverse sources, such as books, articles, and websites. During the training process, these models learn to predict the next word in a sequence, given the context provided by the preceding words. As a result, GPT models gain a deep understanding of grammar, syntax, and semantics, as well as the ability to generate highly contextual and coherent responses based on input prompts.</p><h3>The Art of Prompt Engineering</h3><p>Prompt engineering is the process of designing and refining input prompts to get the desired output from an AI model, specifically GPT-based models. It involves understanding how the model was trained and what type of input it expects to generate the desired results. By fine-tuning the prompt, users can obtain more accurate, contextually relevant, and useful responses from the AI model.</p><h3>Why Large Language Models Respond Well to Prompt Engineering</h3><p>The effectiveness of prompt engineering with GPT-based models can be attributed to the way these models are trained. During training, GPT models are exposed to a wide range of text inputs and learn to generate appropriate responses based on the context provided. This means that if you can craft a prompt that closely resembles the type of input the model has seen during its training, the model is more likely to generate a meaningful and accurate response.</p><p>Furthermore, GPT-based models use a technique called “transformer architecture,” which allows them to pay attention to different parts of the input and assign appropriate weights to each part. This enables the model to focus on the most relevant parts of the input prompt and generate contextually accurate responses.</p><h3>Good vs. Bad Prompt Examples</h3><p>To further illustrate the importance of prompt engineering, let’s compare good and bad examples of prompts and analyze their effectiveness.</p><p>Bad Prompt Example:</p><blockquote>What is the French Revolution</blockquote><p>This prompt is too vague and doesn’t provide enough context for the model to generate a meaningful response. The model could potentially generate a wide range of answers, making it difficult to obtain the desired information.</p><p>Good Prompt Example:</p><blockquote>Provide a brief summary of the key events that took place during the French Revolution between 1789 and 1799.</blockquote><p>This prompt is much more specific, providing a clear time frame and context. By specifying the French Revolution and the years of interest, the model has a much better chance of generating a coherent and relevant response.</p><p>Bad Prompt Example:</p><blockquote>Write me a story about living on Mars.</blockquote><p>This prompt is open-ended and doesn’t give any guidance on what type of story the model should generate. As a result, the output could be unpredictable and may not align with the user’s expectations. Although it could possibly be more creative. You have to balance your expectations and inputs to get the desired outputs.</p><p>Good Prompt Example:</p><blockquote>Write a short science fiction story set in the year 2500, where humans have established a colony on Mars and are now facing challenges adapting to the Martian environment.</blockquote><p>This prompt provides a specific genre (science fiction), setting (year 2500, Mars colony), and central conflict (challenges adapting to the Martian environment). By providing these details, the model is more likely to generate a coherent and engaging story that meets the user’s expectations.</p><h3>Analyzing the Differences</h3><p>The good prompt examples are more effective because they:</p><ol><li>Provide specificity: They include clear and concise instructions about the desired output, helping the model understand the user’s intent.</li><li>Include context: They supply relevant background information, which guides the model towards generating contextually accurate responses.</li><li>Set boundaries: They define the scope of the response, preventing the model from generating irrelevant or overly broad answers.</li></ol><p>By incorporating these characteristics into your prompts, you can significantly improve the quality of the responses generated by GPT-based models.</p><h3>Closing Thoughts</h3><p>Prompt engineering is a powerful technique to harness the full potential of GPT-based models. By understanding how these models are trained and learning how to craft effective prompts, users can obtain more accurate and contextually relevant responses from AI models. Through experimentation and refinement, prompt engineering can help you unleash the true power of GPT-based models and unlock new possibilities in natural language processing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a615680ed5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Analogy for Universal Approximation Theorem: From Discrete Pixels to Neural Networks]]></title>
            <link>https://yusuf-jkhan1.medium.com/an-analogy-for-universal-approximation-theorem-from-discrete-pixels-to-neural-networks-85faa108715f?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/85faa108715f</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[universal-approximation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[explanation]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 02:24:36 GMT</pubDate>
            <atom:updated>2023-03-15T02:24:36.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGZf8h8KrX0kSwqA" /><figcaption>Photo by <a href="https://unsplash.com/@vackground?utm_source=medium&amp;utm_medium=referral">vackground.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Universal Approximation Theorem (UAT) is a fundamental concept in neural network theory that explains the ability of neural networks to approximate any continuous function. To grasp this concept more intuitively, let’s use an analogy of RGB televisions and their discrete pixels that can be combined to create various images, from simple patterns to complex scenes.</p><blockquote><strong><em>From Discrete Pixels to Complex Images</em></strong></blockquote><p>Imagine an RGB television screen made up of discrete pixels. Each pixel can display a single color at a time, created by combining various intensities of red, green, and blue. By adjusting the intensity of these primary colors, a pixel can generate a vast array of colors.</p><p>Now, consider a small 10x10 grid of pixels. With just 100 pixels, you can create simple, crude images or patterns. The resolution is low, but it still serves as a representation of the intended image. As you increase the number of pixels, the image’s resolution and quality improve, allowing you to create anything from Jurassic Park to Star Wars and everything in between.</p><p>This idea of composing complex images from discrete values (pixels) can be used to understand how a neural network can approximate any continuous function, as described by the Universal Approximation Theorem.</p><blockquote><strong><em>Neural Networks: Approximating Functions with Discrete Neurons</em></strong></blockquote><p>In a neural network, the basic building blocks are the neurons. Each neuron performs a simple operation on its input and generates an output, akin to a pixel displaying a single color. By adjusting the weights and biases of the neurons in a neural network, we can change the output of each neuron, just like how we can change the intensity of the primary colors in a pixel to create different colors.</p><p>With a small number of neurons, a neural network can approximate simple functions, just as a small number of pixels can create crude images. As the number of neurons in the network increases, the complexity of the functions that the network can approximate also increases. This is similar to how an image’s resolution and quality improve with an increase in the number of pixels.</p><blockquote><strong><em>The Universal Approximation Theorem: Creating Complex Functions with Discrete Neurons</em></strong></blockquote><p>The Universal Approximation Theorem states that a neural network with a single hidden layer containing a finite number of neurons can approximate any continuous function, given that the activation function is a non-constant, bounded, and continuous function. This means that, in theory, even a simple neural network can learn to approximate complex functions.</p><p>In conclusion, the analogy of RGB televisions and discrete pixels helps us understand the Universal Approximation Theorem more intuitively. Just as a television screen can display anything from simple patterns to complex images using a composition of discrete pixel values, a neural network can approximate any continuous function by breaking it down into simpler parts and combining them using its discrete neurons. This powerful concept forms the foundation for many modern machine learning algorithms and highlights the potential of neural networks in a wide range of applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85faa108715f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polars: The Next Evolution in the Python Data Ecosystem]]></title>
            <link>https://yusuf-jkhan1.medium.com/polars-the-next-evolution-in-the-python-data-ecosystem-4bbf1b5ae3f7?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbf1b5ae3f7</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 02:03:21 GMT</pubDate>
            <atom:updated>2023-03-15T02:03:21.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wf-MmQmBgyUkYRcv" /><figcaption>Photo by <a href="https://unsplash.com/de/@geoffroyh?utm_source=medium&amp;utm_medium=referral">Geoffroy Hauwen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The field of data analysis is in constant motion, with new libraries and techniques emerging regularly to tackle challenges and improve performance. As the data science ecosystem evolves, some libraries fade away, while others take the spotlight. One such example is the transition from NumPy to pandas for data manipulation, which brought a more convenient and powerful DataFrame API to the Python community.</p><p>In this blog post, we’ll introduce you to a new contender in the Python data analysis landscape: Polars. Polars is a high-performance DataFrame library that aims to outshine pandas in terms of speed and memory efficiency. We’ll explore why Polars is so fast, especially when compared to Python-based libraries, and walk you through some common operations to demonstrate its capabilities.</p><h3>The Power of Polars: Rust Under the Hood</h3><p>Polars leverages the power of Rust, a systems programming language known for its speed, memory safety, and concurrency capabilities. Rust’s strong focus on performance and low-level control allows developers to create highly efficient libraries that can outperform their counterparts written in languages like Python. By implementing Polars in Rust and providing Python bindings, the library achieves significant speed improvements and memory optimizations compared to pandas, which is written in Python and C.</p><h3>Getting Started with Polars</h3><p>To install Polars, use the following pip command:</p><pre>pip install polars</pre><p>Once you have Polars installed, you can import it in your Python script using:</p><pre>import polars as pl</pre><h3>Creating a DataFrame</h3><p>Creating a DataFrame in Polars is similar to creating one in pandas. You can use a dictionary, where keys represent column names and values are lists of corresponding data:</p><pre>data = {<br>    &quot;name&quot;: [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;],<br>    &quot;age&quot;: [25, 30, 35],<br>    &quot;city&quot;: [&quot;New York&quot;, &quot;San Francisco&quot;, &quot;Los Angeles&quot;]<br>}<br>df = pl.DataFrame(data)</pre><p>You can also create a DataFrame using a list of tuples, where each tuple contains a column name and its associated data:</p><pre>data = [<br>    (&quot;name&quot;, [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]),<br>    (&quot;age&quot;, [25, 30, 35]),<br>    (&quot;city&quot;, [&quot;New York&quot;, &quot;San Francisco&quot;, &quot;Los Angeles&quot;])<br>]<br>df = pl.DataFrame(data)</pre><h3>Common DataFrame Operations</h3><h3>Selecting Columns</h3><p>To select a specific column from the DataFrame, you can use the same indexing syntax as pandas:</p><pre>names = df[&#39;name&#39;]</pre><p>Alternatively, you can use the select method:</p><pre>names = df.select(&#39;name&#39;)</pre><h3>Filtering Rows</h3><p>To filter rows based on a condition, you can use the filter method, which takes a boolean expression as an argument:</p><pre>older_than_25 = df.filter(df[&#39;age&#39;] &gt; 25)</pre><h3>Sorting Data</h3><p>To sort a DataFrame by one or more columns, you can use the sort method:</p><pre>sorted_by_age = df.sort(&#39;age&#39;)</pre><p>You can also sort by multiple columns by providing a list of column names:</p><pre>sorted_by_age_and_name = df.sort([&#39;age&#39;, &#39;name&#39;])</pre><h3>Aggregations</h3><p>Polars supports various aggregation functions, such as sum, mean, min, max, and count. To perform an aggregation on a specific column, use the agg method:</p><pre>average_age = df[&#39;age&#39;].agg(pl.mean())</pre><h3>Grouping Data</h3><p>To group data by one or more columns and perform aggregations, use the groupby method followed by an aggregation function:</p><pre>grouped_data = df.groupby(&#39;city&#39;).agg(pl.mean(&#39;age&#39;))</pre><p>This code groups the DataFrame by the city column and calculates the average age for each city.</p><h3>Lazy Evaluation</h3><p>One of the key features of Polars is its support for lazy evaluation. This means that when you perform operations on a DataFrame, they are not immediately executed. Instead, Polars creates an execution plan that represents the sequence of operations. The actual computation is deferred until the result is explicitly requested, allowing Polars to optimize the execution plan for better performance and reduced memory usage.</p><p>To enable lazy evaluation, you can use the lazy method on a DataFrame:</p><pre>lazy_df = df.lazy()</pre><p>Now, when you perform operations on lazy_df, they will be added to the execution plan instead of being executed immediately. To compute the final result, use the collect method:</p><pre>result = lazy_df.select(&#39;name&#39;).filter(df[&#39;age&#39;] &gt; 25).collect()</pre><p>This code creates an execution plan to select the name column and filter rows with an age greater than 25. The collect method triggers the computation and returns the result as a DataFrame.</p><h3>Performance Comparison with Pandas</h3><p>The performance gains of Polars compared to pandas can be significant, especially when working with large datasets or performing complex operations. While the exact speedup depends on the specific use case and hardware, it’s not uncommon to see Polars outperform pandas by a factor of 10 or more.</p><p>Keep in mind that for small datasets or simple operations, the difference in performance might not be as noticeable. However, as your data size and complexity grow, Polars can become an invaluable tool for efficient data analysis.</p><h3>Final Thoughts</h3><p>Polars is a powerful and fast DataFrame library that aims to revolutionize the way we perform data analysis in Python. With its Rust-based implementation, Polars can achieve remarkable performance improvements over traditional Python-based libraries like pandas. As we’ve seen in this blog post, Polars provides a familiar API and supports a wide range of operations, making it easy to incorporate into your existing data analysis workflows.</p><p>As the field of data analysis continues to evolve, libraries like Polars are pushing the boundaries of what’s possible in terms of performance and efficiency. Give Polars a try, and see for yourself how it can supercharge your data analysis projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbf1b5ae3f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I/O Operations with Polars: Tips and Tricks]]></title>
            <link>https://yusuf-jkhan1.medium.com/i-o-operations-with-polars-tips-and-tricks-7dc8946d573f?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dc8946d573f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 02:00:02 GMT</pubDate>
            <atom:updated>2023-03-15T02:00:02.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X5baMlo_L_5Oja2C" /><figcaption>Photo by <a href="https://unsplash.com/@op23?utm_source=medium&amp;utm_medium=referral">op23</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Polars supports reading from and writing to various file formats, such as CSV, Parquet, JSON, and more. In this section, we’ll cover some examples of how to work with different file formats and share some best practices for efficient I/O operations.</p><h3>Reading and Writing CSV Files</h3><p>To read a CSV file, use the pl.read_csv function:</p><pre>df = pl.read_csv(&quot;your_file.csv&quot;)</pre><p>When reading large CSV files, you can use the batch_size parameter to read the data in chunks. This can reduce memory usage and increase performance:</p><pre>df = pl.read_csv(&quot;large_file.csv&quot;, batch_size=50000)</pre><p>To write a DataFrame to a CSV file, use the write_csv method:</p><pre>df.write_csv(&quot;output_file.csv&quot;)</pre><h3>Reading and Writing Parquet Files</h3><p>Parquet is a columnar storage file format that is optimized for use with big data processing frameworks. It offers advantages such as data compression and improved query performance. To read a Parquet file, use the pl.read_parquet function:</p><pre>df = pl.read_parquet(&quot;your_file.parquet&quot;)</pre><p>To write a DataFrame to a Parquet file, use the write_parquet method:</p><pre>df.write_parquet(&quot;output_file.parquet&quot;)</pre><h3>Reading and Writing JSON Files</h3><p>Polars also supports reading and writing JSON files. To read a JSON file, use the pl.read_json function:</p><pre>df = pl.read_json(&quot;your_file.json&quot;)</pre><p>To write a DataFrame to a JSON file, use the write_json method:</p><pre>df.write_json(&quot;output_file.json&quot;)</pre><h3>Tips and Best Practices</h3><ol><li>Choose the right file format: Pick a file format that suits your specific use case. CSV is a popular and widely supported format but can be slow to read and write for large datasets. Parquet provides better performance and compression, making it a great choice for big data scenarios.</li><li>Use lazy evaluation: When reading large datasets, consider using Polars’ lazy evaluation feature. This allows you to perform operations on the data without loading the entire dataset into memory, reducing memory usage and potentially increasing performance.</li><li>Optimize column types: When reading data, Polars automatically infers the data types of columns. However, you can also explicitly specify the data types using the dtype parameter. This can help avoid unnecessary type conversions and improve performance.</li><li>Utilize chunked reading: When reading large files, consider using the batch_size parameter to read data in chunks. This can help reduce memory usage and allow for more efficient processing of large datasets.</li></ol><p>By following these tips and best practices, you can ensure that your I/O operations with Polars are as efficient and performant as possible, allowing you to focus on analyzing your data and deriving valuable insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dc8946d573f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[!Forget to save this post: A Python Cheat Sheet to Boost Your Skills Overnight!]]></title>
            <link>https://yusuf-jkhan1.medium.com/forget-to-save-this-post-a-python-cheat-sheet-to-boost-your-skills-overnight-edd95619b503?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd95619b503</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 01:28:34 GMT</pubDate>
            <atom:updated>2023-03-15T01:28:34.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MGIoBQJK34yk5Vs-" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data science is an ever-evolving field, and mastering it can be a daunting task. But fear not, because we have just the thing to give you an edge! Introducing the ultimate Python cheat sheet for data science, designed to supercharge your skills overnight. Experts might not be thrilled that we’re sharing these secrets, but we believe everyone should have access to these powerful tools. So let’s dive in!</p><h3>Python Libraries for Data Science</h3><p>First things first: the lifeblood of any data scientist working with Python is the extensive collection of libraries available. Here are some essential libraries that you should be familiar with:</p><ol><li>NumPy: A library for working with numerical data and arrays.</li><li>pandas: A library for data manipulation and analysis, particularly useful for working with tabular data.</li><li>Matplotlib: A library for creating static, interactive, and animated visualizations.</li><li>Scikit-learn: A library for machine learning and data mining tasks, including preprocessing, model selection, and evaluation.</li><li>TensorFlow: A library for machine learning and deep learning tasks, particularly focused on neural networks.</li><li>Keras: A high-level neural networks API, commonly used as a user-friendly interface to TensorFlow.</li><li>Seaborn: A library for statistical data visualization, based on Matplotlib.</li><li>Statsmodels: A library for statistical modeling, hypothesis testing, and data exploration.</li></ol><h3>Data Import and Export</h3><h3>Reading Data with pandas</h3><pre>import pandas as pd<br><br># Read a CSV file<br>data = pd.read_csv(&#39;file.csv&#39;)<br><br># Read an Excel file<br>data = pd.read_excel(&#39;file.xlsx&#39;)<br><br># Read a JSON file<br>data = pd.read_json(&#39;file.json&#39;)<br><br># Read an SQL query<br>from sqlalchemy import create_engine<br>engine = create_engine(&#39;sqlite:///database.db&#39;)<br>data = pd.read_sql_query(&#39;SELECT * FROM table_name&#39;, engine)</pre><h3>Writing Data with pandas</h3><pre># Write to a CSV file<br>data.to_csv(&#39;output.csv&#39;, index=False)<br><br># Write to an Excel file<br>data.to_excel(&#39;output.xlsx&#39;, index=False)<br><br># Write to a JSON file<br>data.to_json(&#39;output.json&#39;, orient=&#39;records&#39;)<br><br># Write to an SQL table<br>data.to_sql(&#39;table_name&#39;, engine, if_exists=&#39;replace&#39;, index=False)</pre><h3>Data Cleaning and Preprocessing</h3><h3>Handling Missing Data with pandas</h3><pre># Drop rows with missing data<br>data.dropna(axis=0, inplace=True)<br><br># Drop columns with missing data<br>data.dropna(axis=1, inplace=True)<br><br># Fill missing data with a specific value or method<br>data.fillna(value=0, inplace=True)<br>data.fillna(method=&#39;ffill&#39;, inplace=True)  # Forward fill<br>data.fillna(method=&#39;bfill&#39;, inplace=True)  # Backward fill</pre><h3>Data Transformation with pandas</h3><pre># Rename columns<br>data.rename(columns={&#39;old_name&#39;: &#39;new_name&#39;}, inplace=True)<br><br># Drop columns<br>data.drop(columns=[&#39;column_name&#39;], inplace=True)<br><br># Apply a function to a column<br>data[&#39;new_column&#39;] = data[&#39;column_name&#39;].apply(lambda x: x * 2)<br><br># One-hot encoding<br>data = pd.get_dummies(data, columns=[&#39;categorical_column&#39;])</pre><h3>Data Visualization</h3><h3>Basic Plotting with Matplotlib</h3><pre>import matplotlib.pyplot as plt<br><br># Line plot<br>plt.plot(x, y)<br>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Y-axis label&#39;)<br>plt.title(&#39;Line Plot&#39;)<br>plt.show()<br><br># Scatter plot<br>plt.scatter(x, y)<br>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Y-axis label&#39;)<br>plt.title(&#39;Scatter Plot&#39;)<br>plt.show()<br><br># Bar plot<br>plt.bar(x, y)<br>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Y-axis label&#39;)<br>plt.title(&#39;Bar Plot&#39;)<br>plt.show()<br><br># Histogram<br>plt.hist(data, bins=10)<br>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.title(&#39;Histogram&#39;)<br>plt.show()</pre><h3>Advanced Plotting with Seaborn</h3><pre>import seaborn as sns<br><br># Box plot<br>sns.boxplot(x=&#39;categorical_column&#39;, y=&#39;numerical_column&#39;, data=data)<br>plt.show()<br><br># Violin plot<br>sns.violinplot(x=&#39;categorical_column&#39;, y=&#39;numerical_column&#39;, data=data)<br>plt.show()<br><br># Pair plot<br>sns.pairplot(data)<br>plt.show()<br><br># Heatmap<br>correlation_matrix = data.corr()<br>sns.heatmap(correlation_matrix, annot=True, cmap=&#39;coolwarm&#39;)<br>plt.show()</pre><h3>Machine Learning with Scikit-learn</h3><h3>Basic Workflow</h3><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error<br><br># Split data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Scale the data<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)<br><br># Train a model<br>model = LinearRegression()<br>model.fit(X_train_scaled, y_train)<br><br># Make predictions<br>predictions = model.predict(X_test_scaled)<br><br># Evaluate the model<br>mse = mean_squared_error(y_test, predictions)</pre><h3>Final Remarks</h3><p>These Python snippets have hopefully given you a quick and easy way to boost your data science skills overnight. From importing data and cleaning it, to visualizing and modeling, we’ve covered the most essential tips and tricks to help you master data science in Python.</p><p>Remember, though, that this cheat sheet is just a starting point. To truly excel in data science, you’ll need to dive deeper into each topic and continue learning through practice and exploration. But armed with this cheat sheet, you’re well on your way to becoming a data science pro!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd95619b503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cooking Up Concurrency and Parallelism in Python: A Tasty Guide]]></title>
            <link>https://yusuf-jkhan1.medium.com/cooking-up-concurrency-and-parallelism-in-python-a-tasty-guide-d99d429b8efb?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d99d429b8efb</guid>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 01:16:44 GMT</pubDate>
            <atom:updated>2023-03-15T01:16:44.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CrWNh7ZWG29NGFwy" /><figcaption>Photo by <a href="https://unsplash.com/@sebastiancoman?utm_source=medium&amp;utm_medium=referral">Sebastian Coman Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we talk about speeding up your Python code, two terms that often come up are concurrency and parallelism. While these concepts are related, they are not the same thing. To help you understand the differences, let’s use the analogy of a kitchen. Imagine you’re a chef trying to cook several dishes at the same time or order a large number of ingredients. How can you make the process faster and more efficient? In this post, we’ll explore concurrency and parallelism in Python, using the kitchen analogy and code examples with 20 ingredients and dishes to demonstrate the differences.</p><h3>Concurrency: The Multitasking Chef</h3><p>Concurrency is like a chef who’s multitasking, working on several dishes at once, but not necessarily cooking them all at the same time. The chef can start preparing one dish, then switch to another while waiting for the first dish to cook. In this way, the chef can work on multiple tasks without having to wait for one to complete before starting another.</p><p>In Python, we can achieve concurrency using threads. Threads are like chefs who can work on different tasks within the same process. Let’s see an example using the threading module in Python, where a chef has to order 20 different ingredients:</p><pre>import threading<br>import multiprocessing<br>import time<br><br>def order_ingredients(ingredient):<br>    print(f&quot;Ordering {ingredient}...&quot;)<br>    time.sleep(2)<br>    print(f&quot;{ingredient} ordered!&quot;)<br><br>ingredients = [&#39;tomatoes&#39;, &#39;onions&#39;, &#39;garlic&#39;, &#39;basil&#39;, &#39;pasta&#39;, &#39;olive oil&#39;, &#39;salt&#39;, &#39;pepper&#39;, &#39;oregano&#39;, &#39;thyme&#39;, &#39;cheese&#39;, &#39;flour&#39;, &#39;sugar&#39;, &#39;butter&#39;, &#39;milk&#39;, &#39;eggs&#39;, &#39;vanilla&#39;, &#39;cinnamon&#39;, &#39;nutmeg&#39;, &#39;yeast&#39;]<br><br># Using threading (concurrency)<br>start_time_threads = time.time()<br><br>threads = [threading.Thread(target=order_ingredients, args=(ingredient,)) for ingredient in ingredients]<br>for t in threads:<br>    t.start()<br><br>for t in threads:<br>    t.join()<br><br>end_time_threads = time.time()<br><br># Using multiprocessing (parallelism)<br>start_time_processes = time.time()<br><br>processes = [multiprocessing.Process(target=order_ingredients, args=(ingredient,)) for ingredient in ingredients]<br>for p in processes:<br>    p.start()<br><br>for p in processes:<br>    p.join()<br><br>end_time_processes = time.time()<br><br>print(f&quot;Time taken with threading: {end_time_threads - start_time_threads:.2f} seconds&quot;)<br>print(f&quot;Time taken with multiprocessing: {end_time_processes - start_time_processes:.2f} seconds&quot;)</pre><p>In this example, we define the order_ingredients function, which simulates the time it takes to order ingredients. We create 20 threads, one for each ingredient, and start them. The tasks run concurrently, allowing the chef to work on multiple tasks without waiting for one to complete before starting the other. Concurrency is efficient in this I/O-bound scenario, where waiting is involved.</p><h3>Parallelism: The Team of Chefs</h3><p>Parallelism is like having multiple chefs working in the kitchen at the same time. Each chef can work on their own dish simultaneously, allowing the kitchen to produce multiple dishes at once.</p><p>In Python, we can achieve parallelism using the multiprocessing module. Processes are like separate chefs, each with their own resources and workspace. Here&#39;s an example using the multiprocessing module in Python, where a team of chefs needs to cook 20 different dishes:</p><pre>import threading<br>import multiprocessing<br>import time<br><br>def cook_dish(dish):<br>    print(f&quot;Cooking {dish}...&quot;)<br>    start_time = time.time()<br>    for _ in range(10 ** 7):<br>        pass<br>    end_time = time.time()<br>    print(f&quot;{dish} cooked in {end_time - start_time:.2f} seconds&quot;)<br><br>dishes = [&#39;pizza&#39;, &#39;pasta&#39;, &#39;lasagna&#39;, &#39;risotto&#39;, &#39;soup&#39;, &#39;salad&#39;, &#39;sandwich&#39;, &#39;steak&#39;, &#39;burger&#39;, &#39;fries&#39;, &#39;tacos&#39;, &#39;burrito&#39;, &#39;sushi&#39;, &#39;ramen&#39;, &#39;fried rice&#39;, &#39;curry&#39;, &#39;pad thai&#39;, &#39;grilled cheese&#39;, &#39;pancakes&#39;, &#39;waffles&#39;]<br><br># Using threading (concurrency)<br>start_time_threads = time.time()<br><br>threads = [threading.Thread(target=cook_dish, args=(dish,)) for dish in dishes]<br>for t in threads:<br>    t.start()<br><br>for t in threads:<br>    t.join()<br><br>end_time_threads = time.time()<br><br># Using multiprocessing (parallelism)<br>start_time_processes = time.time()<br><br>processes = [multiprocessing.Process(target=cook_dish, args=(dish,)) for dish in dishes]<br>for p in processes:<br>    p.start()<br><br>for p in processes:<br>    p.join()<br><br>end_time_processes = time.time()<br><br>print(f&quot;Time taken with threading: {end_time_threads - start_time_threads:.2f} seconds&quot;)<br>print(f&quot;Time taken with multiprocessing: {end_time_processes - start_time_processes:.2f} seconds&quot;)</pre><p>In this example, we use the cook_dish function, which simulates a CPU-bound task that requires intensive computation. Instead of using threads, we create 20 separate processes, one for each dish. This allows the tasks to run in parallel, with each process working on its task independently and simultaneously. Parallelism is efficient in this CPU-bound scenario, where heavy computation is involved.</p><h3>Concurrency vs. Parallelism: Key Takeaways</h3><p>Concurrency and parallelism are two strategies for improving the performance and efficiency of your Python code:</p><ul><li>Concurrency: Multitasking within a single process, like a chef who can switch between tasks without waiting for one to finish before starting another. Concurrency in Python can be achieved using threads.</li><li>Parallelism: Running tasks simultaneously across multiple processes, like having a team of chefs working on different dishes at the same time. Parallelism in Python can be achieved using multiple processes.</li></ul><p>While both concurrency and parallelism can help speed up your code, they are best suited for different situations:</p><ul><li>Concurrency is more appropriate for tasks that spend a lot of time waiting, such as I/O-bound tasks or tasks that require communication with external services. Using threads, you can switch to another task while waiting for a response, making better use of the available</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d99d429b8efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the AI Curtain: A Simple Guide to Understanding GPT-3 and GPT-4’s Superpowers]]></title>
            <link>https://yusuf-jkhan1.medium.com/behind-the-ai-curtain-a-simple-guide-to-understanding-gpt-3-and-gpt-4s-superpowers-656f5c6a4cec?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/656f5c6a4cec</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[gpt-4]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 22:26:31 GMT</pubDate>
            <atom:updated>2023-03-14T22:26:31.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R4ruMCZkwBZmsZJL" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">CHUTTERSNAP</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In recent years, AI language models like OpenAI’s GPT-3 and GPT-4 have taken the tech world by storm. While their capabilities are truly impressive, understanding how they work can be challenging for those who aren’t well-versed in machine learning. In this blog post, we’ll break down the training process, functioning, strengths, weaknesses, and ethical challenges of GPT-3 and GPT-4 in simple terms that anyone can understand.</p><p><strong>Training GPT-3 and GPT-4: Learning from Massive Text Data</strong></p><p>GPT-3 and GPT-4 are trained using a two-step process: pre-training and fine-tuning. During pre-training, the models learn from a vast amount of text data collected from the internet, including websites, books, and articles. They pick up patterns, relationships between words, and even some facts about the world.</p><p>Fine-tuning is the second step, where the models are further trained on smaller, specific datasets to perform specialized tasks, such as answering questions or summarizing text. By fine-tuning, GPT-3 and GPT-4 can be adapted to various applications, making them versatile and useful tools.</p><p><strong>How GPT-3 and GPT-4 Work: Understanding and Generating Text</strong></p><p>GPT-3 and GPT-4 are both built using a type of AI model called the “Transformer.” This model allows the AI to pay attention to different parts of the input text and understand the context. When you give GPT-3 or GPT-4 a prompt, they generate text by predicting one word at a time, taking into account the words that came before it and the relationships between them. This process continues until the AI has generated a complete response.</p><p><strong>Strengths and Weaknesses of GPT-3 and GPT-4</strong></p><p>Strengths:</p><ol><li>Coherent Text Generation: Both GPT-3 and GPT-4 can generate coherent and contextually relevant text, making them useful for a wide range of applications like content creation, summarization, and question-answering.</li><li>Multilingual Capabilities: Since they are trained on text data from various languages, GPT-3 and GPT-4 can generate content and understand queries in multiple languages.</li><li>Fine-tuning: Both models can be fine-tuned to perform specific tasks, making them adaptable to various use cases.</li></ol><p>Weaknesses:</p><ol><li>Incomplete Understanding: Although GPT-3 and GPT-4 can generate human-like text, they sometimes lack a deep understanding of context or struggle with complex reasoning tasks.</li><li>Verbose or Nonsensical Outputs: The models may occasionally generate verbose or nonsensical text, as their primary goal is to predict the next word in a sequence.</li><li>Bias: Since the models learn from text data on the internet, they may inadvertently acquire and reproduce biases present in the data.</li></ol><p><strong>Ethical Challenges</strong></p><p>As GPT-3 and GPT-4 continue to advance, several ethical challenges arise:</p><ol><li>Misinformation and Disinformation: The ability to generate human-like text can be exploited to create fake news or spread false information, undermining trust in online content.</li><li>Deepfakes and Manipulation: AI-generated text, images, or videos can be used to create convincing deepfakes, leading to potential manipulation and privacy concerns.</li><li>Bias and Discrimination: As mentioned earlier, GPT-3 and GPT-4 can inherit biases from their training data, which may lead to biased outputs that perpetuate stereotypes or discrimination.</li></ol><p>GPT-3 and GPT-4 are remarkable advancements in AI language models, offering impressive capabilities in understanding and generating human-like text. Their training process, which involves pre-training on vast amounts of data followed by fine-tuning, makes them versatile and adaptable to a wide range of applications.</p><p>Despite their strengths, these models have their limitations, such as incomplete understanding, verbosity, and the potential for biased outputs. As we continue to develop and utilize AI models like GPT-3 and GPT-4, it is crucial to be aware of the ethical challenges they pose, including misinformation, deepfakes, and biases.</p><p>By understanding both the potential and the limitations of these AI models, we can make informed decisions about their applications and work towards addressing the ethical challenges they present. As AI continues to advance, researchers, developers, and policymakers must collaborate to ensure that technologies like GPT-3 and GPT-4 are used responsibly and for the betterment of society.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=656f5c6a4cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Frontiers of AI: The Evolution from GPT-3 to GPT-4]]></title>
            <link>https://yusuf-jkhan1.medium.com/exploring-the-frontier-of-ai-c884ecd8af5d?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c884ecd8af5d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 22:11:32 GMT</pubDate>
            <atom:updated>2023-03-15T00:45:14.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Frontier of AI: The Evolution from GPT-3 to GPT-4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyJOuNe07k1ioen7" /><figcaption>Photo by <a href="https://unsplash.com/@stefanbc?utm_source=medium&amp;utm_medium=referral">Stefan Cosma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>The landscape of artificial intelligence (AI) has seen tremendous growth in recent years, with language models like OpenAI’s GPT series pushing the boundaries of what’s possible. GPT-3, the third iteration in the series, gained significant attention for its ability to generate human-like text. But as with all technology, progress never ceases, and GPT-4 has since been unveiled, taking the AI world by storm. In this blog post, we will delve into the differences between GPT-3 and GPT-4, exploring the improvements, implications, and potential applications of these groundbreaking language models.</p><h4>GPT-3: A Brief Recap</h4><p>Before diving into GPT-4, let’s briefly revisit the achievements of its predecessor, GPT-3. Released in 2020 by OpenAI, GPT-3 quickly gained prominence as one of the most powerful language models of its time. With 175 billion parameters, it was orders of magnitude larger than its predecessors. This size enabled GPT-3 to produce coherent and contextually relevant text, perform basic arithmetic, answer questions, and even generate code.</p><p>GPT-3’s capabilities were largely a result of its architecture, which employed the Transformer model. This deep learning model allowed GPT-3 to attend to different parts of the input sequence, enabling better understanding of context and long-range dependencies. However, GPT-3 was not without its limitations. Despite its impressive performance, it occasionally produced nonsensical or verbose outputs and struggled with tasks requiring a deeper understanding of context or more complex reasoning.</p><h4>Enter GPT-4: Enhancements and Innovations</h4><p>With GPT-4, OpenAI has once again raised the bar for AI language models. Key differences between GPT-3 and GPT-4 include:</p><ol><li>Scale: GPT-4 boasts a staggering number of parameters, outshining GPT-3’s 175 billion by a considerable margin. This growth in scale has allowed GPT-4 to learn even more complex patterns and understand context at a deeper level. As a result, it can generate more accurate and coherent text.</li><li>Training Data: GPT-4 is trained on a more diverse and extensive dataset compared to GPT-3. The expanded dataset includes web pages, books, articles, and other sources from various fields and languages. This broader dataset enables GPT-4 to generate content in multiple languages and demonstrate a better understanding of different domains.</li><li>Architectural Improvements: GPT-4 incorporates several architectural refinements that allow it to more effectively learn from its training data. These improvements include innovations in attention mechanisms, optimizations in parallel processing, and enhanced techniques for handling longer input sequences.</li><li>Fine-tuning Capabilities: GPT-4 offers more efficient fine-tuning, allowing developers to adapt the model to specific tasks with smaller datasets. This capability makes GPT-4 a more versatile tool for a wide range of applications.</li></ol><h4>Implications of GPT-4’s Advancements</h4><p>The advancements in GPT-4 have significant implications for both AI research and practical applications. Some of these implications include:</p><ol><li>Enhanced Natural Language Understanding: GPT-4’s improvements allow it to understand context and relationships between words more effectively. This deeper understanding enables more accurate language generation, question-answering, and sentiment analysis.</li><li>Multilingual Capabilities: GPT-4’s extensive training data and architectural advancements have expanded its capabilities across multiple languages. This makes it a valuable tool for translation, cross-lingual information retrieval, and multilingual content generation.</li><li>Real-world Applications: GPT-4’s increased accuracy and versatility open the doors to a myriad of real-world applications. Industries such as healthcare, finance, and law can benefit from GPT-4’s improved natural language understanding for tasks like summarizing documents, drafting reports, and automating customer support.</li><li>Ethical Considerations: As GPT-4’s capabilities continue to advance, ethical concerns surrounding AI-generated content become more pressing. Issues like deepfake generation, misinformation, and privacy must be addressed by both researchers and policymakers to ensure the responsible use of this technology.</li><li>Democratization of AI: GPT-4’s fine-tuning capabilities and ease of use make it more accessible to developers and organizations with limited resources. This democratization of AI can spur innovation and empower smaller players in various industries.</li></ol><h4>Potential Applications of GPT-4</h4><p>GPT-4’s enhancements over its predecessor have opened the doors to a range of new applications across various domains:</p><ol><li>Creative Writing: GPT-4’s ability to generate coherent and contextually relevant text can aid writers in generating ideas, crafting dialogues, or even writing entire stories. The improved model can also assist in generating marketing copy, ad slogans, or social media content.</li><li>Code Generation: GPT-4 can generate code more accurately than GPT-3, making it a useful tool for developers seeking to automate coding tasks or generate code snippets.</li><li>Personal Assistants: With its enhanced language understanding, GPT-4 can serve as the foundation for more sophisticated AI personal assistants. These assistants can understand and respond to complex queries, manage schedules, and even carry out context-aware conversations.</li><li>Education: GPT-4’s advancements can be leveraged in educational settings to create personalized learning experiences, generate practice questions, or provide real-time feedback on student work.</li><li>Data Analysis and Visualization: GPT-4 can be used to analyze large datasets, identify patterns, and generate insightful visualizations, aiding professionals in fields such as data science, finance, and market research.</li></ol><h4>Conclusion</h4><p>The release of GPT-4 marks yet another leap forward in the world of artificial intelligence. With its increased scale, diverse training data, architectural improvements, and fine-tuning capabilities, GPT-4 has demonstrated unparalleled natural language understanding and generation. As a result, it has opened up numerous possibilities for real-world applications across various industries.</p><p>However, as with any technology, the ethical implications of GPT-4’s advancements must be carefully considered. As the AI community continues to innovate and push the boundaries of what is possible, researchers, developers, and policymakers must work together to ensure that AI technologies like GPT-4 are used responsibly and for the betterment of society.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c884ecd8af5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Placement Optimization of Public EV Charging Stations]]></title>
            <link>https://medium.com/99p-labs/placement-optimization-of-public-ev-charging-stations-67ece277e460?source=rss-4e2670156d5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/67ece277e460</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[university]]></category>
            <category><![CDATA[telematics]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ev-charging]]></category>
            <dc:creator><![CDATA[Yusuf J Khan]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 01:31:06 GMT</pubDate>
            <atom:updated>2020-12-18T14:41:06.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Authored by Yusuf Khan</p><p>Case Study: Leveraging vehicle telematics data to determine optimal locations to install EV charging stations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIDcQezsgAU5P38_cy2Hwg.png" /><figcaption>Rain’s Rustle II |Credit: Leonid Afremov|</figcaption></figure><blockquote>In research as in art, we often encounter representations that are expressive surrogates for the literal. And it’s in that chasm where we search for meanings.</blockquote><h4>Table of Contents</h4><ul><li><a href="#ba77">Introduction</a></li><li><a href="#7d16">Data Acquisition and Wrangling</a></li><li><a href="#962c">Candidate Location Identification</a></li><li><a href="#8d6c">Cluster Feature Engineering</a></li><li><a href="#9f0e">Selection Optimization</a></li><li><a href="#9a66">Evaluation and Experiments</a></li><li><a href="#046c">Discussion and Future Work</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBTJByWEXOg4rhjxv6feEw.jpeg" /><figcaption>| Credit: <a href="https://pixabay.com/users/paulbr75-2938186/">paulbr75</a> from <a href="https://pixabay.com/photos/electric-charge-road-sign-sign-2301604/">Pixabay </a>|</figcaption></figure><h3>— Introduction —</h3><h4>One of the considerable challenges of the coming decade will be how to transition to cleaner, more efficient sources of energy.</h4><p>One of the notable emerging technologies that tackles this challenge are fully battery powered electric vehicles (<strong>EV</strong>s). For over a century traditional internal combustion engine (<strong>ICE</strong>) vehicles have been establishing the infrastructure necessary for commercial use, in comparison if EV adoption is to make a significant impact in the clean energy movement, it will have to cultivate similar levels of <em>functionality </em>in its supporting infrastructure in a fraction of that time. The keyword here being, <em>functionality</em>, because the dynamics of the supporting network for ICE vehicles and EVs will differ, so absolute infrastructure-per-capita comparisons may largely be misleading.</p><p>As a student at <strong>Georgia Tech</strong>, I was enrolled in a Computer Science and Engineering class for <strong>Data and Visual Analytics</strong> and was presented with the opportunity to work on a semester long, structured project worth 50% of the total available grade. While it felt easy to reach for a coronavirus or twitter analysis, the project description specifically challenged us to pick a difficult topic and focus less on success vs failure, and more on learning and breaking down a problem into computational components. Knowing that I wouldn’t enjoy working on something rote or cliché, I decided to pursue one of my more ambitious ideas that had been simmering in the back of my mind for some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIWbgJ_TGxTxxN2CfdmvSw.jpeg" /><figcaption>Honda | Credit: <a href="https://pixabay.com/users/iniesta44-4560761/">iniesta44</a> from <a href="https://pixabay.com/photos/honda-auto-vehicle-race-speed-4967587/">Pixabay</a>|</figcaption></figure><p><a href="https://www.99plabs.com/"><strong>99P Labs</strong></a>, powered by a partnership between <strong>Honda and The Ohio State University</strong> provides a unique and intellectually captivating <a href="https://developer.99plabs.io/">data developer platform</a> that (among other things) serves an event stream of vehicle telematics data. This is real data, coming in over the air from vehicles in use on the roads. It’s packaged with privacy and purpose such that the information being served contains nothing intrusive or personally identifiable about any of the vehicles in the fleet. All the information is purposefully packaged in a single, easy-to-use, well documented API geared towards research and use case exploration. The case study my group and I pursued thus intended to…</p><blockquote><strong><em>Evaluate a geo-spatial, telematics driven method to augment infrastructure planning decisions for Public EV Charging Stations (PCS), specifically as it relates to improving EV adoption through placement optimization.</em></strong></blockquote><h3>— Data Acquisition and Wrangling —</h3><p><strong>We proceeded with our case study while making the following operational assumptions:</strong></p><ul><li>Additional EV infrastructure promotes higher rates of EV adoption</li><li>We can define the quality of a candidate location for a PCS by analyzing the demand for that location i.e. <em>How often, and how many vehicles visit?</em></li><li>The supplier building the charging stations is budget conscious and won’t build at every recommended location, so wants to select only the optimal ones.</li></ul><p>The 99P Labs developer portal has a telematics data service that provides geo-spatial timeseries data that is enriched with additional attributes relevant for our problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5qIvWDFTrZXqaz08f8hcA.png" /></figure><p>The volume of data can approach a half billion records with ~200 attributes for the 30 days we planned to use as our case study window, therefore we developed a method that would send a parameterized request to the API such that it only returned a few minutes of data which would be easy to search and operate on. We then would request data from the API again, this time for the <strong><em>next</em></strong> few minutes of data.</p><p>With each returned response, we performed our computations and stored the results in a document database. This method of <strong><em>iterative aggregation </em></strong>allowed us to touch every record of data available, while not overwhelming our resources in doing so. This did mean that getting the full span of data over 30 days required some long running API calls. However, we only needed a small sliver of that to begin development on the next stages of the study.</p><h3>— Candidate Location Identification —</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6aj5GSlX9RJlkne0irzng.jpeg" /><figcaption>Dubai Long Exposure | Credit: <a href="https://pixabay.com/users/martinschuschi-5260235/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2292779">Martinschuschi</a> from <a href="https://pixabay.com/photos/dubai-skyline-city-architecture-2292779/">Pixabay</a>|</figcaption></figure><p><strong>The above image shows the Dubai skyline at night, rising up out of the streets shimmering with speeding cars.</strong> Photographic long exposure works when the camera opens its mechanical or electronic shutter over an extended period of time allowing the sensor to capture a composition of light representing a period of time instead of a single snapshot.</p><p>Combining this with static frame control, usually achieved by setting the camera steady on a tripod, the resulting effect for vehicles moving at high speeds is for the sensor to only retain the most intense light readings which tend to be the headlights and tail lights of a moving car. The rest gets washed out as light continues to be collected.</p><p><strong>This process is analogous to how we approached identifying candidate locations. </strong>Any single snapshot wouldn’t contain the latent patterns we were trying to discover. So we approached this with a method, that considered an extended period of time, and allowed the aggregate intensity of the phenomena we were observing to be collected and the noise to be washed out in relation.</p><p><strong>To achieve this we proceeded with using a density based clustering algorithm called </strong><a href="https://www.aaai.org/Papers/KDD/1996/KDD96-037.pdf"><strong>DBSCAN</strong></a><strong>.</strong> This procedure clustered our observations of where vehicles in the dataset were arriving and like photographic long exposure, it was able to surface patterns of intensity while washing out noise. These clusters became our candidate locations.</p><p>Below on the left are all the raw destinations collected through the iterative aggregation method. The purple points representing a vehicle arrival at the destination. On the right is the output from the DBSCAN, the clusters that were identified on the basis of density.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TeyCBkQq8NguP8JhMSLAA.png" /><figcaption><strong>Left:</strong> Raw destinations collected via iterative aggregation |<strong> Right: </strong>Visualized output of density based clustering | Credit: Author |</figcaption></figure><p>Below is a gif of zooming into a single cluster to show that these clusters are found on the basis of density, and can identify arbitrary shapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*DcWjkthAQpNxygnpLaftzw.gif" /><figcaption>Cluster Example, Hospital next to Kroger and Restaurant plaza identified as a location</figcaption></figure><h3>— Cluster Feature Engineering —</h3><blockquote><strong><em>The telematics API, contains a wealth of information and if a problem can be formulated with discipline and logic, then it can behave as a surrogate for some rich insights.</em></strong></blockquote><p>From the output of the previous stage, we were now able to merge a vector of computed cluster labels into the data set of observations. This provides a meaningful grouping variable to then aggregate over and define additional features that help differentiate between the quality, and ultimately, the utility of the identified candidate locations.</p><h4>The M/M/∞ Model</h4><p>Along with the destinations, we were also able to extract timestamps for vehicle trips from the API. This allowed us to evaluate a trip not only where it ended, but also what time the trip started and ended. By comparing sequential trips for a given vehicle we were able to calculate how long a vehicle stayed at a destination by the timestamps.</p><p>The developer portal telematics API protects the anonymity of vehicles by encrypting the vehicle identification number (<strong>VIN</strong>), however, it sustains this field as a valuable research attribute by preserving its uniqueness.</p><p>With this level of granularity we were able to precisely calculate, for every identified location, what the frequency of arrivals, and the dwell time was at each location.</p><p>Borrowing from queuing theory, we leveraged the <strong><em>M/M/∞</em></strong> model and were able to use the arrival behavior and the dwell time behavior to generate an expected number of vehicles that would be at any of the candidate locations at any given time.</p><h4>Diversity</h4><p>The second engineered feature was <strong><em>Diversity</em></strong><em>.</em> It simply represented the ratio of unique visitors to total visitors at a cluster. The primary purpose of incorporating this term as a factor was that it cleansed irregular data, where an instance of a cluster was formed by a small number of vehicles and large number of observations, such that it qualified as a cluster. There were a few instances that behaved like this, such as apartment blocks and neighborhoods. The diversity factor helped dampen such irregularities.</p><p>The secondary purpose was that our goal was to improve EV adoption, and selecting locations that represented a wider audience, meant that any potential EV infrastructure would get more visibility at those locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*MDjLg4ocFcNZnEs5p3TYIw.gif" /><figcaption>Example of two identified candidate locations and their respective computed features</figcaption></figure><h3>— Selection Optimization —</h3><p>At this stage we have all the raw observations labeled by cluster group, and those that were labeled as noise have been removed. Furthermore, we have calculated <strong>utility </strong>for each cluster in a manner that represents its demand. From this, to calculate the optimized selections we treat each cluster as a node in an undirected fully connected graph.</p><p>However, we did not want to evaluate the value of the nodes independently, but rather consider both their utility as well as their relative distance to other node placements in the network. So what we were scoring in this optimization was a specific selection configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*xy3-ConLx_QPI34VL5Pl8w.png" /><figcaption>Diagram of clusters treated as nodes in fully connected graph | Credit: Author |</figcaption></figure><p>Furthermore, although the data was not available in this study, a cost constant is included that serves as a place holder within the objective function formulation. So if and when more granular installation cost information can be acquired, it can be input into the objective function as a variable in the optimization.</p><p>We formulate our linear integer optimization as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*6Aai7aRY2NpiQBN3tpNkYw.png" /></figure><p>The <strong>Dispersion Constant </strong>was used as a constraint for the solution so<strong> </strong>that nodes wouldn’t be selected in such a manner that they were bunched up together. We set this value to be roughly 1/3 of the diameter of the case study area.</p><p>The <strong>Compression Constant</strong> was used a constraint for the solution so that the average distance between nodes wouldn’t spread above a certain value in any configuration. The way we decided to input the compression constant was to take the average EV range from models available for retail in the U.S.</p><h3>— Evaluation and Experiments —</h3><h4>Comparison</h4><p>To evaluate the efficacy of the methodology one experiment that we ran was to compare the output from our study with the existing placements as retrieved from <a href="https://www.plugshare.com/">PlugShare</a>.</p><p>The thought process was that even though the granularity and ground truth that our data provides is not available to the charging station suppliers, the existing placements should roughly converge to the intuitive notion of placing stations at popular destinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*OPQRSAmJqtXk3jMoYopaXQ.png" /><figcaption>Left: Identified Candidate Locations from our study | Right: Existing placements recorded on PlugShare |Credit: Author|</figcaption></figure><p>We concluded it would not be meaningful to quantify the similarity of these distributions because we are not aiming to predict the locations of charging stations, and the underlying generative mechanisms are different. Whereas we simply look at destination demand density, the Plug- Share data contains many charging stations that are built as amenities for a facility such as at a hotel, rather than demand satisfying infrastructure. In broad strokes however, it’s evident looking at the above visualization that our candidate location identifying procedure seems to be capturing the phenomena we intended it to.</p><h4>Inspection</h4><p>Additionally we manually inspected the locations that were selected during the optimization stage. Below is an example of a selected cluster. This is a plaza area near down town Columbus, near the Ohio State University.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGb5M5czwo-zb3nHO9ej-Q.png" /></figure><p>We manually inspected every candidate location and optimized selection. Applying the criterion that a location was <strong>reasonable</strong> if it was a public place with two or more points of interest nearby. This means that apartment blocks would be evaluated as unreasonable.</p><p>Using this criterion, we decided to judge accuracy as the proportion of reasonable candidate locations to all candidate locations from the density clustering stage. We found this to be <strong>94%</strong> accurate.</p><p>For our selection optimization we ran a hypothetical scenario where the party building the public charging stations only had budget for 15 charging stations. From our selected 15 charging stations we found <strong>100%</strong> of them to be accurate.</p><h3>— Discussion and Future Work —</h3><p>It’s important to highlight, that while we are deriving an optimal solution, the feature space for that solution exists by the attributes we selected. Our selection was driven on the basis of logic and queuing theory but is also limited by data availability.</p><p>Both the unsupervised learning method and the optimization are deterministic, so our results do represent a fully converged optimal solution, but we concede that a truly global solution would also require information regarding the cost of installations as these can vary based on location, whether a transformer is needed, whether a new power line is needed and more.</p><p>This is why we included the cost constant in our formulation, because at a mathematical level setting the cost to be constant across all decision variables just means it is essentially ignored, however it is there to suggest that the framework we have created can and should be improved upon.</p><blockquote><strong><em>There remains a wealth of opportunity still to be investigated and formalized. We believe our study demonstrated a promising methodology for leveraging vehicle telematics data to augment EV infrastructure planning decisions.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67ece277e460" width="1" height="1" alt=""><hr><p><a href="https://medium.com/99p-labs/placement-optimization-of-public-ev-charging-stations-67ece277e460">Placement Optimization of Public EV Charging Stations</a> was originally published in <a href="https://medium.com/99p-labs">99P Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>