<?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 Bedouin on Medium]]></title>
        <description><![CDATA[Stories by Bedouin on Medium]]></description>
        <link>https://medium.com/@bedouin7?source=rss-e364f40f8219------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*re0WP-xKu26EK-NFs8KBPg.png</url>
            <title>Stories by Bedouin on Medium</title>
            <link>https://medium.com/@bedouin7?source=rss-e364f40f8219------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:51:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bedouin7/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[What is DVC?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://bedouin7.medium.com/what-is-dvc-415ae40a0ca5?source=rss-e364f40f8219------2"><img src="https://cdn-images-1.medium.com/max/2112/1*njyeZFUlPjxDUwX85FQ6Ow.jpeg" width="2112"></a></p><p class="medium-feed-snippet">DVC (Data Version Control) is an open-source tool designed to bring Git-like version control and reproducibility to machine learning and&#x2026;</p><p class="medium-feed-link"><a href="https://bedouin7.medium.com/what-is-dvc-415ae40a0ca5?source=rss-e364f40f8219------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://bedouin7.medium.com/what-is-dvc-415ae40a0ca5?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/415ae40a0ca5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 04:41:06 GMT</pubDate>
            <atom:updated>2025-07-20T04:45:19.626Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Tuning — Common methods with Code in Python]]></title>
            <link>https://medium.com/swlh/hyperparameter-tuning-common-methods-with-code-in-python-a7c9935a5cda?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c9935a5cda</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 20:09:48 GMT</pubDate>
            <atom:updated>2023-11-17T20:09:48.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hyperparameter Tuning — Common methods with Code in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMwreszGhnufoq_pBziz0g.jpeg" /></figure><p>Hyperparameter tuning is the process of optimizing the hyperparameters of a machine learning model to achieve better performance. Hyperparameters are configuration settings external to the model itself and are not learned from the data. They are set prior to the training process and influence the learning process of the model.</p><p>Common hyperparameters include - <em>learning rates, regularization strengths, the number of hidden layers in a neural network, or the depth and width of a decision tree</em>. The optimal values for these hyperparameters can significantly impact the model’s predictive accuracy.</p><p>The goal of hyperparameter tuning is to find the hyperparameter values that result in the best performance of the model on a validation dataset. This process is essential because using default or arbitrary hyperparameter values may lead to <em>suboptimal</em> model performance. The search for optimal hyperparameters often involves experimenting with different combinations, evaluating model performance, and adjusting hyperparameter values iteratively.</p><p>Hyperparameter tuning methods include: <em>grid search, random search, Bayesian optimization, genetic algorithms, and more</em>. Grid search systematically tests predefined hyperparameter combinations, while random search randomly samples combinations. Bayesian optimization uses probabilistic models to guide the search efficiently. Genetic algorithms mimic the process of natural selection to evolve a set of hyperparameters.</p><p>Effective hyperparameter tuning requires a balance between exploration and exploitation, considering computational resources, and understanding the characteristics of the machine learning model and dataset. Automated tools and frameworks are often employed to streamline the hyperparameter tuning process, making it more efficient and accessible. Overall, hyperparameter tuning is a crucial step in building robust and high-performing machine learning models.</p><h4>Types of Hyperparameter tuning</h4><p>Hyperparameter tuning is a critical step in optimizing machine learning models. Common methods for hyperparameter tuning include:</p><ol><li><strong>Grid Search:</strong></li></ol><ul><li><strong>Method:</strong> Exhaustively searches a predefined set of hyperparameter values.</li><li><strong>Pros:</strong> Simple, easy to implement, and ensures all combinations are tried.</li><li><strong>Cons:</strong> Computationally expensive for large search spaces.</li><li><strong>Example:</strong> Let’s consider a simple example using Python and scikit-learn for hyperparameter tuning. We’ll use the popular Iris dataset and a Support Vector Machine (SVM) classifier. In this example, we’ll focus on tuning the hyperparameters C (regularization parameter) and gamma (kernel coefficient) using grid search.</li></ul><pre># Import necessary libraries<br>from sklearn import datasets<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.svm import SVC<br><br># Load the Iris dataset<br>iris = datasets.load_iris()<br>X, y = iris.data, iris.target<br><br># Split the dataset 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># Define the SVM classifier<br>svm = SVC()<br><br># Define the hyperparameters to tune and their possible values<br>param_grid = {&#39;C&#39;: [0.1, 1, 10, 100], &#39;gamma&#39;: [0.01, 0.1, 1, 10]}<br><br># Use GridSearchCV to find the best hyperparameters<br>grid_search = GridSearchCV(svm, param_grid, cv=5)<br>grid_search.fit(X_train, y_train)<br><br># Print the best hyperparameters<br>print(&quot;Best Hyperparameters:&quot;, grid_search.best_params_)<br><br># Evaluate the model with the best hyperparameters on the test set<br>best_svm = grid_search.best_estimator_<br>accuracy = best_svm.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set:&quot;, accuracy)</pre><p>In this example, we define an SVM classifier and a grid of hyperparameter values (C and gamma). The GridSearchCV function from scikit-learn performs a cross-validated grid search over the specified hyperparameter values. The best hyperparameters are then printed, and the final model is evaluated on the test set.</p><p>2. <strong>Random Search:</strong></p><ul><li><strong>Method:</strong> Randomly samples hyperparameter values from predefined distributions.</li><li><strong>Pros:</strong> More efficient than grid search, especially for large search spaces.</li><li><strong>Cons:</strong> Might not guarantee optimal hyperparameters, but often finds good ones faster.</li><li><strong>Example: </strong>Let’s extend the previous example to demonstrate hyperparameter tuning using Random Search. We’ll use the RandomizedSearchCV from the scikit-learn library.</li></ul><pre># Import necessary libraries<br>from sklearn.model_selection import RandomizedSearchCV<br>from sklearn.svm import SVC<br><br># ... (Same code to load and split the Iris dataset as in the previous example)<br><br># Define the SVM classifier<br>svm = SVC()<br><br># Define the hyperparameters and their search spaces<br>param_dist = {&#39;C&#39;: [0.1, 1, 10, 100], &#39;gamma&#39;: [0.01, 0.1, 1, 10]}<br><br># Use RandomizedSearchCV for Random Search<br>random_search = RandomizedSearchCV(svm, param_distributions=param_dist, n_iter=10, cv=5, random_state=42)<br>random_search.fit(X_train, y_train)<br><br># Print the best hyperparameters from Random Search<br>print(&quot;Best Hyperparameters (Random Search):&quot;, random_search.best_params_)<br><br># Evaluate the models with the best hyperparameters on the test set<br>best_svm_random = random_search.best_estimator_<br>accuracy_random = best_svm_random.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set (Random Search):&quot;, accuracy_random)</pre><p>3<strong>. Bayesian Optimization:</strong></p><ul><li><strong>Method:</strong> Uses probabilistic models to model the objective function and guides the search towards promising regions.</li><li><strong>Pros:</strong> Efficient in terms of the number of evaluations required, suitable for expensive-to-evaluate functions.</li><li><strong>Cons:</strong> More complex to implement compared to grid and random search.</li><li><strong>Example: </strong>Install scikit-optimize python library:</li></ul><pre>pip install scikit-optimize</pre><p>Let’s extend the previous example to demonstrate hyperparameter tuning using Bayesian Optimization. For Bayesian Optimization, we’ll use the BayesSearchCV from the scikit-optimize library.</p><pre># Import necessary libraries<br>from skopt import BayesSearchCV<br>from sklearn.svm import SVC<br><br># ... (Same code to load and split the Iris dataset as in the previous example)<br><br># Define the SVM classifier<br>svm = SVC()<br><br># Define the hyperparameters and their search spaces<br>param_dist = {&#39;C&#39;: [0.1, 1, 10, 100], &#39;gamma&#39;: [0.01, 0.1, 1, 10]}<br><br># Use BayesSearchCV for Bayesian Optimization<br>bayesian_opt = BayesSearchCV(svm, search_spaces={&#39;C&#39;: (0.1, 100), &#39;gamma&#39;: (0.01, 10)}, n_iter=10, cv=5)<br>bayesian_opt.fit(X_train, y_train)<br><br># Print the best hyperparameters from Bayesian Optimization<br>print(&quot;Best Hyperparameters (Bayesian Optimization):&quot;, bayesian_opt.best_params_)<br><br>best_svm_bayesian = bayesian_opt.best_estimator_<br>accuracy_bayesian = best_svm_bayesian.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set (Bayesian Optimization):&quot;, accuracy_bayesian)</pre><p>In these examples, RandomizedSearchCV is used for random search, and BayesSearchCV from scikit-optimize is used for Bayesian Optimization. Both methods search through the hyperparameter space, and their best hyperparameters are printed and evaluated on the test set. Adjust the number of iterations (n_iter) based on computational resources and search space complexity.</p><p>4<strong>. Gradient-Based Optimization:</strong></p><ul><li><strong>Method:</strong> Utilizes gradient information to iteratively update hyperparameters.</li><li><strong>Pros:</strong> Effective when the objective function is smooth and differentiable.</li><li><strong>Cons:</strong> Limited to differentiable hyperparameters and can get stuck in local minima.</li><li><strong>Example:</strong> Gradient-based optimization involves using gradient information to iteratively update hyperparameters. In this example, we’ll use the hyperopt library, which provides tools for optimization using Tree of Parzen Estimators (TPE), a Bayesian optimization algorithm. First, install the hyperopt library if you haven&#39;t already:</li></ul><pre>pip install hyperopt</pre><p>Now, let’s modify the previous example to demonstrate hyperparameter tuning using gradient-based optimization:</p><pre># Import necessary libraries<br>from hyperopt import fmin, tpe, hp, STATUS_OK, Trials<br>from sklearn.model_selection import cross_val_score<br>from sklearn.svm import SVC<br><br># ... (Same code to load and split the Iris dataset as in the previous examples)<br><br># Define objective function to minimize (negative accuracy)<br>def objective(params):<br>    clf = SVC(C=params[&#39;C&#39;], gamma=params[&#39;gamma&#39;])<br>    score = cross_val_score(clf, X_train, y_train, cv=5).mean()<br>    return {&#39;loss&#39;: -score, &#39;status&#39;: STATUS_OK}<br><br># Define search space for hyperparameters<br>space = {&#39;C&#39;: hp.loguniform(&#39;C&#39;, -3, 2), &#39;gamma&#39;: hp.loguniform(&#39;gamma&#39;, -3, 2)}<br><br># Perform optimization using Tree of Parzen Estimators (TPE)<br>trials = Trials()<br>best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=10, trials=trials)<br><br># Print the best hyperparameters<br>print(&quot;Best Hyperparameters (Gradient-Based Optimization):&quot;, best)<br><br># Evaluate the model with the best hyperparameters on the test set<br>best_svm_gradient = SVC(C=best[&#39;C&#39;], gamma=best[&#39;gamma&#39;])<br>best_svm_gradient.fit(X_train, y_train)<br>accuracy_gradient = best_svm_gradient.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set (Gradient-Based Optimization):&quot;, accuracy_gradient)</pre><p>In this example, the hyperopt library is used to define the objective function, search space for hyperparameters, and perform the optimization using the Tree of Parzen Estimators (TPE) algorithm. The best hyperparameters are printed, and the model is evaluated on the test set. Adjust the number of evaluations (max_evals) based on computational resources.</p><p>5<strong>. Genetic Algorithms:</strong></p><ul><li><strong>Method:</strong> Applies principles of natural selection to evolve a population of potential hyperparameter sets.</li><li><strong>Pros:</strong> Effective for non-continuous search spaces and non-differentiable objective functions.</li><li><strong>Cons:</strong> Computationally intensive, may not always converge to optimal solutions.</li><li><strong>Example:</strong> To perform hyperparameter tuning using genetic algorithms, we can use the deap library in Python. First, install the library:</li></ul><pre>pip install deap</pre><p>Now, let’s modify the previous example to demonstrate hyperparameter tuning using genetic algorithms:</p><pre># Import necessary libraries<br>from deap import base, creator, tools, algorithms<br>from sklearn.model_selection import cross_val_score<br>from sklearn.svm import SVC<br>import random<br><br># ... (Same code to load and split the Iris dataset as in the previous examples)<br><br># Define objective function to maximize (accuracy)<br>def objective(params):<br>    # The &#39;gamma&#39; parameter of SVC must be a str among {&#39;scale&#39;, &#39;auto&#39;} or a float in the range [0.0, inf)<br>    clf = SVC(C=max(0.1, params[0]), gamma=params[1])<br>    score = cross_val_score(clf, X_train, y_train, cv=5).mean()<br>    return score,<br><br># Define genetic algorithm parameters<br>creator.create(&quot;FitnessMax&quot;, base.Fitness, weights=(1.0,))<br>creator.create(&quot;Individual&quot;, list, fitness=creator.FitnessMax)<br><br>toolbox = base.Toolbox()<br>toolbox.register(&quot;attr_float&quot;, random.uniform, 0.1, 10)<br>toolbox.register(&quot;individual&quot;, tools.initRepeat, creator.Individual, toolbox.attr_float, n=2)<br>toolbox.register(&quot;population&quot;, tools.initRepeat, list, toolbox.individual)<br><br>toolbox.register(&quot;evaluate&quot;, objective)<br>toolbox.register(&quot;mate&quot;, tools.cxBlend, alpha=0.5)<br>toolbox.register(&quot;mutate&quot;, tools.mutGaussian, mu=0, sigma=1, indpb=0.2)<br>toolbox.register(&quot;select&quot;, tools.selTournament, tournsize=3)<br><br># Perform genetic algorithm optimization<br>population = toolbox.population(n=10)<br>algorithms.eaMuPlusLambda(population, toolbox, mu=10, lambda_=50, cxpb=0.7, mutpb=0.2, ngen=10, stats=None, halloffame=None, verbose=True)<br><br># Print the best individual&#39;s hyperparameters<br>best_individual = tools.selBest(population, k=1)[0]<br>print(&quot;Best Hyperparameters (Genetic Algorithm):&quot;, best_individual)<br><br># Evaluate the model with the best hyperparameters on the test set<br>best_svm_genetic = SVC(C=best_individual[0], gamma=best_individual[1])<br>best_svm_genetic.fit(X_train, y_train)<br>accuracy_genetic = best_svm_genetic.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set (Genetic Algorithm):&quot;, accuracy_genetic)</pre><p>In this example, the deap library is used to define the genetic algorithm&#39;s components, including the creation of individuals and populations, genetic operators (crossover and mutation), and the optimization process. The best individual&#39;s hyperparameters are printed, and the model is evaluated on the test set. Adjust the parameters of the genetic algorithm (mu, lambda_, cxpb, mutpb, ngen, etc.) based on your requirements and computational resources.</p><p>6<strong>. Tree-structured Parzen Estimators (TPE):</strong></p><ul><li><strong>Method:</strong> Models the objective function using a probabilistic model and focuses on regions likely to contain better hyperparameters.</li><li><strong>Pros:</strong> Efficient in high-dimensional spaces and handles categorical parameters well.</li><li><strong>Cons:</strong> May require more tuning of its own parameters.</li><li><strong>Example: </strong>The hyperopt library is used to define the objective function, search space for hyperparameters, and perform optimization using TPE. The best hyperparameters are printed, and the model is evaluated on the test set. Adjust the number of evaluations (max_evals) based on computational resources.</li></ul><p>7<strong>. Hyperband:</strong></p><ul><li><strong>Method:</strong> Divides resources between configurations dynamically, allocating more resources to promising configurations.</li><li><strong>Pros:</strong> Efficient in terms of resource usage, particularly useful for parallel optimization.</li><li><strong>Cons:</strong> Limited to settings with predefined resource budgets.</li><li><strong>Example:</strong> Hyperband is a hyperparameter optimization algorithm that allocates resources dynamically to promising configurations. The hyperband library in Python provides an implementation of the Hyperband algorithm. To use it, you can install the library with:</li></ul><pre>pip install hpbandster-sklearn</pre><p>Now, let’s modify the previous example to demonstrate hyperparameter tuning using Hyperband:</p><pre>from hpbandster_sklearn import HpBandSterSearchCV<br>from sklearn.model_selection import cross_val_score<br>from sklearn.svm import SVC<br><br># ... (Same code to load and split the Iris dataset as in the previous examples)<br><br># Define the hyperparameters to tune and their possible values<br>space = {&#39;C&#39;: [0.1, 1, 10, 100], &#39;gamma&#39;: [0.01, 0.1, 1, 10]}<br><br># Use GridSearchCV to find the best hyperparameters<br>hb_search = HpBandSterSearchCV(svm, space, cv=5, random_state=0, n_jobs=1, n_iter=10, verbose=1, optimizer = &#39;hyperband&#39;)<br>hb_search.fit(X_train, y_train)<br><br># Print the best hyperparameters<br>print(&quot;Best Hyperparameters:&quot;, hb_search.best_params_)<br><br># Evaluate the model with the best hyperparameters on the test set<br>best_svm = SVC(C=hb_search.best_params_[&#39;C&#39;], gamma=hb_search.best_params_[&#39;gamma&#39;])<br>accuracy_hyperband = hb_search.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set:&quot;, accuracy_hyperband)</pre><p>In this example, the hyperband library is used to perform hyperparameter optimization using the Hyperband algorithm. The best hyperparameters are printed, and the model is evaluated on the test set. Adjust the Hyperband parameters (min_budget, max_budget, eta, max_iter) based on your requirements.</p><p>8<strong>. Optuna:</strong></p><ul><li><strong>Method:</strong> An open-source framework for hyperparameter optimization using various algorithms, including TPE and grid search.</li><li><strong>Pros:</strong> Supports distributed optimization, integrates with various machine learning frameworks.</li><li><strong>Cons:</strong> Requires familiarity with the Optuna framework.</li><li><strong>Example:</strong> If you haven’t installed Optuna yet, you can do so with:</li></ul><pre>pip install optuna</pre><p>Now, let’s modify the previous example to demonstrate hyperparameter tuning using Optuna:</p><pre># Import necessary libraries<br>import optuna<br>from sklearn.model_selection import cross_val_score<br>from sklearn.svm import SVC<br><br># ... (Same code to load and split the Iris dataset as in the previous examples)<br><br># Define objective function to minimize (negative accuracy)<br>def objective(trial):<br>    C = trial.suggest_loguniform(&#39;C&#39;, 0.1, 100)<br>    gamma = trial.suggest_loguniform(&#39;gamma&#39;, 0.01, 10)<br><br>    clf = SVC(C=C, gamma=gamma)<br>    score = cross_val_score(clf, X_train, y_train, cv=5).mean()<br>    return -score  # Negative accuracy since Optuna minimizes the objective<br><br># Perform hyperparameter optimization using Optuna<br>study = optuna.create_study(direction=&#39;minimize&#39;)<br>study.optimize(objective, n_trials=10)<br><br># Get the best hyperparameters<br>best_params = study.best_params<br>print(&quot;Best Hyperparameters (Optuna):&quot;, best_params)<br><br># Evaluate the model with the best hyperparameters on the test set<br>best_svm_optuna = SVC(C=best_params[&#39;C&#39;], gamma=best_params[&#39;gamma&#39;])<br>best_svm_optuna.fit(X_train, y_train)<br>accuracy_optuna = best_svm_optuna.score(X_test, y_test)<br>print(&quot;Accuracy on Test Set (Optuna):&quot;, accuracy_optuna)</pre><p>In this example, we use Optuna to define the hyperparameter search space and perform the optimization. The best hyperparameters are printed, and the model is evaluated on the test set. You can adjust the number of trials (n_trials) based on your computational resources. Optuna supports various search spaces and optimization algorithms, providing flexibility for different optimization scenarios.</p><h4>Conclusion</h4><p>The choice of method depends on factors such as the size of the search space, available computational resources, and the characteristics of the objective function. Practitioners often experiment with multiple methods to find the most effective approach for their specific scenario.</p><p>In summary, effective hyperparameter tuning is essential for enhancing model generalization and accuracy. As machine learning models become more complex, the importance of robust optimization methods becomes increasingly significant. Researchers and practitioners continue to explore new tools and frameworks to streamline and automate the hyperparameter optimization process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c9935a5cda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/hyperparameter-tuning-common-methods-with-code-in-python-a7c9935a5cda">Hyperparameter Tuning — Common methods with Code in Python</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ETL vs ELT — Extract, Transform, Load]]></title>
            <link>https://medium.com/analytics-vidhya/etl-vs-elt-extract-transform-load-b230461105a9?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/b230461105a9</guid>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 13:33:01 GMT</pubDate>
            <atom:updated>2023-11-17T13:46:12.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>ETL vs ELT — Extract, Transform, Load and how to use it</h3><p><strong>ETL</strong> (Extract, Transform, Load) and <strong>ELT</strong> (Extract, Load, Transform) are two approaches to data integration and processing in the context of data warehousing and business intelligence.</p><p>The ETL and ELT processes are fundamental components in the realm of data integration and management. These processes play a pivotal role in bringing together data from diverse sources, fostering a cohesive and unified view for organizations. ETL, <em>the traditional approach</em>, involves the extraction of data from various sources, its transformation to meet specific requirements, and finally, loading it into a centralized data warehouse or repository. This method is particularly adept at handling complex transformations before the loading phase, ensuring data accuracy and consistency through cleansing and validation.</p><p>In contrast, ELT, <em>a modern approach</em>, extracts data and loads it directly into the target data warehouse before undergoing transformation. This approach capitalizes on the processing power of contemporary cloud-based data warehouses, allowing for efficient handling of large-scale data transformations. <strong>ELT is especially advantageous for real-time or near-real-time analytics</strong>, providing timely insights into the ever-evolving landscape of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HK1E9n3LAORR7Xf0v0EA4g.png" /><figcaption>Image: ETL Process.</figcaption></figure><p>These processes are instrumental in maintaining data quality and cleanliness. ETL processes, during the transformation phase, facilitate intricate data restructuring, aggregations, and calculations to prepare the data for analytical processing. This step is crucial for optimizing storage structures and data retrieval efficiency. Moreover, both ETL and ELT play a vital role in the historical data context, supporting the inclusion of historical information within the transformed data.</p><p>In addition to their technical advantages, these processes address compliance and regulatory requirements by providing mechanisms for data governance and compliance measures. They offer flexibility in tool selection, allowing organizations to choose tools tailored to their specific needs at each stage of the process. Ultimately, the choice between ETL and ELT hinges on factors such as data volume, processing capabilities, and the overall architecture of the data infrastructure. Both processes are indispensable for ensuring data integrity and supporting data-driven decision-making in today’s dynamic and data-rich environments.</p><h4>ETL (Extract, Transform, Load)</h4><ul><li><strong>Extract:</strong> In the ETL process, data is first extracted from source systems. This involves retrieving data from various sources such as databases, applications, or flat files.</li><li><strong>Transform:</strong> Once extracted, the data undergoes transformation. Transformation involves cleaning, filtering, aggregating, and restructuring the data to meet the requirements of the target system or data warehouse. This step may also include data enrichment, validation, and the application of business rules.</li><li><strong>Load: </strong>Finally, the transformed data is loaded into the target data warehouse or database. This is where the data becomes available for analysis and reporting.</li></ul><p>ETL follows a sequential order where data is extracted, transformed, and then loaded into the destination.</p><h4>ELT (Extract, Load, Transform)</h4><ul><li><strong>Extract:</strong> Similar to ETL, ELT starts with extracting data from source systems.</li><li><strong>Load:</strong> After extraction, the data is directly loaded into the target data warehouse or database without significant transformation. The raw data is stored in its original state.</li><li><strong>Transform:</strong> Once the data is loaded into the destination, transformations are applied within the data warehouse itself. This often involves using the processing power of the destination system to perform complex transformations and analytics.</li></ul><p>ELT differs from ETL in that the transformation step occurs after the data is loaded into the target system.</p><h4>Key Differences:</h4><p><strong>ETL Pros:</strong><br> — Transformation happens before loading, allowing for clean and organized data in the data warehouse.<br> — Suited for scenarios where the source data needs significant cleansing and transformation.</p><p><strong>ELT Pros:</strong><br> — Takes advantage of the processing power of modern data warehouses, enabling high-performance transformations.<br> — Well-suited for big data scenarios where loading raw data first and then transforming it can be more efficient.</p><h4>Choosing Between ETL and ELT:</h4><p>- Choose ETL when data transformation is complex, requires cleaning, and needs to be organized before loading into the data warehouse.<br>- Choose ELT when the data warehouse has powerful processing capabilities, and the transformation can be efficiently handled after the data is loaded.</p><p>Ultimately, the choice between ETL and ELT depends on factors like the nature of the data, processing requirements, and the capabilities of the target data warehouse or database.</p><h4>Tools</h4><p>Both ETL and ELT processes can be implemented using a variety of tools, and the choice often depends on the specific requirements, the nature of the data, and the existing technology stack. Here are examples of tools for both ETL and ELT:</p><h3>ETL Tools:</h3><ol><li><strong>Apache NiFi:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*E8hSi_TZZ8wQws8w9_WL2A.png" /></figure><p><a href="https://nifi.apache.org/">Apache NiFi</a> is an open-source ETL tool that provides a web-based interface for designing data flows. It supports the extraction, transformation, and loading of data from various sources to different destinations.</p><p>2. <strong>Talend:</strong></p><p><a href="https://www.talend.com/">Talend</a> is a popular open-source ETL tool with a user-friendly interface. It supports a wide range of data integration tasks and can connect to various data sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*oJHw6VGDdiNMSZVx5Ujb8g.png" /></figure><p>3. <strong>Apache Spark:</strong></p><p>While <a href="https://spark.apache.org/">Spark</a> is a powerful distributed computing framework, it includes components like Spark SQL and DataFrames that can be used for ETL tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*zg5jmMHiLfuRBKBMUcIdKg.png" /></figure><pre># PySpark example (Python)<br>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&quot;ETLExample&quot;).getOrCreate()<br><br># Load data, perform transformations, and save the result<br>df = spark.read.csv(&quot;input.csv&quot;, header=True)<br>transformed_df = df.filter(df[&quot;column&quot;] &gt; 10)<br>transformed_df.write.parquet(&quot;output.parquet&quot;)</pre><h3>ELT Tools:</h3><ol><li><strong>Amazon Redshift:<br></strong><a href="https://aws.amazon.com/redshift/">Amazon Redshift</a> is a managed data warehouse service that supports ELT workflows. You can load raw data into Redshift and then perform transformations using SQL queries within the database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XE8V1TbleEHrvXia.png" /></figure><pre>-- Amazon Redshift example (SQL)<br>COPY raw_data FROM &#39;s3://your_bucket/raw_data.csv&#39; DELIMITER &#39;,&#39; CSV;<br>UPDATE raw_data SET column = column * 2 WHERE condition;</pre><p>2. <strong>Snowflake:<br></strong><a href="https://www.snowflake.com/en/">Snowflake</a> is a cloud-based data warehousing platform that supports ELT. Similar to Redshift, you can load data into Snowflake and perform transformations using SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sODshsesM1EfmVvl.png" /></figure><pre>-- Snowflake example (SQL)<br>COPY INTO raw_data FROM @stage/raw_data.csv FILE_FORMAT=(TYPE=CSV);<br>UPDATE raw_data SET column = column * 2 WHERE condition;</pre><p>3. <strong>Google BigQuery:<br></strong><a href="https://cloud.google.com/bigquery">Google BigQuery</a> is a serverless, highly-scalable data warehouse that supports ELT. You can load data into BigQuery and then use SQL for transformations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*D1wRwpfFKX5e4hAW.png" /></figure><pre>-- Google BigQuery example (SQL)<br>INSERT INTO dataset.raw_data (column1, column2)<br>SELECT column1 * 2, column2 FROM dataset.raw_data WHERE condition;</pre><p>These are just a few examples, and there are many other ETL and ELT tools available, both open-source and commercial. The choice depends on your specific use case, data volume, and integration requirements.</p><h4>Web Scraping and ETL</h4><p>There are several tools that can be used for both web scraping and ETL (Extract, Transform, Load) processes. Here are a few examples:</p><ol><li><strong>Apache Nifi:</strong></li></ol><ul><li><strong>Web Scraping:</strong> While <a href="https://nifi.apache.org/">NiFi</a> is primarily known as an ETL tool, it has processors that can be used for web scraping. You can use processors like GetHTTP or InvokeHTTP to fetch web pages.</li><li><strong>ETL:</strong> Apache NiFi excels in designing data flows for ETL tasks. It provides a visual interface to design data flows, making it easy to integrate web scraping and subsequent data processing.</li></ul><p>2. <strong>Apache Spark:</strong></p><ul><li><strong>Web Scraping:</strong> <a href="https://spark.apache.org/">Spark</a> itself is not designed for web scraping, but you can use libraries like Beautiful Soup or Scrapy along with Spark to combine web scraping and ETL.</li><li><strong>ETL:</strong> Apache Spark is a powerful distributed computing framework that includes components like Spark SQL and DataFrames for ETL tasks. You can load, transform, and process data efficiently.</li></ul><p>3.<strong> Scrapy:</strong></p><ul><li><strong>Web Scraping:</strong> <a href="https://scrapy.org/">Scrapy</a> is a dedicated Python framework for web scraping. It allows you to define spiders to crawl websites and extract data.</li><li><strong>ETL:</strong> Once data is scraped using Scrapy, you can use Python libraries like Pandas for further data transformation and then load it into your preferred database.</li></ul><p>4. <strong>Selenium:</strong></p><ul><li><strong>Web Scraping:</strong> <a href="https://www.selenium.dev/">Selenium</a> is commonly used for web automation, making it useful for scraping dynamic websites. It can interact with JavaScript-based content.</li><li><strong>ETL:</strong> After scraping data with Selenium, you can use other ETL tools or libraries to process and load the data.</li></ul><p>5. <strong>Octoparse:</strong></p><ul><li><strong>Web Scraping:</strong> <a href="https://www.octoparse.com/">Octoparse</a> is a visual web scraping tool that allows you to point-and-click to define scraping tasks.</li><li><strong>ETL:</strong> Octoparse includes features for data cleaning and transformation within its interface, making it suitable for simple ETL tasks.</li></ul><p>Remember, the choice of the tool depends on your specific requirements, the complexity of the web scraping tasks, and the nature of the ETL processes you need to perform. Additionally, always ensure that your web scraping activities comply with the terms of service of the websites you are scraping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b230461105a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/etl-vs-elt-extract-transform-load-b230461105a9">ETL vs ELT — Extract, Transform, Load</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas — Quick Lookup]]></title>
            <link>https://python.plainenglish.io/pandas-quick-lookup-5d84fa9c62a2?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d84fa9c62a2</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 18:50:34 GMT</pubDate>
            <atom:updated>2023-11-08T01:50:24.725Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas — Quick Lookup | Data Science | Data Analytics</h3><p><strong>Pandas</strong> is an open-source data manipulation and analysis library for the Python programming language. It provides easy-to-use data structures and functions for working with structured data, such as spreadsheets, tables, and time-series data. Pandas is built on top of the NumPy library and is widely used for data cleaning, data transformation, data exploration, and data analysis in a variety of domains, including data science, machine learning, and finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*yOq6dlUa_hGf920e.png" /></figure><p>Here’s why Pandas is important:</p><ol><li><strong>Data Handling:</strong> Pandas simplifies the process of loading, manipulating, and transforming data. It provides data structures like DataFrames and Series that allow users to work with tabular and time-series data efficiently.</li><li><strong>Data Cleaning:</strong> One of the first steps in any data analysis project is data cleaning. Pandas provides powerful tools for handling missing data, removing duplicates, and dealing with outliers.</li><li><strong>Data Transformation:</strong> Pandas makes it easy to reshape and transform data. You can pivot, melt, and aggregate data with just a few lines of code. This is crucial for preparing data for analysis or feeding it into machine learning models.</li><li><strong>Data Exploration:</strong> You can quickly summarize and explore your data using Pandas. It offers functions for calculating statistics, creating plots, and understanding the distribution of data.</li><li><strong>Time Series Data:</strong> Time-series data, commonly encountered in finance, economics, and IoT, is well-supported in Pandas. It includes tools for resampling, date shifting, and handling time zones.</li><li><strong>Integration:</strong> Pandas integrates seamlessly with other Python libraries and tools. It can read data from various file formats, including CSV, Excel, SQL databases, and more. It also plays a crucial role in the data science ecosystem, working alongside libraries like NumPy, Matplotlib, and scikit-learn.</li><li><strong>Flexibility and Productivity:</strong> Pandas provides a high-level, expressive API that allows you to perform complex operations with minimal code. This boosts productivity and makes it easy for analysts and data scientists to work with data effectively.</li><li><strong>Community and Ecosystem:</strong> Pandas has a large and active user community, which means there is a wealth of resources, tutorials, and third-party libraries available. This helps users solve specific data manipulation and analysis challenges.</li></ol><p>In summary, Pandas is important because it provides a powerful and user-friendly toolset for data manipulation and analysis. It simplifies the process of working with structured data, making it accessible to a broad range of users, from beginners to experienced data professionals. Whether you are cleaning, exploring, or analyzing data, Pandas is an invaluable library in the Python data science toolkit.</p><p><em>Let’s have a look at it’s useful functions &amp; save the article for future quick reference.</em></p><h4>DataFrame</h4><p><strong>DataFrame</strong> and <strong>Series</strong> are fundamental data structures for handling and manipulating structured data.</p><p>A DataFrame is a two-dimensional, size-mutable, and heterogeneous tabular data structure. It can be thought of as a table in a relational database or an Excel spreadsheet.</p><p>DataFrames have rows and columns, and each column can contain data of different types (e.g., integers, floats, strings). DataFrames are commonly used for storing and analyzing structured data, such as datasets, spreadsheets, and CSV files. They provide powerful tools for data cleaning, data transformation, and data analysis.</p><ul><li>pd.<strong>DataFrame</strong>() — Create a new DataFrame</li></ul><pre>import pandas as pd<br><br>df = pd.DataFrame({&#39;A&#39;: [1,2,3], &#39;B&#39;: [4,5,6]})</pre><pre>data = {&#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;],<br>        &#39;Age&#39;: [25, 30, 35],<br>        &#39;City&#39;: [&#39;New York&#39;, &#39;San Francisco&#39;, &#39;Los Angeles&#39;]}<br>df = pd.DataFrame(data)</pre><ul><li>df.<strong>head</strong>() — Return the first n rows of the DataFrame</li></ul><pre>df.head(5)</pre><ul><li>df.<strong>tail</strong>() — Return the last n rows of the DataFrame</li></ul><pre>df.tail(3)</pre><ul><li>df.<strong>info</strong>() — Print a concise summary of the DataFrame</li></ul><pre>df.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 6 entries, 0 to 5<br>Data columns (total 2 columns):<br> #   Column  Non-Null Count  Dtype<br>---  ------  --------------  -----<br> 0   A       6 non-null      int64<br> 1   B       6 non-null      int64<br>dtypes: int64(2)<br>memory usage: 224.0 bytes</pre><ul><li>df.<strong>describe</strong>() — Generate descriptive statistics of the DataFrame</li></ul><pre>df.describe()</pre><ul><li>df.<strong>columns — </strong>Return the column labels of the DataFrame</li></ul><pre>df.columns</pre><ul><li>df.<strong>shape — </strong>Return the dimensions of the DataFrame</li></ul><pre>df.shape</pre><h4>Series</h4><p>A Series is a one-dimensional array-like object in Pandas. It can be thought of as a single column of data within a DataFrame.</p><p>Series are designed to hold data of a single data type, such as integers, floats, or strings. They are often used to represent and manipulate a single variable or attribute within a dataset.</p><ul><li>pd.<strong>Series</strong>() — Create a new Series</li></ul><pre>s = pd.Series([1, 2, 3, 4])</pre><ul><li>s.<strong>value_counts</strong>() — Count unique values in a Series</li></ul><pre>s.value_counts()</pre><ul><li>s.<strong>unique</strong>() — Return unique values of the Series</li></ul><pre>s.unique()</pre><ul><li>s.<strong>nlargest</strong>() — Return the n largest elements in the Series</li></ul><pre>s.nlargest(3)</pre><ul><li>s.<strong>nsmallest</strong>() — Return the n smallest elements in the Series</li></ul><pre>s.nsmallest(2)</pre><ul><li>s.<strong>values — </strong>Return the values of a Series as a NumPy array</li></ul><pre>s.values</pre><h4>File Read / Write</h4><ul><li>pd.<strong>read_csv</strong>() — Read a CSV file into a DataFrame</li></ul><pre>df = pd.read_csv(&#39;data.csv&#39;)</pre><ul><li>pd.<strong>to_csv</strong>() — Write a DataFrame to a CSV file</li></ul><pre>df.to_csv(&#39;output.csv&#39;, index=False)</pre><ul><li>pd.<strong>read_excel</strong>() — Read an Excel file into a DataFrame</li></ul><pre>df = pd.read_excel(&#39;dat.xlsx&#39;)</pre><ul><li>pd.<strong>to_excel</strong>() — Write a DataFrame to an Excel file</li></ul><pre>df.to_excel(&#39;output.xlsx&#39;, index=False)</pre><ul><li>pd.<strong>read_json</strong>() — Read a JSON file into a DataFrame</li></ul><pre>df = pd.read_json(&#39;data.json&#39;)</pre><ul><li>pd.<strong>to_json</strong>() — Write a DataFrame to a JSON file</li></ul><pre>df.to_json(&#39;output.json&#39;, orient=&#39;records&#39;)</pre><ul><li>pd.<strong>read_sql</strong>() — Read data from a SQL database into a DataFrame</li></ul><pre>df = pd.read_sql(&#39;SELECT * FROM table&#39;, connection)</pre><ul><li>df.<strong>to_sql</strong>() — Write a DataFrame to a SQL database</li></ul><pre>df.to_sql(&#39;table_name&#39;, connection, if_exists=&#39;replace&#39;)</pre><ul><li>pd.<strong>read_html</strong>() — Read tables from HTML web pages into a list of DataFrames</li></ul><pre>tables = pd.read_html(&#39;http://example.com/data.html&#39;)</pre><h4>Data Manipulation</h4><ul><li>df.<strong>sort_values</strong>() — Sort the DataFrame by one or more columns</li></ul><pre>df.sort_values(by=[&#39;Column1&#39;, &#39;Column2&#39;], ascending=[True, False])</pre><ul><li>df.<strong>fillna</strong>() — Fill missing values with a specified value</li></ul><pre>df.fillna(0)</pre><ul><li>df.<strong>interpolate</strong>() — Interpolate missing values in the DataFrame</li></ul><pre>df.interpolate()</pre><ul><li>df.<strong>rename</strong>() — Rename columns or index of the DataFrame</li></ul><pre>df.rename(columns={&#39;old_name&#39;: &#39;new_name&#39;})</pre><ul><li>df.<strong>pivot_table</strong>() — Create a pivot table from the DataFrame</li></ul><pre>df.pivot_table(index=&#39;A&#39;, columns=&#39;B&#39;, values=&#39;C&#39;, aggfunc=&#39;sum&#39;)</pre><h4>Data Cleaning and Preprocessing</h4><ul><li>df.<strong>drop</strong>() — Remove specified labels from rows or columns</li></ul><pre>df.drop([&#39;Column1&#39;, &#39;Column2&#39;], axis=1)</pre><ul><li>df.<strong>dropna</strong>() — Remove missing values from the DataFrame</li></ul><pre>df.dropna()</pre><ul><li>df.<strong>drop_duplicates</strong>() — Remove duplicate rows based on specified columns</li></ul><pre>df.drop_duplicates(subset=[&#39;Column1&#39;, &#39;Column2&#39;])</pre><ul><li>df.<strong>duplicated</strong>() — Identify and remove duplicate rows</li></ul><pre>df.drop_duplicates(subset=[&#39;Column1&#39;, &#39;Column2&#39;])</pre><ul><li>df.<strong>replace</strong>() — Replace values in the DataFrame</li></ul><pre>df.replace({&#39;old_value&#39;: &#39;new_value&#39;})</pre><h4>Working with Index</h4><ul><li>df.<strong>index — </strong>Return the index labels of the DataFrame</li></ul><pre>df.index</pre><ul><li>df.<strong>set_index</strong>() — Set a column as the DataFrame’s index</li></ul><pre>df.set_index(&#39;Date&#39;)</pre><ul><li>df.<strong>reset_index</strong>() — Reset the index of the DataFrame</li></ul><pre>df.reset_index()</pre><h4>Data Selection and Filtering</h4><ul><li>df.<strong>loc[] — </strong>Access a group of rows and columns by labels</li></ul><pre>df.loc[2:4, [&#39;Column1&#39;, &#39;Column2&#39;]]</pre><ul><li>df.<strong>iloc[] — </strong>Access a group of rows and columns by integer positions</li></ul><pre>df.iloc[2:4, 0:2]</pre><ul><li>df<strong>[condition]- </strong>Filter rows based on a condition</li></ul><pre>df[df[&#39;Age&#39;] &gt; 30]</pre><ul><li>df.<strong>query</strong>() — Filter rows using a query expression</li></ul><pre>df.query(&#39;Age &gt; 30 and Gender == &quot;Male&quot;&#39;)</pre><ul><li>df.<strong>filter</strong>() — Filter DataFrame columns by label or regular expression</li></ul><pre>df.filter(like=&#39;substring&#39;)</pre><ul><li>df.<strong>isin</strong>() — Filter rows with values that exist in a list</li></ul><pre>df[df[&#39;Category&#39;].isin([&#39;A&#39;, &#39;B&#39;])]</pre><h4>String Operations</h4><ul><li>df.str.<strong>split</strong>() — Split strings in a DataFrame column</li></ul><pre>df[&#39;Name&#39;].str.split(&#39; &#39;)</pre><ul><li>df.str.<strong>contains</strong>() — Check if a string contains a substring</li></ul><pre>df[&#39;Description&#39;].str.contains(&#39;keyword&#39;)</pre><ul><li>df.str.<strong>lower</strong>() — Convert strings to lowercase</li></ul><pre>df[&#39;Text&#39;].str.lower()</pre><ul><li>df.str.<strong>upper</strong>() — Convert strings to uppercase</li></ul><pre>df[&#39;Text&#39;].str.upper()</pre><ul><li>df.str.<strong>replace</strong>() — Replace a substring in strings</li></ul><pre>df[&#39;Text&#39;].str.replace(&#39;old&#39;, &#39;new&#39;)</pre><ul><li>df.str.<strong>extract</strong>() — Extract substrings using regular expressions</li></ul><pre>df[&#39;Text&#39;].str.extract(r&#39;(\d+)&#39;)</pre><ul><li>df.str.<strong>strip</strong>() — Strip whitespace from the beginning and end of strings</li></ul><pre>df[&#39;Text&#39;].str.strip()</pre><ul><li>df.str.<strong>contains</strong>() — Check if a string contains a substring</li></ul><pre>df[&#39;Text&#39;].str.contains(&#39;keyword&#39;)</pre><h4>Data Aggregation</h4><ul><li>df.<strong>groupby</strong>() — Group the DataFrame using a specified column</li></ul><pre>grouped = df.groupby(&#39;Category&#39;)</pre><ul><li>df.groupby().<strong>agg</strong>() — Perform multiple aggregation operations on grouped data</li></ul><pre>grouped.agg([&#39;sum&#39;, &#39;mean&#39;, &#39;max&#39;])</pre><h4>Data Visualization</h4><ul><li>df.<strong>plot</strong>() — Create basic plots from DataFrame data</li></ul><pre>df.plot(kind=&#39;line&#39;, x=&#39;A&#39;, y=&#39;B&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ltwJM6lLtlIL4a4uRCjlcw.png" /></figure><ul><li>df.<strong>hist</strong>() — Generate histograms of DataFrame columns</li></ul><pre>df[&#39;A&#39;].hist(bins=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*sDpqrCo-KvYJzg0B_-LsCA.png" /></figure><ul><li>df.<strong>boxplot</strong>() — Create box plots of DataFrame columns</li></ul><pre>df.boxplot(column=[&#39;A&#39;, &#39;B&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*6rHTjOKCwGFP7Jea5pX5Lw.png" /></figure><h3>Time Series Data</h3><ul><li>pd.<strong>to_datetime</strong>() — Convert a column to datetime format</li></ul><pre>df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;])</pre><ul><li>df.<strong>resample</strong>() — Resample time-series data</li></ul><pre>df.resample(&#39;D&#39;).sum()</pre><ul><li>df.<strong>shift</strong>() — Shift the values of a time series</li></ul><pre>df[&#39;Previous_Value&#39;] = df[&#39;Value&#39;].shift(1)</pre><ul><li>df.<strong>rolling</strong>() — Calculate rolling statistics on time series data</li></ul><pre>df[&#39;Rolling_Mean&#39;] = df[&#39;Value&#39;].rolling(window=7).mean()</pre><ul><li>pd.<strong>date_range</strong>() — Generate a date range</li></ul><pre>pd.date_range(start=&#39;2023–01–01&#39;, periods=10, freq=&#39;D&#39;)</pre><ul><li>df.<strong>asfreq</strong>() — Convert time series to a specified frequency</li></ul><pre>df.asfreq(&#39;H&#39;)</pre><ul><li>df.<strong>ewm</strong>() — Exponentially weighted moving average</li></ul><pre>df[&#39;EWMA&#39;] = df[&#39;Value&#39;].ewm(span=5).mean()</pre><h4>Time Zone Handling</h4><ul><li>df.<strong>tz_localize</strong>() — Localize timestamps to a specific time zone</li></ul><pre>df[&#39;Timestamp&#39;].tz_localize(&#39;US/Eastern&#39;)</pre><ul><li>df.<strong>tz_convert</strong>() — Convert timestamps to a different time zone</li></ul><pre>df[&#39;Timestamp&#39;].tz_convert(&#39;Europe/London&#39;)</pre><h4>Merging and Joining Data</h4><ul><li>pd.<strong>concat</strong>() — Concatenate DataFrames along a particular axis</li></ul><pre>concatenated = pd.concat([df1, df2])</pre><ul><li>df.<strong>merge</strong>() — Merge two DataFrames using a common column</li></ul><pre>merged = df1.merge(df2, on=&#39;CommonColumn&#39;)</pre><ul><li>df.<strong>join</strong>() — Join two DataFrames on their indexes</li></ul><pre>joined = df1.join(df2, on=&#39;IndexColumn&#39;)</pre><h4>Data Sampling and Randomization</h4><ul><li>df.<strong>sample</strong>() — Randomly sample rows from the DataFrame</li></ul><pre>df.sample(n=10)</pre><ul><li>df.<strong>shuffle</strong>() — Randomly shuffle the rows of the DataFrame</li></ul><pre>df.sample(frac=1)</pre><h4>Categorical Data</h4><ul><li>df.<strong>astype</strong>() — Change the data type of a column</li></ul><pre>df[&#39;Category&#39;] = df[&#39;Category&#39;].astype(&#39;category&#39;)</pre><ul><li>df.<strong>get_dummies</strong>() — Create dummy variables for categorical data</li></ul><pre>pd.get_dummies(df, columns=[&#39;Category&#39;])</pre><ul><li>df.<strong>cat.codes — </strong>Encode categorical data as integers</li></ul><pre>df[&#39;Category_Code&#39;] = df[&#39;Category&#39;].cat.codes</pre><h4>Reshaping Data</h4><ul><li>pd.<strong>melt</strong>() — Unpivot a DataFrame from wide to long format</li></ul><pre>pd.melt(df, id_vars=[&#39;ID&#39;], value_vars=[&#39;Var1&#39;, &#39;Var2&#39;])</pre><ul><li>pd.<strong>crosstab</strong>() — Create a cross-tabulation of two or more factors</li></ul><pre>pd.crosstab(df[&#39;Category&#39;], df[&#39;Status&#39;])</pre><ul><li>df.<strong>stack</strong>() — Stack the prescribed level(s) from columns to index</li></ul><pre>stacked = df.stack()</pre><ul><li>df.<strong>unstack</strong>() — Unstack (pivot) the DataFrame from index to columns</li></ul><pre>unstacked = df.unstack()</pre><h4>Statistical and Mathematical Functions</h4><ul><li>df.<strong>sum</strong>() — Compute the sum of all columns</li></ul><pre>df.sum()</pre><ul><li>df.<strong>max</strong>() — Find the maximum value in each column</li></ul><pre>df.max()</pre><ul><li>df.<strong>min</strong>() — Find the minimum value in each column</li></ul><pre>df.min()</pre><ul><li>df.<strong>mean</strong>() — Compute the mean of all columns</li></ul><pre>df.mean()</pre><ul><li>df.<strong>std</strong>() — Compute the standard deviation of all columns</li></ul><pre>df.std()</pre><ul><li>df.<strong>corr</strong>() — Compute the correlation matrix</li></ul><pre>df.corr()</pre><ul><li>df.<strong>cov</strong>() — Compute the covariance matrix</li></ul><pre>df.cov()</pre><h4>Custom Functions</h4><ul><li>df.<strong>apply</strong>() — Apply a custom function to each element of a DataFrame</li></ul><pre>df[&#39;Column&#39;].apply(lambda x: x * 2)</pre><ul><li>df.<strong>transform</strong>() — Apply a custom function to each group in a groupby operation</li></ul><pre>df.groupby(&#39;Category&#39;)[&#39;Value&#39;].transform(custom_func)</pre><p>Pandas is an invaluable tool for anyone working with data in Python. Whether you’re a data scientist, analyst, engineer, or researcher, Pandas simplifies the process of data manipulation, exploration, and analysis. Its data structures, DataFrames, and Series make it easy to work with structured data, while its extensive library of functions and methods provides a powerful toolkit for a wide range of data tasks. It is the bridge that connects raw data to meaningful insights, and this quick lookup reference is a handy guide to navigate this essential data manipulation library effectively.</p><p><strong><em>References:</em></strong></p><ol><li><a href="https://pandas.pydata.org/docs/">https://pandas.pydata.org/docs</a></li></ol><p><strong><em>Read More Articles:</em></strong></p><ul><li><a href="https://bedouin7.medium.com/sql-structured-query-language-855a8dfb1da0">SQL — Structured Query Language</a></li><li><a href="https://ai.plainenglish.io/exploratory-data-analysis-eda-with-python-matplotlib-bb784e1d3dd3">Exploratory Data Analysis (EDA) with Python &amp; Matplotlib</a></li><li><a href="https://ai.plainenglish.io/python-concepts-for-interview-ffeae5c357f1">Python concepts for Interview</a></li><li><a href="https://bedouin7.medium.com/useful-python-code-snippets-3aaf47e04d1b">Useful Python Code Snippets</a></li><li><a href="https://bedouin7.medium.com/a-travelers-diary-on-the-road-to-machine-learning-chapter-1-8850ec5b4243">A Traveler’s Diary on the Road to Machine Learning — Chapter 1</a></li></ul><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d84fa9c62a2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/pandas-quick-lookup-5d84fa9c62a2">Pandas — Quick Lookup</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ImageNet & the rise of Deep Neural Network Architectures for Image Classification — AlexNet…]]></title>
            <link>https://ai.plainenglish.io/imagenet-the-rise-of-deep-neural-network-architectures-for-image-classification-alexnet-713df0500e7f?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/713df0500e7f</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 20:44:20 GMT</pubDate>
            <atom:updated>2022-12-19T12:39:08.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>ImageNet &amp; the rise of Deep Neural Network Architectures for Image Classification — AlexNet, Inception, VGG, ResNet, ViT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_nLq9XiBUfPCdN1vOM5Zw.png" /></figure><h4>Backstory</h4><p>The exciting journey of modern deep learning networks started with <strong>Prof. </strong><a href="https://en.wikipedia.org/wiki/Fei-Fei_Li"><strong>Fei-Fei Li</strong></a>, who was back then a newly joined computer science professor at the University of Illinois Urbana-Champaign. She had an idea to redefine the world of datasets. She realized that the best algorithm would not work well if the data it learned from did not reflect the real world. “We’re going to map out the entire world of objects,” she said.</p><p>She was inspired by <a href="https://en.wikipedia.org/wiki/WordNet">WordNet</a> (a lexical database developed by Princeton psychologist George Miller with 155k words from more than 200 languages, in mid 1980) and wanted to build something similar for images and named it <strong>ImageNet</strong>. She started working on the project in early 2007. She and her two Ph.D. students (<a href="https://scholar.google.com/citations?user=U3Eub-EAAAAJ">Jia Deng</a> and <a href="https://scholar.google.com/citations?user=TB5OwW8AAAAJ">Olga Russakovsky</a>) used Amazon Mechanical Turk to collect and label with WordNet 3.2 million images, separated into 5,247 categories (synsets), on average over 600 images per synset, sorted into 12 subtrees (i.e. mammal, bird, fish, reptile, amphibian, vehicle, furniture, musical instrument, geological formation, tool, flower, fruit) in just 2.5 years. The main aim of the dataset was to be used in the fields of object recognition, image classification and object localization. <a href="https://image-net.org/static_files/papers/imagenet_cvpr09.pdf">ImageNet paper</a> was published in 2009.</p><p>Prof. Li worked as the Chief Scientist of AI/ML (Vice President) for Google (2017–18), a member of the Board of Directors in Twitter (2020–2022) and Sequoia Professor of computer science department at the Stanford University since 2009.</p><h3>ILSVRC (ImageNet Large Scale Visual Recognition Challenge, 2010–17)</h3><p>Prof. Li approached <a href="http://host.robots.ox.ac.uk/pascal/VOC/"><strong>PASCAL VOC</strong></a>, which was a well-known image recognition competition in Europe (2005–12). They agreed to collaborate with ImageNet and ILSVRC started from 2010 as an yearly competition till 2017. The PASCAL challenge only had 20 categories whereas ILSVRC used a smaller version of ImageNet with 1,000 categories of 1.28 million training images and evaluated on the 50k validation images. It became the benchmark for image classification and localization.</p><p>The first winner of ILSVRC in May 2010 was a <strong>Descriptor Coding + SVM</strong> model by team NEC Laboratories America-University of Illinois Urbana-Champaign, USA. Their classification cost was 0.28. This method performed poorly on some categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o1Jd038zqm8ElT1iDgLzA.png" /><figcaption>Fig.1. Fisher kernel + SVM model.</figcaption></figure><p>The honorable mention was <strong>Fisher kernel + SVM</strong> by Xerox Research Centre Europe (XRCE), France. Their classification cost was 0.34.</p><p>In the <a href="https://image-net.org/challenges/LSVRC/2011/index.php">next challenge</a> in 2011, XRCE won in classification task with <strong>Compressed Fisher vectors </strong>with classification cost 0.26. University of Amsterdam &amp; University of Trento won detection task with <strong>Segmentation as Selective Search </strong>having<strong> </strong>a flat cost 0.425.</p><p>Something even bigger happened in 2012, just after two years of the first ImageNet competition. If the extra-ordinary artificial intelligence boom we see today could be attributed to a single incident, it would be the announcement of the 2012 ImageNet challenge results. Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton from the University of Toronto submitted a deep CNN architecture called <a href="https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf"><strong>AlexNet</strong></a> which still used in research to this day — achieved a winning top-5 test error rate of massive 15.3%, compared to 26.2% by the second-best entry.</p><blockquote>ImageNet and ILSVRC inspired a whole new generation of Image Classification deep neural network architectures. In this article, we will try to look at some popular ones of the past &amp; current state-of-the-art.</blockquote><h3>LeNet (1989–98)</h3><p>Before we talk about AlexNet, let’s take a look at LeNet. This CNN model was proposed by <a href="https://en.wikipedia.org/wiki/Yann_LeCun">Yann LeCun</a> et al. in 1989 and named after <strong>Le</strong>Cun. LeNet usually refers to <a href="http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf">LeNet-5</a> which was published in 1998.</p><ul><li>Input size: 32×32×1</li><li>Number of layers: 7</li><li>Output:1 of 10 classes.</li><li>LeNet-1 first implements <strong>backpropagation</strong>.</li><li>LeNet-5 utilizes two major types of Layers: <em>Convolutional</em> Layers and <em>Subsampling</em> Layers. The <strong>subsampling layer</strong> applies <strong><em>Average Pooling</em></strong> to reduce the dimensionality and <strong><em>tanh</em></strong> activation function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3d8Fz7EBpkjw69vFpHvdGg.png" /><figcaption>Fig.2. Architecture of LeNet-5, a Convolutional Neural Network, here for digits recognition. Each plane is a feature map, i.e. a set of units whose weights are constrained to be identical.</figcaption></figure><h4>Implementation:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd38a6fbba4bf69a79a508925c4b378f/href">https://medium.com/media/cd38a6fbba4bf69a79a508925c4b378f/href</a></iframe><p>LeNet gives very good accuracy on the MNIST hand written image dataset.</p><h3>AlexNet (2012)</h3><p>This is a better and deeper version of LeNet. <a href="https://doi.org/10.1145/3065386">AlexNet</a> was the winning model on ILSVRC 2012 by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton from the University of Toronto, named after <strong>Alex</strong> Krizhevsky. It is considered one of the most influential papers published in computer vision.</p><ul><li>Input size: 224×224×3</li><li>Number of layers: 8</li><li>Output:1 of 1,000 classes</li><li>AlexNet uses <strong><em>ReLU</em></strong><em> </em>activation</li><li><strong>Reduces overfitting with <em>Data Augmentation</em> and <em>Dropout</em> (50%)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TZzN-OMXNeJmbiNg1QBKA.png" /><figcaption>Fig.3. LeNet &amp; AlexNet Deep Neural Network.</figcaption></figure><h4>Implementation:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81f8de2f4f576779f49365a5c15bdc42/href">https://medium.com/media/81f8de2f4f576779f49365a5c15bdc42/href</a></iframe><h3>ZFNet (2013)</h3><p>Published by Matthew D. <strong>Z</strong>eiler and Rob <strong>F</strong>ergus from New York University, hence the name <a href="https://arxiv.org/abs/1311.2901v3">ZFNet,</a> won the ILSVRC in 2013.</p><ul><li>Input size: 224×224×3</li><li>Number of layers: 8</li><li>Output:1 of C classes</li><li>All filters and feature maps are square in shape.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwFK-6hJMNTopG7zlec_LQ.png" /><figcaption>Fig.4. ZFNet Network.</figcaption></figure><p>ZFNet uses a technique called <strong>contrast normalized</strong> across feature maps. Local contrast normalization (LCN) is used to normalize the contrast of an image in a <em>non-linear way</em>. Instead of performing a global normalization based on the range of values of the entire image, LCN operates on local patches of the image on a per pixel basis. This can be done by removing the mean of a neighborhood from a particular pixel and dividing by the variation of the pixel values.</p><p>The final layer has a <strong>C-way</strong> softmax function, C being the number of classes.</p><h3>GoogLeNet (2014) — Inception (2015)</h3><p><a href="https://arxiv.org/abs/1409.4842">GoogLeNet</a> is a neural network with 22 layers which won ILSVRC 2014. The name is an homage to Yann LeCuns pioneering LeNet-5. The overall number of layers (independent building blocks) used for the construction of the network is about 100. It is trained on <em>Places365</em> dataset, classifies images into 365 place categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*foqQX-k9eobsx_JxPniftA.png" /><figcaption>Fig.5. GoogLeNet network with all the bells and whistles.</figcaption></figure><ul><li>Input size: 224×224×3</li><li>Number of layers: 22 (100 independent building blocks)</li><li>Output:1 of 1,000 classes.</li><li>It’s weight is smaller than <em>VGG</em> and <em>ResNet</em>.</li></ul><p>GoogLeNet contains module blocks called <strong><em>Inception</em></strong><em>.</em><strong><em> </em></strong>It has 9 inception modules fitted linearly. Later versions called <em>Inception vN</em>, inspired by Christofer Nolan’s film of the same name, which got a popular meme, “<em>We Need To Go Deeper</em>”. Inception v3 published in 2015.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*NAnu1lc-hMDrysPoWgybHQ.png" /><figcaption>Fig.6. Inception Module.</figcaption></figure><p>Goal of Inception module is that it acts as a “<strong>Multi-level feature extractor</strong>” by computing 1×1, 3×3, 5×5 convolutions within the same module of the network. The output of these filters are then stacked along the channel dimension &amp; before being fed into the next layer in neural network. An Inception network stacks these modules on top of each other, with occasional <em>max-pooling</em> layers with stride 2 to halve the resolution of the grid.</p><p><strong>Implementation:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33c78b508feb5bf22dd3c9716d6c934/href">https://medium.com/media/e33c78b508feb5bf22dd3c9716d6c934/href</a></iframe><h3>VGG (2014)</h3><p><a href="https://arxiv.org/abs/1409.1556v6">VGG</a> is another exceptional neural network architecture which just lost to GoogLeNet and became the runner-up in ILSVRC 2014. It was proposed by Karen Simonyan &amp; Andrew Zisserman from <strong>Visual Geometry Group</strong>, Dept. of Engineering Science, University of Oxford. Their main contribution was a thorough evaluation of <em>networks of increasing depth</em>. They used an architecture with very small (3×3) convolution filters. It showed that a significant improvement can be achieved by pushing the depth to 16 - 19 weight layers (thus, VGG16 - VGG19).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*QhDKfmUMOR1-jgDz.png" /><figcaption>Fig.7. VGG Neural Network.</figcaption></figure><ul><li>Input size: 224×224×3</li><li>Number of layers: 16–19 weight layers</li><li>Output: 1 of 1,000 classes.</li><li>Uses <em>ReLU</em> activation.</li></ul><p>This network contains multiple blocks , group of convolutional layers with 3×3 filters (padding=1) and max pooling 2×2 filter (stride=2).</p><p><strong>Implementation:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d42dff9df21a825233dd66fdb3933d87/href">https://medium.com/media/d42dff9df21a825233dd66fdb3933d87/href</a></iframe><h3>ResNet (2015)</h3><p>This revolutionary model from Microsoft Research won the 1st place on ILSVRC 2015 classification task. With the ImageNet dataset, Residual neural network (<a href="https://arxiv.org/abs/1512.03385">ResNet</a>) can be evaluated with a depth of up to 152 layers - 8x deeper than VGG nets but still having lower complexity.</p><p>ResNet contains identity mapping by<strong> shortcut connections</strong> to adopt residual learning to every few stacked layers (i.e. every two weight layers). These stacks are building blocks to construct the network, called “<em>Residual blocks</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGigygLstjL25qbo8l04hQ.png" /><figcaption>Fig.8. Residual learning: a building block in ResNet-34.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWwQXzLBxlrGXEIWe7AsTQ.png" /><figcaption>Fig.9. Left: a building block (on 56×56 feature maps) in ResNet-34.<br> Right: a “bottleneck” building block for ResNet-50/101/152.</figcaption></figure><ul><li>Input size: 224×224×3</li><li>Number of layers: 18,34,50,101,152 or more parameter (weight) layers.</li><li>Output:1 of 1,000 classes.</li><li>SGD optimizer used with a mini-batch size of 256</li><li>Uses <em>ReLU</em> activation.</li><li>No dropout used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*LbkJOJ7mJ3i6JsSCKNpToA.png" /><figcaption>Fig.10. Residual network with 34 parameter layers (3.6 billion<br>FLOPs). The dotted shortcuts increase dimensions.</figcaption></figure><p><strong>Deeper Bottleneck Architectures:</strong> To reduce training time, the building block is modified as a bottleneck design (for each residual function, a stack of 3 layers used instead of 2) for ResNet-50/101/152.</p><p>An ensemble of these residual nets achieves 3.57% error on the ImageNet test set and 28% relative improvement on the COCO object detection dataset.</p><p><strong>Implementation:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9c063c996e1cc7c912598eeddaba49/href">https://medium.com/media/7b9c063c996e1cc7c912598eeddaba49/href</a></iframe><h3>ResNeXt (2016)</h3><p><a href="https://arxiv.org/abs/1611.05431v2">ResNeXt</a> became the 1st runner up of ILSVRC 2016 classification task. It showed much better results than it’s ResNet counterpart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XU_pWjTb46LZDwjLGXsyog.png" /><figcaption>Fig.11. Left: A block of ResNet.<br>Right: A block of ResNeXt with cardinality = 32, with roughly the same complexity. A layer is shown as (# in channels, filter size, # out channels)</figcaption></figure><p>ResNeXt uses an ensemble of building blocks similar to the one in ResNet deep (50/101/152) neural networks. It is constructed by repeating a building block that aggregates a set of transformations with the same topology.</p><p>ResNeXt denotes a new dimension on top of ResNet. This new dimension is called the “<strong>cardinality</strong>” (the size of the set of transformations/building blocks). Increasing cardinality is able to improve classification accuracy. Moreover, increasing cardinality is more effective than going deeper or wider when capacity is increased.</p><p>Implementation of ResNeXt in Pytorch can be found <a href="https://pytorch.org/hub/pytorch_vision_resnext">here</a>.</p><h3>SENet (2017)</h3><p><a href="https://arxiv.org/abs/1709.01507">Squeeze-and-Excitation Networks</a> won the first place in ILSVRC 2017 classification submission and reduced the top-5 error to 2.251%, surpassing ILSVRC 2016 winning entry by 25%.</p><p>It investigates a different aspect of a network design —<strong> </strong><em>the relationship between channels</em>. It introduces a new architectural unit, called the <strong>Squeeze-and-Excitation (SE) block</strong>. SE-block is a lightweight gating mechanism, specialised to model channel-wise relationships in a computationally efficient manner and designed to enhance the representational power of modules throughout the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhsmC7qG0IRM7yW_hlHRkw.png" /><figcaption>Fig.12. “Squeeze-and-Excitation” (SE) block.</figcaption></figure><p>Feature maps (u = vX) are produced by a <em>summation</em> through all channels (X). Channel dependencies are implicitly embedded in kernels (v), but are entangled with the local spatial correlation captured by the filters. A block access global information and recalibrate filter responses in <strong>two</strong> steps before they are fed into the next transformation:</p><ol><li><strong>Squeeze: Global Information Embedding:</strong> Global<em> average pooling</em> is used (max pooling can be as well) to <em>squeeze</em> global spatial information into a channel descriptor by generating channel-wise statistics (z = u/H×W).</li><li><strong>Excitation: Adaptive Re-calibration: </strong>The <em>excitation operator</em> (ReLu / tanh / Sigmoid) maps the input-specific descriptor (z) to a set of channel weights. To fully capture channel-wise dependencies, the function must meet two criteria:</li></ol><ul><li>First, it must be flexible (capable of learning a nonlinear interaction between channels).</li><li>Second, it must learn a non-mutually-exclusive relationship since we would like to ensure that multiple channels are allowed to be emphasised (rather than enforcing a one-hot activation).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3TLb0Bavn2phtrdQHFuWw.png" /><figcaption>Fig.13. Left: The schema of the original Inception module and SE-Inception module.<br>Right: The schema of the original Residual module and SE-ResNet module.</figcaption></figure><ul><li>To meet these criteria, a simple <strong>gating mechanism</strong> with a <strong>sigmoid </strong>(σ) activation used: s = F(z, W) = σ(g(z, W)) = <strong>σ</strong>(W₂ × ReLU(z × W₁))</li><li>The final output of the block is obtained by <strong>rescaling</strong> u with activations s: x = Fₛ𝒸ₐₗₑ(u, s) = s × u</li><li>Input size: <br>Depends on model architecture (224×224 pixels for Inception-ResNet-v2 or 299×299 for SE-Inception-ResNet-v2)</li><li>Number of layers: Depends on model architecture.</li><li>Output:1 of 1,000 classes.</li></ul><p>An implementation of <strong>SE-ResNeXt101</strong> in PyTorch can be found <a href="https://pytorch.org/hub/nvidia_deeplearningexamples_se-resnext">here</a>.</p><p>SENet surpasses the previous state-of-the-art model Places-365-CNN which has a top-5 error of 11.48% on this task. <strong>In-fact, it was so good that it ended the renowned ILSVRC competition altogether.</strong></p><h3>Scaling Vision Transformers (2021)</h3><p>Attention-based neural networks such as the <a href="https://arxiv.org/abs/2106.04560">Vision Transformer (ViT)</a> had gained state-of-the-art results on many computer vision benchmarks. <em>Scale</em> is a primary ingredient in attaining excellent results, therefore, understanding a model’s scaling properties is a key to designing future generations effectively. It is unknown how Vision Transformers scale. To address this, researchers apply following methods:</p><ol><li>Upscale &amp; downscale ViT models and data,</li><li>Characterize relationships between error rate, data &amp; compute.</li><li>Refine architecture &amp; training of ViT,</li><li>Reduce memory consumption,</li><li>Increase accuracy of the resulting models.</li></ol><p>As a result, researchers successfully trained a ViT model with <strong>2 Billion</strong> parameters, which attains on ImageNet of <strong>90.45%</strong> top-1 accuracy. The model also performs well on few-shot learning, for example, attaining 84.86% top-1 accuracy on ImageNet with only 10 examples per class.</p><p>An implementation of <strong>ViT</strong> in PyTorch can be found <a href="https://github.com/lucidrains/vit-pytorch">here</a>.</p><h3>CoCa (2022)</h3><p>Contrastive Captioners (CoCa) shows that a single pretrained model can outperform many specialized models using <a href="https://en.wikipedia.org/wiki/Zero-shot_learning">zero-shot transfer</a> or minimal task-specific adaptation. It uses a <em>modified</em> encoder-decoder architecture trained with both <strong>contrastive loss</strong> and <strong>captioning (generative) loss</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEP1fzWsugRXsKLeBtVGPA.png" /><figcaption>Fig.13. Overview of Contrastive Captioners (CoCa) pretraining as image-text foundation models.</figcaption></figure><p>They decouple the <em>decoder transformer</em> into 2 parts:</p><ol><li>Unimodal decoder: <br>- Omit cross-attention in unimodal decoder layers to encode <em>text-only representations</em>.</li><li>Multimodal decoder:<br>- Cascade multimodal decoder layers cross-attending to image encoder outputs to learn <em>multimodal image-text representations</em>.</li></ol><p>They apply both the contrastive objective between outputs of the image encoder &amp; unimodal text decoder, and the captioning objective at the output of the multimodal decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*J2ZcLGLz8J82AKZzvfU1fg.png" /><figcaption>Fig.14. Detailed illustration of CoCa architecture and training objectives.</figcaption></figure><p>With a frozen-encoder, CoCa achieves 90.6% on ImageNet classification and after lightweight finetuning, CoCa further achieves state-of-the-art 91.0% top-1 accuracy.</p><p>An implementation of <strong>CoCa</strong> in PyTorch can be found <a href="https://github.com/lucidrains/CoCa-pytorch">here</a>.</p><h4>What Next?</h4><p>In Dec 2022, came <a href="https://arxiv.org/abs/2212.02400v1">Location-Aware Self-Supervised Transformers</a> where each patch in a query view has to predict its position relatively to another reference view and <a href="https://arxiv.org/abs/2212.03035v1">IncepFormer</a> introduces a novel pyramid structured transformer encoder integrating an Inception-like architecture with depth-wise convolutions. Newer models will outperform older ones. Sometimes, old techniques will come back with a new twist to break down all known records. Will try to keep this article updated. Check back after few months. <em>Tschüss!</em></p><h4>References:</h4><ul><li>J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li and L. Fei-Fei, <strong>ImageNet: A Large-Scale Hierarchical Image Database. </strong><em>IEEE Computer Vision and Pattern Recognition (CVPR), 2009. </em><a href="https://image-net.org/static_files/papers/imagenet_cvpr09.pdf">pdf</a> | <a href="https://image-net.org/static_files/papers/imagenet_cvpr09.bib">BibTex</a></li><li>Russakovsky, O., Deng, J., Su, H. <em>et al.</em> <strong>ImageNet Large Scale Visual Recognition Challenge</strong>. <em>Int J Comput Vis</em> 115<strong>, </strong>211–252 (2015). <a href="https://doi.org/10.1007/s11263-015-0816-y">https://doi.org/10.1007/s11263-015-0816-y</a></li><li>Everingham, M., Van Gool, L., Williams, C. K. I., Winn, J. and Zisserman, A. <strong>The PASCAL Visual Object Classes (VOC) Challenge </strong><em>International Journal of Computer Vision, 88(2), 303–338, 2010</em><br> <a href="http://host.robots.ox.ac.uk/pascal/VOC/pubs/everingham10.html#bibtex">Bibtex source</a> | <a href="http://host.robots.ox.ac.uk/pascal/VOC/pubs/everingham10.html#abstract">Abstract</a></li><li>(LeNet) Y. Lecun, L. Bottou, Y. Bengio and P. Haffner, <strong>Gradient-based learning applied to document recognition.</strong> in Proceedings of the IEEE, vol. 86, no. 11, pp. 2278–2324, Nov. 1998, doi: <a href="https://doi.org/10.1109/5.726791">10.1109/5.726791</a>.</li><li>(<em>AlexNet</em>) Alex Krizhevsky, Ilya Sutskever, and Geoffrey E. Hinton. 2017. <strong>ImageNet classification with deep convolutional neural networks.</strong> Commun. ACM 60, 6 (June 2017), 84–90. DOI:<a href="https://doi.org/10.1145/3065386">https://doi.org/10.1145/3065386</a></li><li>(<em>ZFNet</em>) Matthew D. Zeiler, Rob Fergus, <strong>Visualizing and Understanding Convolutional Networks</strong>. <a href="https://dblp.dagstuhl.de/db/journals/corr/corr1311.html#ZeilerF13">CoRR abs/1311.2901</a> (2013)</li><li>(<em>GoogLeNet</em>) C. Szegedy et al., <strong>Going deeper with convolutions</strong>, 2015 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2015, pp. 1–9, doi: <a href="https://ieeexplore.ieee.org/document/7298594">10.1109/CVPR.2015.7298594</a>.</li><li>(<em>Inceptionv3</em>) C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens and Z. Wojna, <strong>Rethinking the Inception Architecture for Computer Vision</strong>, 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, pp. 2818–2826, doi: <a href="https://ieeexplore.ieee.org/document/7780677">10.1109/CVPR.2016.308</a>.</li><li>(<em>VGG</em>) K. Simonyan, A. Zisserman, <strong>Very Deep Convolutional Networks for Large-Scale Image Recognition</strong>, 2015, <a href="https://arxiv.org/abs/1409.1556v6">https://arxiv.org/abs/1409.1556v6</a></li><li>(<em>ResNet</em>) He Kaiming, Zhang Xiangyu, Ren Shaoqing, Sun Jian (2016), <strong>Deep Residual Learning for Image Recognition</strong>. <em>2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR)</em>. Las Vegas, NV, USA: IEEE. pp. 770–778. arXiv:<a href="https://arxiv.org/abs/1512.03385">1512.03385</a>. doi:<a href="https://doi.org/10.1109%2FCVPR.2016.90">10.1109/CVPR.2016.90</a>. ISBN 978–1–4673–8851–1.</li><li>(<em>ResNeXt</em>) Saining Xie, Ross B. Girshick, Piotr Dollár, Zhuowen Tu, Kaiming He (2016), <strong>Aggregated Residual Transformations for Deep Neural Networks</strong>. <a href="https://arxiv.org/abs/1611.05431v2">https://arxiv.org/abs/1611.05431v2</a></li><li><em>(SENet)</em> Jie Hu, Li Shen, Samuel Albanie, Gang Sun, Enhua Wu (2019),<br><strong>Squeeze-and-Excitation Networks</strong>, <a href="https://arxiv.org/abs/1709.01507">https://arxiv.org/abs/1709.01507</a></li><li>(<em>ViT</em>) Xiaohua Zhai, Alexander Kolesnikov, Neil Houlsby, Lucas Beyer (2021), <strong>Scaling Vision Transformers</strong>, <a href="https://arxiv.org/abs/2106.04560">https://arxiv.org/abs/2106.04560</a></li><li>(CoCa) Jiahui Yu, Zirui Wang, Vijay Vasudevan, Legg Yeung, Mojtaba Seyedhosseini, Yonghui Wu (2022), <strong>CoCa: Contrastive Captioners are Image-Text Foundation Models</strong>, <a href="https://arxiv.org/abs/2205.01917">https://arxiv.org/abs/2205.01917</a></li></ul><h4>More content at <a href="https://plainenglish.io/">PlainEnglish.io</a>.</h4><p>Sign up for our <a href="http://newsletter.plainenglish.io/"><strong>free weekly newsletter</strong></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><strong>Twitter</strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong>, and</strong> <a href="https://discord.gg/GtDtUAvyhW"><strong>Discord</strong></a><strong>.</strong></p><h4>Interested in scaling your software startup? Check out <a href="https://circuit.ooo/?utm=publication-post-cta">Circuit</a>.</h4><p>We offer free expert advice and bespoke solutions to help you build awareness and adoption for your tech product or service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=713df0500e7f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/imagenet-the-rise-of-deep-neural-network-architectures-for-image-classification-alexnet-713df0500e7f">ImageNet &amp; the rise of Deep Neural Network Architectures for Image Classification — AlexNet…</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — Structured Query Language]]></title>
            <link>https://bedouin7.medium.com/sql-structured-query-language-855a8dfb1da0?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/855a8dfb1da0</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[structured-query-language]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 08:14:30 GMT</pubDate>
            <atom:updated>2022-08-03T18:58:22.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Must read on SQL</h3><h4>Structured Query Language Basics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*9KiThOBUDz8V9Tns8ZqMDw.png" /><figcaption>SQL (Structured Query Language)</figcaption></figure><p>SQL (Structured Query Language) is a language used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems (RDBMS).</p><blockquote>You should have already known about SQL. In this article, we will go through few common SQL statements, operators and queries that any developer should never forget!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>Column Constraints</h4><p>Constraints can be column level or table level. These are rules applied to the values of individual columns to limit the type of data:</p><ul><li>PRIMARY KEY constraint can be used to uniquely identify the row.</li><li>FOREIGN KEY constraint is prevents actions that would destroy links between tables.</li><li>UNIQUE columns have a different value for every row.</li><li>NOT NULL columns must have a value.</li><li>DEFAULT assigns a default value for the column when no value is specified.</li><li>CHECK constraint is used to limit the value range that can be placed in a column.</li><li>AUTO_INCREMENT constraint allows an increment number to be generated automatically when a new record is inserted into a table.</li></ul><p>There can be only one PRIMARY KEY column per table and multiple UNIQUE columns.</p><pre>CREATE TABLE student (<br>  id INTEGER <strong>PRIMARY KEY </strong>AUTO_INCREMENT,<br>  name TEXT <strong>UNIQUE</strong>,<br>  grade INTEGER <strong>NOT NULL</strong>,<br>  age INTEGER <strong>DEFAULT</strong> 10,<br>  <strong>CONSTRAINT</strong> age <strong>CHECK</strong> (age&gt;=1 AND age&lt;30)<br>);</pre><h4>CREATE TABLE Statement</h4><p>The CREATE TABLE statement creates a new table in a database. It allows one to specify the name of the table and the name of each column in the table.</p><pre><strong>CREATE TABLE</strong> table_name (<br>  column_name_1 datatype,<br>  column_name_2 datatype,<br>  column_name_3 datatype<br>);</pre><h4>ALTER TABLE Statement</h4><p>The ALTER TABLE statement is used to modify the columns of an existing table. When combined with the ADD COLUMN clause, it is used to add a new column.</p><pre><strong>ALTER TABLE</strong> table_name <strong>ADD</strong> column_name datatype;</pre><h4>DROP TABLE Statement</h4><p>The DROP TABLE statement is used to drop an existing table from a database.</p><pre><strong>DROP TABLE</strong> table_name;</pre><h4>TRUNCATE TABLE Statement</h4><p>The TRUNCATE TABLE statement is used to remove the data inside an existing table without dropping the table from the database.</p><pre><strong>TRUNCATE</strong><strong> TABLE</strong> table_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>INSERT Statement</h4><p>The INSERT INTO statement is used to add a new record (row) to a table. It has two forms as shown:</p><ul><li>Insert into columns in order.</li><li>Insert into columns by name.</li></ul><pre>-- Insert into columns in order:<br><strong>INSERT INTO</strong> table_name <strong>VALUES</strong> (value1, value2);<br> <br>-- Insert into columns by name:<br><strong>INSERT INTO</strong> table_name (column1, column2) <strong>VALUES</strong> (value1, value2);</pre><h4>SELECT Statement</h4><p>The SELECT * statement returns all columns from the provided table in the result set. The given query will fetch all columns and records (rows) from the movies table.</p><pre><strong>SELECT</strong> * FROM movies;</pre><h4>UPDATE Statement</h4><p>The UPDATE statement is used to edit records (rows) in a table. It includes a SET clause that indicates the column to edit and a WHERE clause for specifying the record(s).</p><pre><strong>UPDATE</strong> table_name <strong>SET</strong> column1 = value1, column2 = value2 WHERE some_column = some_value;</pre><h4>DELETE Statement</h4><p>The DELETE statement is used to delete records (rows) in a table. The WHERE clause specifies which record or records that should be deleted. If the WHERE clause is omitted, all records will be deleted.</p><pre><strong>DELETE</strong> <strong>FROM</strong> table_name WHERE some_column = some_value;</pre><h4>WHERE Clause</h4><p>The WHERE clause is used to filter records (rows) that match a certain condition. The given query will match any customer from state &#39;CA&#39;.</p><pre>SELECT name FROM customers <strong>WHERE</strong> state = &#39;CA&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>AND Operator</h4><p>The AND operator allows multiple conditions to be combined. Records must match both conditions that are joined by AND to be included in the result set. The given query will match any customer from state &#39;CA&#39; and age at least 20.</p><pre>SELECT name FROM customers WHERE state = &#39;CA&#39; <strong>AND</strong> age &gt;= 20;</pre><h4>OR Operator</h4><p>The OR operator allows multiple conditions to be combined. Records matching either condition joined by the OR are included in the result set. The given query will match customers whose state is either &#39;CA&#39; or &#39;NY&#39;.</p><pre>SELECT name FROM customers WHERE state = &#39;CA&#39; <strong>OR</strong> state = &#39;NY&#39;;</pre><h4>NOT Operator</h4><p>The NOT operator displays a record if the condition(s) is not TRUE. The given query will match customers whose state are not &#39;CA&#39;.</p><pre>SELECT name FROM customers WHERE NOT state = &#39;CA&#39;;</pre><h4>BETWEEN Operator</h4><p>The BETWEEN operator can be used to filter by a range of values. The range of values can be text, numbers, or date data. The given query will match any movie made between the years 1980 and 1990, inclusive.</p><pre>SELECT * FROM movies WHERE year <strong>BETWEEN</strong> 1980 <strong>AND</strong> 1990;</pre><h4>IN Operator</h4><p>The IN operator allows to specify multiple values in a WHERE clause. It is a shorthand for multiple OR conditions.</p><pre>SELECT * FROM customers WHERE country NOT <strong>IN</strong> (&#39;UAE&#39;, &#39;USA&#39;, &#39;UK&#39;);<br></pre><pre>SELECT * FROM customers WHERE country <strong>IN</strong> (SELECT country FROM orders);</pre><h4>LIKE Operator</h4><p>The LIKE operator can be used inside of a WHERE clause to match a specified pattern. The given query will match any movie that begins with Star in its title.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> &#39;Star%&#39;;</pre><h4>% Wildcard</h4><p>The % wildcard can be used in a LIKE operator pattern to match zero or more unspecified character(s). The given query will match any movie that begins with Ele, followed by zero or more of any characters.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> <strong>&#39;</strong>Ele<strong>%&#39;</strong>;</pre><h4>_ Wildcard</h4><p>The _ wildcard can be used in a LIKE operator pattern to match any single unspecified character. The given query will match any movie which begins with a single character, followed by ven.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> &#39;<strong>_</strong>ven&#39;;</pre><h4>[charlist] Wildcard</h4><p>The [] wildcard can be used in a LIKE operator pattern to match any single character within the brackets. The given query will match movies: Elen,Eeen,Even.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> &#39;E[lev]en&#39;;</pre><p>The [^charlist] wildcard can be used in a LIKE operator pattern to match any character not in the brackets. The following query will match movies except these: Elen,Eeen,Even.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> &#39;E[^lev]en&#39;;</pre><h4>- Wildcard</h4><p>The - wildcard can be used in a LIKE operator pattern to match any single character within the specified range. The following query will match movies: Eaen,Eben,Ecen,Eden,Eeen.</p><pre>SELECT name FROM movies WHERE name <strong>LIKE</strong> &#39;E[a-e]en&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>AS Clause</h4><p>Columns or tables can be aliased using the AS clause. This allows columns or tables to be specifically renamed in the returned result set. The given query will return a result set with the column for name renamed to movie_title.</p><pre>SELECT name <strong>AS</strong> &#39;movie_title&#39; FROM movies;</pre><h4>DISTINCT Clause</h4><p>Unique values of a column can be selected using a DISTINCT query. For a table contact_details having five rows in which the city column contains Chicago, Madison, Boston, Madison, Denver, Madison the given query would return:Chicago, Madison, Boston, Denver</p><pre>SELECT <strong>DISTINCT</strong> city FROM contact_details;</pre><h4>LIMIT Clause</h4><p>The LIMIT clause is used to narrow, or limit, a result set to the specified number of rows. The given query will limit the result set to 5 rows.</p><pre>SELECT * FROM movies <strong>LIMIT</strong> 5;</pre><h4>NULL Values</h4><p>Column values can be NULL, or have no value. These records can be matched (or not matched) using the IS NULL and IS NOT NULL operators in combination with the WHERE clause. The given query will match all addresses where the address has a value or is not NULL.</p><pre>SELECT address FROM records WHERE address <strong>IS NOT</strong> <strong>NULL</strong>;</pre><h4>ORDER BY Clause</h4><p>The ORDER BY clause can be used to sort the result set by a particular column either alphabetically or numerically. It can be ordered in two ways:</p><ul><li>DESC is a keyword used to sort the results in descending order.</li><li>ASC is a keyword used to sort the results in ascending order (default).</li></ul><pre>SELECT * FROM contacts <strong>ORDER BY</strong> birth_date <strong>DESC</strong>;</pre><h4>GROUP BY Clause</h4><p>The GROUP BY clause will group records in a result set by identical values in one or more columns. It is often used in combination with aggregate functions to query information of similar records. The GROUP BY clause can come after FROM or WHERE but must come before any ORDER BY or LIMIT clause.</p><p>The given query will count the number of movies per rating.</p><pre>SELECT rating, COUNT(*) FROM movies <strong>GROUP BY</strong> rating;</pre><h4>Column References</h4><p>The GROUP BY and ORDER BY clauses can reference the selected columns by number in which they appear in the SELECT statement. The example query will count the number of movies per rating, and will:</p><ul><li>GROUP BY column 2 (rating)</li><li>ORDER BY column 1 (total_movies)</li></ul><pre>SELECT COUNT(*) AS &#39;total_movies&#39;, rating FROM movies <strong>GROUP BY</strong> 2 <strong>ORDER BY</strong> 1;</pre><h4>HAVING Clause</h4><p>The HAVING clause is used to further filter the result set groups provided by the GROUP BY clause. HAVING is often used with aggregate functions to filter the result set groups based on an aggregate property. The given query will select only the records (rows) from only years where more than 5 movies were released per year.</p><pre>SELECT year, COUNT(*) FROM movies <strong>GROUP BY</strong> year <strong>HAVING</strong> COUNT(*) &gt; 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>Aggregate Functions</h4><p>Aggregate functions perform a calculation on a set of values and return a single value:</p><ul><li>COUNT()</li><li>SUM()</li><li>MAX()</li><li>MIN()</li><li>AVG()</li></ul><h4>COUNT() Aggregate Function</h4><p>The COUNT() aggregate function returns the total number of rows that match the specified criteria. For instance, to find the total number of employees who have less than 5 years of experience, the given query can be used.</p><p><strong>Note:</strong> A column name of the table can also be used instead of *. Unlike COUNT(*), this variation COUNT(column) will not count NULL values in that column.</p><pre>SELECT <strong>COUNT</strong>(*) FROM employees WHERE experience &lt; 5;</pre><h4>SUM() Aggregate Function</h4><p>The SUM() aggregate function takes the name of a column as an argument and returns the sum of all the value in that column.</p><pre>SELECT <strong>SUM</strong>(salary) FROM salary_disbursement;</pre><h4>MAX() Aggregate Function</h4><p>The MAX() aggregate function takes the name of a column as an argument and returns the largest value in a column. The given query will return the largest value from the amount column.</p><pre>SELECT <strong>MAX</strong>(amount) FROM transactions;</pre><h4>MIN() Aggregate Function</h4><p>The MIN() aggregate function returns the smallest value in a column. For instance, to find the smallest value of the amount column from the table named transactions, the given query can be used.</p><pre>SELECT <strong>MIN</strong>(amount) FROM transactions;</pre><h4>AVG() Aggregate Function</h4><p>The AVG() aggregate function returns the average value in a column. For instance, to find the average salary for the employees who have less than 5 years of experience, the given query can be used.</p><pre>SELECT <strong>AVG</strong>(salary) FROM employees WHERE experience &lt; 5;</pre><h4>ROUND() Function</h4><p>The ROUND() function will round a number value to a specified number of places. It takes two arguments: a number, and a number of decimal places. It can be combined with other aggregate functions, as shown in the given query. This query will calculate the average rating of movies from 2015, rounding to 2 decimal places.</p><pre>SELECT year, <strong>ROUND(</strong>AVG(rating)<strong>, 2)</strong> FROM movies WHERE year = 2015;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>Inner Join</h4><p>The JOIN clause allows for the return of results from more than one table by joining them together with other results based on common column values specified using an ON clause. INNER JOIN is the default JOIN and it will only return results matching the condition specified by ON.</p><pre>SELECT * FROM books <strong>JOIN</strong> authors <strong>ON</strong> books.author_id = authors.id;</pre><h4>Outer Join</h4><p>An outer join will combine rows from different tables even if the join condition is not met. In a LEFT JOIN, every row in the <em>left</em> table is returned in the result set, and if the join condition is not met, then NULL values are used to fill in the columns from the <em>right</em> table.</p><pre>SELECT column_name(s) FROM table1 <strong>LEFT</strong> <strong>JOIN</strong> table2 <br><strong>ON</strong> table1.column_name <strong>=</strong> table2.column_name;</pre><p>An overview of SQL joins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3KFK0V2ZfCcESXQmwaMzw.png" /><figcaption>SQL JOINS</figcaption></figure><h4>WITH Clause</h4><p>The WITH clause stores the result of a query in a temporary table (temporary_movies) using an alias. Multiple temporary tables can be defined with one instance of the WITH keyword.</p><pre><strong>WITH</strong> <em>temporary_movies</em> <strong>AS</strong> (SELECT * FROM movies)<br></pre><pre>SELECT * FROM <em>temporary_movies</em> WHERE year BETWEEN 2000 AND 2020;</pre><h4>UNION Clause</h4><p>The UNION clause is used to combine results that appear from multiple SELECT statements and filter duplicates.</p><p>For example, given a first_names table with a column name containing rows of data “James” and “Hermione”, and a last_names table with a column name containing rows of data “James”, “Hermione” and “Cassidy”, the result of this query would contain three names: “Cassidy”, “James”, and “Hermione”.</p><pre>SELECT name FROM first_names<br><strong>UNION</strong><br>SELECT name FROM last_names</pre><h4>CROSS JOIN Clause</h4><p>The CROSS JOIN clause is used to combine each row from one table with each row from another in the result set. This JOIN is helpful for creating all possible combinations for the records (rows) in two tables.</p><p>The given query will select the shirt_color and pants_color columns from the result set, which will contain all combinations of combining the rows in the shirts and pants tables. If there are 3 different shirt colors in the shirts table and 5 different pants colors in the pants table then the result set will contain 3 x 5 = 15 rows.</p><pre>SELECT shirts.shirt_color, pants.pants_color <br>FROM shirts <strong>CROSS JOIN</strong> pants;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>Primary Key</h4><p>A <em>primary key</em> column in a SQL table is used to uniquely identify each record in that table. A primary key cannot be NULL. In the example, customer_id is the primary key. The same value cannot re-occur in a primary key column. Primary keys are often used in JOIN operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CiRd0HQTEi1R-_s4.png" /></figure><h4>Foreign Key</h4><p>A <em>foreign key</em> is a reference in one table’s records to the primary key of another table. To maintain multiple records for a specific row, the use of foreign key plays a vital role. For instance, to track all the orders of a specific customer, the table orders (illustrated at the bottom of the image) can contain a foreign key.</p><pre>CREATE TABLE orders (<br> order_id int NOT NULL,<br> customer_id int NOT NULL,<br> order_qty int,<br> PRIMARY KEY (order_id),<br> <strong>FOREIGN KEY</strong> (customer_id) <strong>REFERENCES</strong> customers (customer_id)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*uThbY94IVm4wAjza.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><h4>Let’s look at few queries:</h4><ol><li><strong>Write the SQL query to get the third maximum salary of an employee from a table named </strong>employees<strong>.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxcYMGMEeSpaVH8Ctb3lJw.png" /></figure><pre>SELECT * FROM ((SELECT * from employees <br>       ORDER BY `salary` DESC LIMIT <strong>3</strong>) AS T)<br>       ORDER BY T.`salary` ASC LIMIT 1;</pre><p><strong>2. How to remove duplicate rows in SQL?</strong></p><p>Remove duplicate rows from both tables where employee_email is same and primary key is employee_id.</p><pre>DELETE table_1 FROM salary table_1<br>INNER JOIN salary table_2<br>WHERE<br>    table_1.employee_id &gt; table_2.employee_id AND <br>    table_1.employee_email = table_2.employee_email;</pre><p><strong>3. Select unique records from a table?</strong></p><pre>Select <strong>DISTINCT</strong> employee_id from salary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*lIIfJJf_-Z2L5f5dx_dLkg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855a8dfb1da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis (EDA) with Python & Matplotlib]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ai.plainenglish.io/exploratory-data-analysis-eda-with-python-matplotlib-bb784e1d3dd3?source=rss-e364f40f8219------2"><img src="https://cdn-images-1.medium.com/max/840/1*YLQowJd6ROxxjJOuaCM-hQ.png" width="840"></a></p><p class="medium-feed-snippet">Analyzing datasets to summarize their main characteristics, often with visual methods&#x2026;</p><p class="medium-feed-link"><a href="https://ai.plainenglish.io/exploratory-data-analysis-eda-with-python-matplotlib-bb784e1d3dd3?source=rss-e364f40f8219------2">Continue reading on Artificial Intelligence in Plain English »</a></p></div>]]></description>
            <link>https://ai.plainenglish.io/exploratory-data-analysis-eda-with-python-matplotlib-bb784e1d3dd3?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb784e1d3dd3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 23:44:10 GMT</pubDate>
            <atom:updated>2022-12-13T09:47:11.004Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Python concepts for Interview]]></title>
            <link>https://ai.plainenglish.io/python-concepts-for-interview-ffeae5c357f1?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffeae5c357f1</guid>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 23:33:28 GMT</pubDate>
            <atom:updated>2021-01-15T12:56:16.564Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<p><em>As of December 2020 Python ranked third in </em><a href="https://en.wikipedia.org/wiki/TIOBE_index"><em>TIOBE</em></a><em>’s index of most popular programming languages, behind C and Java. This article assumes you’re already familiar with programming language basics, syntax etc. It focuses mostly on a rundown on few topics before interview.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*WsdjpoKvX601Xod_K6G-VQ.png" /></figure><h4>⚜ Key features</h4><p>Python is considered as a general-purpose programming language which is capable of scripting. Python is an <strong>interpreted</strong> language. It does not need to be compiled before it is run. Python is <strong>dynamically typed</strong>, we don’t need to state the types of variables during declaration. Python does not have access specifiers (like public, private, protected) and it is <strong>case sensitive</strong>. Functions are<strong> first-class objects</strong>. Memory management in python is managed by <strong>Python private heap space</strong>.<br>(Usually developers use <strong>__varname</strong> to indicate private variables and <strong>_varname </strong>to indicate protected variables.)</p><h4>⚜ PEP 8</h4><p><a href="https://www.python.org/dev/peps/pep-0008/">PEP</a> stands for <strong>Python Enhancement Proposal. </strong>It is the Style Guide for Python Code for better readability and easier understanding.<br><em>Read more: </em><a href="https://realpython.com/python-pep8/"><em>https://realpython.com/python-pep8</em></a></p><h4>⚜ Namespace, PYTHONPATH, modules</h4><p>Namespace is a naming system used to make sure that names are unique to avoid naming conflicts. A namespace is a collection of names which maps every name to corresponding objects. At any given moment, there are at least three nested scopes.</p><ol><li>Scope of the current function which has local names</li><li>Scope of the module which has global names</li><li>Outermost scope which has built-in names</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*yh6S2fwgRu8n7KGO.jpg" /></figure><p><strong>PYTHONPATH</strong> is an environment variable which we can set to add additional directories where python will look for modules and packages.</p><p>Python <strong>modules</strong> are files containing code for functions, classes or variables. Some of the commonly used built-in modules are:</p><ul><li><strong>os</strong>: The OS module in python provides functions for interacting with the operating system. Look at few common functions:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xX4gA6sot8WfP9J49wUMMQ.png" /></figure><ul><li><strong>sys</strong>: It provides functions and variables used to manipulate different parts of the Python runtime environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcoTC-ZFvoQb0S_HYIWdMQ.png" /></figure><ul><li><strong>math</strong>: Provides trigonometric functions, representation functions, logarithmic functions, angle conversion functions, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D86j1Fa2YFxzDRMO7VDt-Q.png" /></figure><ul><li><strong>random</strong>: Uses a pseudo-random number generator function random() to generate random numbers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAfggJFZvM33-Cs2GWmTHA.png" /></figure><ul><li><strong>datetime</strong>: It works with dates as date objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEBQvK0phhHObhENc0rfCA.png" /></figure><ul><li><strong>JSON</strong>: It works with JSON data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RG7KSmtv49BxiD0VjHOaGA.png" /></figure><h4>⚜ File I/O operations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwU0pJu14XgYZ3jwyUFKOw.png" /></figure><h4>⚜ Lambda function, filter, map</h4><p>Lambda functions are anonymous function that are defined without a name. The filter() function takes in a function and a list as arguments and a new list is returned which contains items for which the function evaluates to True. The map() function is similar but it returns a new list which contains items returned by that function for each item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdBiOE_-wz93E99OfM0GZw.png" /></figure><h4>⚜ Local, global and nonlocal variables</h4><p>Variables declared outside a function or in global space are called <strong>global</strong> variables. These variables can be accessed by any function in the program.</p><p>Any variable declared inside a function is known as a <strong>local</strong> variable. This variable is present in the local space and not in the global space.</p><p><strong>Nonlocal</strong> variables are used in nested functions whose values can be accessed and modified from outside of the function. If we change the value of a nonlocal variable, the changes appear in the local variable as well.</p><h4>⚜ Built-in types</h4><p>Integers, Floating-point, Complex numbers, Strings, Boolean and Built-in functions.</p><h4>⚜ Type conversion</h4><p>Type conversion refers to the conversion of one data type into another.<br><strong>int() </strong>— converts any data type into integer<br><strong>float()</strong> — converts any data type into float<br><strong>ord()</strong> — converts characters into integer<br><strong>hex(</strong>) — converts integer to hexadecimal<br><strong>oct()</strong> — converts integer to octal<br><strong>tuple() — </strong>convert to a tuple<br><strong>set() — </strong>convert to set<br><strong>list() — </strong>convert to list type.<br><strong>dict() — </strong>convert a tuple of order (key, value) into a dictionary<br><strong>str() — </strong>convert integer into a string<br><strong>complex(real,imag) </strong>— converts real numbers to complex(real, imag) number</p><h4>⚜ Difference between List and Tuple</h4><p>Lists are <strong>mutable</strong> i.e they can be edited. Lists are slower than tuples. Syntax: list_name = [10, &#39;Apple&#39;, 70.5]<br>Tuples are <strong>immutable</strong> (tuples are lists which can’t be edited). Tuples are faster than list. Syntax: tuple_name = (10, &#39;Apple&#39;, 70.5)</p><h4>⚜ Difference between Array and List</h4><p>Python <em>list</em> is a built-in object, whereas <em>array</em> is not. We have to import <em>array</em> module to use arrays. <strong>Array</strong> can hold only a single data type elements whereas <strong>List</strong> can hold any data type elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkGtamO6Jl1bJoVB1tme2w.png" /></figure><h4>⚜ Constructor</h4><p><strong>__init__</strong> is the constructor which automatically called to allocate memory when a new object/instance of a class is created. All classes have the __init__ method with <em>self</em> as the first parameter.</p><p>Self is an instance or an object of a class. It helps to differentiate between the methods and attributes of a class with local variables. The <em>self</em> variable in the __init__ method refers to the newly created object but in other methods, it refers to the object whose method was called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNnaaUgPeiReOILYoPgHgQ.png" /></figure><h4>⚜ Break, Continue, Pass</h4><p><strong>Break</strong>: Terminates loop and goes to the next statement.<br><strong>Continue</strong>: Skip some part of a loop and goes to the beginning of the loop.<br><strong>Pass</strong>: Used when we need some block of code syntactically, but we want to skip its execution. This is basically a null operation. Nothing happens when this is executed.</p><h4>⚜ Slicing, List comprehension</h4><p>Slicing is a tool to build new lists out of an existing list/sequence, it use this syntax: [lower bound : upper bound : step size]</p><p>List comprehension is another way to define and create lists based on existing lists, it use syntax: [expression for item in list]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kH1ewLxh_HXqAc-VSYIjEQ.png" /></figure><h4>⚜ Iterators, Generators</h4><p><strong>Iterators</strong> are objects which can be traversed though or iterated upon, which consist of the methods __iter__() and __next__(). Lists, tuples, dictionaries, string and sets are all iterable objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W09cH5dSseiDf3KcFkoZKg.png" /></figure><p><strong>Generators </strong>are functions which return an iterable set of items. To create a generator, we use <strong>yield</strong> statement inside a function instead of the return.</p><ul><li>A list holds all values at once but a generator holds only one value at a time (the value to yield). That’s why it needs less space compared to a list.</li><li>With a generator, we don’t need to wait until all the values are rendered.</li><li>When interpreter reaches return statement in a function, it stops executing. However, when it reaches the yield statement in a generator, it yields the value to the iterable. Finally, it gets back to the generator to continue for the next value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lExV6PbywHwu2yZVx2u3-A.png" /></figure><h4>⚜ Pickling, Unpickling</h4><p>Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxWrBBk-IjKJjrSv8Iiz_A.png" /></figure><h4>⚜ The dir() built-in function</h4><p>We can use the dir() function to find out sorted defined names/symbols within a module or a class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dNVRn3Of5mM5mqPR6ilFg.png" /></figure><h4>⚜ String functions</h4><p>All string methods returns new values. They do not change the original string. Look more: <a href="https://www.w3schools.com/python/python_ref_string.asp">https://www.w3schools.com/python/python_ref_string.asp</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uR8ZaHxNP0NrKIAOLEZXdQ.png" /></figure><h4>⚜ docstrings, help() function</h4><p>Docstring (Documentation string) provides a description for the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pl3E8paKhgna7fVym8L2eg.png" /></figure><p>The help() function is used to display the documentation string and also facilitates to see the help related to modules, keywords, attributes, etc.</p><h4>⚜ *args and *kwargs</h4><p>We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments.</p><h4>⚜ OOP</h4><p><strong>Inheritance</strong> allows child class to obtain all the attributes and methods of parent class. Inheritance provides code re-usability, makes it easier to create and maintain an application. Supported types of inheritance:</p><ol><li><em>Single Inheritance</em>: child class acquires the members of a single super class.</li><li><em>Multi-level inheritance</em>: child class is inherited from a class which is also inherited from another class.</li><li><em>Hierarchical inheritance</em>: more than one derived classes are created from a single base.</li><li><em>Multiple inheritance</em>: child class is inherited from more than one base class.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCKHnAHvoBDqXazlW__P4Q.png" /></figure><p>In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in <em>depth-first, left-right</em> fashion without searching the same class twice. This order is also called linearization of MultiDerived class and the set of rules used to find this order is called <strong>Method Resolution Order (MRO)</strong>.</p><p><strong>Polymorphism</strong> means the ability to take multiple forms.</p><p><strong>Encapsulation</strong> means wrapping the code and the data together (e.g. A Python class). Data</p><p><strong>Abstraction</strong> is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.</p><h4>⚜ Monkey patching</h4><p>It refers to dynamic modifications of a class or module at run-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKTEtEM9EzUjCNTg-pm_AA.png" /></figure><h4>⚜ Operator Overloading</h4><p>The meaning of an operator in a class can be changed depending upon the operands used using Python <strong>magic methods</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtSzaLe5rO6eIfsSRq_xOQ.png" /></figure><h4>⚜ zip() function</h4><p>It takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2tS4z2pMnKTnnAbo4ZNog.png" /></figure><h4>⚜ Decorators</h4><p>A decorator takes in a function, adds some functionality and returns it. It is a callable which returns a callable. Here is a nice video: <a href="https://www.youtube.com/watch?v=FsAPt_9Bf3U">https://www.youtube.com/watch?v=FsAPt_9Bf3U</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MYfsverg3KP_mFX8v0W0Q.png" /><figcaption>Decorator example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZ9iNVVCuIkDfZ1RboceoA.png" /><figcaption>Decorator example 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFn_LvItoD3VNfJuR-yfBg.png" /><figcaption>Decorator example 3</figcaption></figure><p><em>This article is actively being updated. Add a bookmark and check back later.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffeae5c357f1" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/python-concepts-for-interview-ffeae5c357f1">Python concepts for Interview</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Traveler’s Diary on the Road to Machine Learning — Chapter 1]]></title>
            <link>https://bedouin7.medium.com/a-travelers-diary-on-the-road-to-machine-learning-chapter-1-8850ec5b4243?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/8850ec5b4243</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 01:19:04 GMT</pubDate>
            <atom:updated>2022-11-13T18:12:11.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Traveler’s Diary on the Road to Machine Learning - Chapter 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*gZRjwbx5GmchEWT6_tMNiQ.png" /></figure><p><strong>Contents</strong><br>• <a href="#0625">Machine Learning</a><br>• <a href="#e4b2">Model</a><br>• <a href="#3d0c">Types of Machine Learning algorithms</a><br>• <a href="#8f05">Supervised Learning</a><br>• <a href="#29a7">Unsupervised Learning</a><br>• <a href="#4c07">Reinforcement Learning</a><br>• <a href="#f7c7">Useful terms of a dataset</a><br>• <a href="#3621">Loss function</a><br>• <a href="#94ee">Cost function</a></p><p><strong>What is Machine Learning?<br></strong>Machine Learning (ML) is a branch of Artificial Intelligence (AI). It is a process to find cause-effect relationships and patterns usually in a huge amount of data, using algorithms and statistical models without programming explicitly.</p><p><strong>How Machine Learning works?<br></strong>Machine Learning algorithms use various techniques to find and calculate patterns in given data. Then try to predict a result and compare it with the actual output. This process continues as they gradually reduce the error in prediction and establish a standard. The output of a machine learning algorithm is a machine learning model comprised of model data and a prediction algorithm.</p><p><strong>What is ‘Learning’ in</strong> <strong>Machine Learning?</strong><br>The process of obtaining a prediction algorithm (classifier) from data is called Learning.</p><p><strong>What is a Model / Prediction Mechanism / Classifier ?</strong><br>Model is a function with parameter θ<em>. </em>Model is the output of a machine learning algorithm after running on data, comprised of both model data and a procedure for using the data to make a prediction. Model represents what was learned by the algorithm.<br>For example, in Linear Regression<strong>:</strong></p><ul><li><em>Algorithm</em>: Find set of coefficients that minimize error on training dataset.</li><li><em>Model</em>: Model Data: Vector of coefficients and <br>Prediction Algorithm: Multiple and sum coefficients with input row.</li></ul><p>In k-Nearest Neighbors:</p><ul><li><em>Algorithm</em>: Save training data.</li><li><em>Model</em>: Model Data: Entire training dataset.<br>Prediction Algorithm: Find k most similar rows and average their target variables.</li></ul><p>Algorithms provide a sort of automatic programming where as models represent the program. <a href="https://machinelearningmastery.com/difference-between-algorithm-and-model-in-machine-learning/">Read</a> the difference Between algorithm and model in Machine Learning.</p><p><strong>Types of Machine Learning algorithms:<br></strong>Machine Learning models are generally divided in three groups: <em>Supervised learning</em> (task driven), <em>Unsupervised learning</em> (data driven) and <em>Reinforcement learning</em> (learn from errors).</p><p>Here you can see a brief overview of different types of Machine Learning algorithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mz6UvzdyG1FeSOSy7iflrA.jpeg" /><figcaption>Different Types of Machine Learning algorithms</figcaption></figure><p><strong>Supervised Learning:</strong><br>In Supervised Learning, the algorithm learns on a labeled dataset. Here, both input and output are provided. The model learns the relationship between independent and dependent variables to give a prediction for unknown targets.</p><p><em>e.g.: House price detection, Leaf category detection, sequence prediction etc.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*_tT-Z4sNqk2wCffG.png" /><figcaption><strong>Supervised Learning</strong> (Image source: nvidia)</figcaption></figure><p>Usually Supervised Learning is divided into <em>two</em> categories: Classification &amp; Regression. There are few other categories as well.</p><ol><li><strong>Classifier Learning</strong>: Predicts the class of given data points.<br><em>e.g.: Binary classification, Logistic regression, Decision tree, Ensemble classifier, Naive Bayes, KNN etc.<br></em>There are two types of learners in classification: <br>Lazy learners simply store the training data and wait until a testing data to appear. Classification is conducted based on the most related data in the stored training data. They have less training time but more time in predicting. <br><em>e.g.: k-nearest neighbor, Case-based reasoning.<br></em>Eager learners construct a classification model based on the given training data, before receiving test data for classification. It must be able to commit to a single hypothesis that covers the entire instance space. Due to the model construction, eager learners take a long time for train and less time to predict. <br><em>e.g.: Decision Tree, Naive Bayes, ANN.</em></li><li><strong>Regression</strong>: Predicts a continuous variable.<br><em>e.g.: Linear Regression.</em></li><li><strong>Ordinal Regression</strong>: It predicts a discrete value y ∈ Y like classification, but there is an ordering on the elements of Y. The relative ordering between different values is significant.<br>The model can be formulated as: Pr(y ≤ i|x) = σ(θᵢ — w.x )<br><em>e.g.: Customer rating, Product review etc.</em></li><li><strong>Taxonomy Classification</strong>: Output is discrete value y ∈ Y like classification, but there is a tree-based ordering on the elements of Y.<br><em>e.g.: Animal or plant taxonomy etc.</em></li><li><strong>Sequence and Structure Prediction</strong>: Sequence, Tree or Graph y ∈ Y.<br><em>e.g.: Parse natural languages, Protein folding etc.</em></li><li><strong>Ranking</strong>: Predicts a sorting of the items y ∈ Y.<br><em>e.g.: Ranking of search results.</em></li><li><strong>Recommendations</strong>: Predicts a item-by-user matrix to recommend y ∈ Y for the user.<br><em>e.g.: Product recommendation, YouTube video recommendation, Music recommendation etc.</em></li></ol><p><strong>Unsupervised Learning:<br></strong>The algorithm tries to detect structure in the data by extracting features, grouping, clustering and finding patterns on its own as the target is not known.</p><p><em>e.g.: Customer segmentation, Email campaign, Market segmentation etc.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*8fdqapJVtS3fYK6F.png" /><figcaption><strong>Unsupervised Learning</strong> (Image source: nvidia.com)</figcaption></figure><p>Unsupervised learning can be divided into <em>two</em> main categories: Clustering and Association.</p><p>i. <strong>Cluster Analysis:</strong> It is a way to group unlabeled data based on similarities or differences.<br><em>e.g.: k-means clustering assigns similar data points into k-groups. It is technique is helpful for market segmentation, image compression, etc.</em></p><p>ii. <strong>Association:</strong> It uses various methods to find relationships in a unlabeled dataset. There are several types of association:<br>- Exclusive association: It uses partitioning. <em>e.g.: k-means.<br>- </em>Agglomerative association: Hierarchical association.<br>- Overlapping association: <em>e.g.: Fuzzy C-means.</em><br>- Probabilistic association: <em>e.g.: Keywords.</em></p><p>iii. <strong>Dimensionality reduction</strong> is also a type of unsupervised learning. When the number of features (or dimensions) in a dataset is too high, it reduces the number of features keeping data integrity. It is used in data pre-processing.<br><em>e.g.: Principal component analysis (PCA).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaZL0zvyy2fG2vK9rk9ELA.png" /><figcaption>Difference between Supervised Learning and Unsupervised Learning</figcaption></figure><p><strong>Reinforcement Learning (Semi-supervised Learning):</strong><br>In Reinforcement Learning, the algorithm learns itself to control a dynamic system (environment). It tries to find a model to achieve the desired behavior (exploration), or keep the best possible state on a specific task (exploitation).</p><p><em>e.g.: Helicopter autopilot, Self driving cars, Ad placements etc.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqfJFN3ZME-ONqdH4r7nJg.jpeg" /><figcaption><strong>Reinforcement Learning</strong></figcaption></figure><p>Here, a software agent takes actions in an environment in order to maximize the cumulative reward and applies observations to improve performance. Exploration vs exploitation trade-off is an issue which should be taken into account while designing algorithm for Reinforcement Learning.</p><p><strong>Model space / Language bias / Parameter space / Hypothesis space</strong>:<br>Set of all models or classifiers, θ<em> </em>∈ Θ.</p><p><strong>Useful terms of a dataset</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQdcxnkiXOiCAlCP5JFr3A.jpeg" /><figcaption><strong>A Dataset</strong></figcaption></figure><p><strong>Loss function:</strong><br>Measures how well a model fits the data. It calculates the error between target and the predicted value, ℓ(f(xᵢ), yᵢ). Loss will converge into global minimum (lowest value) only if the loss function is convex (if a line is drawn between <em>any</em> two points of the function, the line will be above all other points between those points).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2XlgAgBmtqcC3rSS7OLezg.jpeg" /><figcaption>Convex and Non-convex functions</figcaption></figure><p>Here are several types of loss functions (L0, L1, L2<strong> </strong>are norms):<br>1. <strong>L0 loss / Zero-one loss:</strong> The error is 0 if target and predicted value are same, otherwise 1. In practice, if the signs (positive or negative) of target value and predicted value are same, then error is 0. Used in <strong>Linear</strong> <strong>classification</strong>. It is not convex, thus difficult to minimize!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULjoSxg21LsHfX6HWxFQ0Q.png" /></figure><p>2. <strong>L1 loss / Absolute loss</strong>: Absolute value of the difference between target and predicted value. It has no tolerance towards outliers. Loss ranges 0 to +inf. Used in regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJgfGlt0rmCYf9avxvcuKQ.png" /></figure><p>A commonly used variant is <strong>Mean absolute error (MAE)</strong>. It is the mean absolute loss on all data points. MAE is sensitive towards outliers and the optimal prediction will be <em>median</em> target value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUJPSpQCn73bHlv9f0svbA.png" /></figure><p>3. <strong>L2 Loss / Quadratic loss / Squared loss</strong>: Squared value of the difference between target and predicted value. Used in regression. It is slightly tolerant to smaller errors. Since the errors are squared, it gives a relatively high weight to larger errors. Loss ranges 0 to +inf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuxHN64pVHTC3_a4G7vvGg.png" /></figure><p>A commonly used variant is <strong>Mean squared error (MSE)</strong>. It is the mean value of squared loss on all data points. It is sensitive towards outliers. MSE is good to use on normally distributed data around a mean value, and when it is important to penalize outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P41nroPcI3yoN9phHsdHJA.png" /></figure><p>Another loss function is <strong>Root Mean squared error (RMSE)</strong>. It is the square root of MSE. RMSE is thus the distance, on average, of a data point from the fitted line, measured along a vertical line. RMSE is directly interpretable in terms of measurement units, and so is a better measure of goodness of fit than a <em>correlation coefficient</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fD4YrRAgYNEQDvkEG1snNw.png" /></figure><p>4. <strong>ɛ-intensive Loss</strong>:<br>The loss function is not 0 if the absolute error minus ɛ is greater than 0<em>. </em>Here<em>, </em>ɛ is a predetermined parameter of maximal-margin of error. It is more fault tolerant than MAE or MSE as it ignores wrong predictions within the margin. It is used in <strong>Support Vector Regression (SVR)</strong> to provide robust regression estimates. Loss ranges between ɛ to +inf or 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFtCXr8s_wjRCiw6NJiMnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cG8PticTShrPX7qNgmUyCQ.png" /><figcaption>SVM in regression setting: <strong>a</strong> <em>ε</em>-regression and <strong>b</strong> error function (Image source: springer)</figcaption></figure><p>5. <strong>Perceptron Loss:</strong><br>It is convex. If classified correctly, the error is 0. However, for misclassified predictions, error is not 1, it is the negative product of target and predicted value. Used in <strong>Perceptron algorithm</strong> for classification. Loss ranges 0 to +inf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MM7WtfxtZZSt2HKcsOoVA.png" /></figure><p>6. <strong>Hinge loss:<br></strong>Used for “maximum-margin” classification, most notably for <strong>Support vector machine (SVM)</strong>. It is often used for <strong>binary classification</strong> problems. When using hinge loss, it is important to change the class labels to -1 and +1. Hinge Loss penalizes both wrong predictions and the right predictions that are not confident. Loss ranges 1 to +inf or 0. Hinge loss is not differentiable but it is convex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdyRy1ctRbzuAOz9zuWifA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GnOC5Qd3zVQUGWnmvOGaQ.png" /><figcaption>Plots of various loss functions as a function of the relation between predicted and target values. The loss is closest to 0 when the predicted value equals the target. (Image source: peltarion)</figcaption></figure><p>The <strong>Squared hinge</strong> <strong>loss</strong> is used for “maximum margin” <strong>binary classification </strong>problems. The hinge loss guarantees that, during training the classifier will find the <em>classification boundary</em> which is the furthest apart from each of the different classes of data points as possible. In other words, it finds the classification boundary that guarantees the maximum margin between the data points of the different classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48AAwOE8xg6vRNe3DOtJfg.png" /></figure><p>Squared Hinge loss is used for problems involving yes/no (binary) decisions and not interested in knowing how certain the classifier is about the classification (i.e., classification probabilities). It is used in combination with the tanh() activation function in the last layer to keep the output between -1 to +1.<br>e.g: Email classification to ‘spam’ and ‘not spam’.</p><p>7. <strong>Logistic loss</strong>:<br>It is a convex function. The error is practically never 0. Used in classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2v7JvLNE32wpzOdTaJHlA.png" /></figure><p>8. <strong>Poisson Loss</strong>:<br>It is used for regression when modeling count data that follows the Poisson distribution. Minimizing the Poisson loss is equivalent of maximizing the likelihood of the data under the assumption that the target comes from a Poisson distribution, conditioned on the input.<br>e.g: churn of customers next week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFyHkjVe65a9CKvFgU8FSQ.png" /></figure><p>9. <strong>Cross Entropy</strong>:<br>Cross-entropy is a measure of the difference between two probability distributions for a given random variable or set of events. These loss functions are usually used in neural networks.</p><p><strong>Entropy</strong> is the number of bits required to transmit a randomly selected event from a probability distribution. Skewed distributions have low entropy, distributions where events have equal probability has larger entropy.</p><p><strong>Categorical cross entropy</strong> is a loss function that is used in multi-class classification tasks. It is designed to quantify the difference between two probability distributions. The target must be one-hot encoded. <em>Softmax</em> activation function is used with it. <br>e.g: MNIST hand written digit recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrPNSH--prCSH4_c7e4tJg.png" /></figure><p><strong>Sparse categorical cross entropy</strong> is similar to categorical cross entropy, only difference is it uses only one value as target. It saves memory as well as computation time because it stores a single integer for a class instead of a one-hot vector.</p><p><strong>Binary Cross Entropy</strong> is a loss function used in binary classification tasks. It is equal to the average of the categorical cross entropy loss on many two-category tasks. It is very convenient to train a model to solve many classification problems at the same time, if each classification can be reduced to a binary choice (i.e. yes or no, A or B, 0 or 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwyllUTup1hW-HQlDhYdEw.png" /></figure><p>The binary cross entropy needs to compute the logarithms of prediction​ and (1 − prediction), which only exist if prediction​​ is between 0 and 1. The <em>sigmoid</em> activation function is the only one to guarantee that the output is within this range.<br>e.g: Tag songs with genre.</p><p><strong>Cost function / Error function</strong>:<br>The loss function is calculated at every instance but the cost function deals with a penalty for a training set or a complete batch. The cost function is calculated as an average of loss functions. For a single training cycle or epoch, loss is calculated numerous times, but the cost function is only calculated once.</p><p>(Next chapter — Regularizer, Risk, Problem analysis, Data Preprocessing)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8850ec5b4243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Python Code Snippets]]></title>
            <link>https://bedouin7.medium.com/useful-python-code-snippets-3aaf47e04d1b?source=rss-e364f40f8219------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aaf47e04d1b</guid>
            <dc:creator><![CDATA[Bedouin]]></dc:creator>
            <pubDate>Mon, 25 May 2020 21:43:57 GMT</pubDate>
            <atom:updated>2023-03-04T18:51:42.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*uBe975tBtLdW2KghZk0eDg.png" /></figure><ol><li><strong>Equal list</strong>: Checks if all elements in a list are equal. Use [1:] and [:-1] to compare all the values in the given list.</li></ol><pre>def all_equal(lst):<br>  return lst[1:] == lst[:-1]<br><br>all_equal([1, 2, 3, 4, 5, 6]) # False<br>all_equal([1, 1, 1, 1]) # True</pre><p><strong>2.</strong> <strong>Unique items in list</strong>: Returns True if all the values in a list are unique, False otherwise. Use set() on the given list to remove duplicates, use len() to compare its length with the length of the list.</p><pre>def all_unique(lst):<br>  return len(lst) == len(set(lst))<br><br>x = [1, 2, 3, 4, 5, 6]<br>y = [1, 2, 2, 3, 4, 5]<br>all_unique(x) # True<br>all_unique(y) # False</pre><p><strong>3. Mean</strong>: Returns the average of two or more numbers. Use sum() to sum all of the args provided, divide by len(args).</p><pre>def mean(*args):<br>  return sum(args, 0.0) / len(args)<br><br>mean(*[1, 2, 3]) # 2.0<br>mean(1, 2, 3) # 2.0</pre><p><strong>Mean after mapping:</strong> Returns the average of a list, after mapping each element to a value using the provided function. Use map() to map each element to the value returned by fn. Use sum() to sum all of the mapped values, divide by len(lst).</p><pre>def mean_by(lst, f=lambda el: el):<br>  return sum(map(f, lst), 0.0) / len(lst)<br><br>mean_by([{ &#39;n&#39;: 4 }, { &#39;n&#39;: 2 }, { &#39;n&#39;: 8 }, { &#39;n&#39;: 6 }], lambda p: p[&#39;n&#39;]) # 5.0</pre><p><strong>4. Split list:</strong> Splits values into two groups. If an element in filter is True, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group. Use list comprehension and enumerate() to add elements to groups, based on filter.</p><pre>def split_list(lst, filter):<br>  return [<br>    [x for i, x in enumerate(lst) if filter[i] == True],<br>    [x for i, x in enumerate(lst) if filter[i] == False]<br>  ]<br><br>split_list(<br>  [&#39;beep&#39;, &#39;boop&#39;, &#39;foo&#39;, &#39;bar&#39;], <br>  [True, True, False, True]<br>) # [ [&#39;beep&#39;, &#39;boop&#39;, &#39;bar&#39;], [&#39;foo&#39;] ]</pre><p><strong>Split list by function:</strong> Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. If the function returns True, the element belongs to the first group; otherwise, it belongs to the second group. Use list comprehension to add elements to groups, based on fn.</p><pre>def split_by(lst, fn):<br>  return [<br>    [x for x in lst if fn(x)],<br>    [x for x in lst if not fn(x)]<br>  ]<br><br>split_by(<br>  [&#39;beep&#39;, &#39;boop&#39;, &#39;foo&#39;, &#39;bar&#39;], <br>  lambda x: x[0] == &#39;b&#39;<br>) # [ [&#39;beep&#39;, &#39;boop&#39;, &#39;bar&#39;], [&#39;foo&#39;] ]</pre><p><strong>5. String byte length:</strong> Returns the length of a string in bytes. Use s.encode(&#39;utf-8&#39;) to encode the given string and return its length.</p><pre>def byte_size(s):<br>  return len(s.encode(&#39;utf-8&#39;))<br><br>byte_size(&#39;😀&#39;) # 4<br>byte_size(&#39;Hello World&#39;) # 11</pre><p><strong>6. Camelcase string:</strong> Converts a string to camelcase. Use re.sub() to replace any - or _ with a space, using the regexp r&quot;(_|-)+&quot;. Use title() to capitalize the first letter of each word convert the rest to lowercase. Finally, use replace() to remove spaces between words.</p><pre>from re import sub<br><br>def str_camelcase(s):<br>  s = sub(r&quot;(_|-)+&quot;, &quot; &quot;, s).title().replace(&quot; &quot;, &quot;&quot;)<br>  return s[0].lower() + s[1:]<br><br>str_camelcase(&#39;some_database_field_name&#39;) # &#39;someDatabaseFieldName&#39;<br>str_camelcase(&#39;Some label that needs to be camelized&#39;) # &#39;someLabelThatNeedsToBeCamelized&#39;<br>str_camelcase(&#39;some-javascript-property&#39;) # &#39;someJavascriptProperty&#39;<br>str_camelcase(&#39;some-mixed_string with spaces_underscores-and-hyphens&#39;) # &#39;someMixedStringWithSpacesUnderscoresAndHyphens&#39;</pre><p><strong>7. Capitalize string:</strong> Capitalizes the first letter of a string. Capitalize the first letter of the string and then add it with rest of the string. Omit the lower_rest parameter to keep the rest of the string intact, or set it to True to convert to lowercase.</p><pre>def str_capitalize(s, lower_rest=False):<br>  return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])<br><br>str_capitalize(&#39;fooBar&#39;) # &#39;FooBar&#39;<br>str_capitalize(&#39;fooBar&#39;, True) # &#39;Foobar&#39;</pre><p>Use s.title() to capitalize first letter of every word in the string.</p><p><strong>Decapitalize:</strong> Decapitalize the first letter of the string and then add it with rest of the string. Omit the upper_rest parameter to keep the rest of the string intact, or set it to True to convert to uppercase.</p><pre>def decapitalize(s, upper_rest=False):<br>  return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])<br><br>decapitalize(&#39;FooBar&#39;) # &#39;fooBar&#39;<br>decapitalize(&#39;FooBar&#39;, True) # &#39;fOOBAR&#39;</pre><p><strong>8. Property of object: </strong>Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate. Return a lambda function that takes an object and applies the predicate function, fn to the specified property.</p><pre>def check_prop(fn, prop):<br>  return lambda obj: fn(obj[prop])<br><br>check_age = check_prop(lambda x: x &gt;= 18, &#39;age&#39;)<br>user = {&#39;name&#39;: &#39;Mark&#39;, &#39;age&#39;: 18}<br><br>check_age(user) # True</pre><p><strong>9. Batch:</strong> Chunks a list into smaller lists of a specified size. Use list() and range() to create a list of the desired size. Use map() on the list and fill it with splices of the given list. Finally, return the created list.</p><pre>from math import ceil<br><br>def batch(lst, size):<br>  return list(<br>    map(lambda x: lst[x * size:x * size + size],<br>      list(range(0, ceil(len(lst) / size)))))<br><br>batch([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],5]</pre><p><strong>10. Invert dictionary:</strong> Inverts a dictionary with non-unique hashable values. Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dictionary.setdefault(), list() and append() to create a list for each one.</p><pre>def inverse_dict(obj):<br>  inv_obj = {}<br>  for key, value in obj.items():<br>    inv_obj.setdefault(value, list()).append(key)<br>  return inv_obj<br><br>ages = {<br>  &quot;Car&quot;: 5,<br>  &quot;Bat&quot;: 5,<br>  &quot;Ball&quot;: 8,<br>}<br>inverse_dict(ages) # { 5: [&quot;Car&quot;, &quot;Bat&quot;], 8: [&quot;Ball&quot;] }</pre><p><strong>11. Drop false value:</strong> Removes false values from a list. Use filter() to filter out false values (False, None, 0, and &quot;&quot;).</p><pre>def dropna(lst):<br>  return list(filter(None, lst))<br><br>dropna([0, 5, False, 3, &#39;&#39;, None, 1, &#39;b&#39;, &#39;K&#39;, 78]) # [ 5, 3, 1, &#39;b&#39;, &#39;K&#39;, 78 ]</pre><p><strong>12. Deep flatten list</strong>: Use recursion. Use isinstance() with collections.abc.Iterable to check if an element is iterable. If it is, apply deep_flatten() recursively, otherwise return [lst].</p><pre>from collections.abc import Iterable<br><br>def deep_flatten(lst): <br>  return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]<br><br>deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aaf47e04d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>