<?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 Bob Chesebrough on Medium]]></title>
        <description><![CDATA[Stories by Bob Chesebrough on Medium]]></description>
        <link>https://medium.com/@zmadscientist?source=rss-bcad9f1c533b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bbXcjLCmiaCpo1D6.</url>
            <title>Stories by Bob Chesebrough on Medium</title>
            <link>https://medium.com/@zmadscientist?source=rss-bcad9f1c533b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zmadscientist/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[Clustering Time Series with PCA and DBSCAN]]></title>
            <link>https://medium.com/intel-analytics-software/clustering-time-series-with-pca-and-dbscan-f9f98851f8ec?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f98851f8ec</guid>
            <category><![CDATA[dbscan]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pca-analysis]]></category>
            <category><![CDATA[intel]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 01:27:36 GMT</pubDate>
            <atom:updated>2024-07-19T17:56:26.573Z</atom:updated>
            <content:encoded><![CDATA[<h4>Accelerating These Algorithms Using Intel Extension for Scikit-learn</h4><p>In this article, we’ll explore the clustering of time series data using Principal Component Analysis (PCA) for dimensionality reduction and Density-Based Spatial Clustering of Applications with Noise (DBSCAN) for clustering. This technique identifies patterns in time series data, such as traffic flow in a city, without requiring labeled data. We’ll be using <a href="https://www.intel.com/content/www/us/en/developer/tools/oneapi/scikit-learn.html#gs.buohts">Intel Extension for Scikit-learn</a> to accelerate performance.</p><p>Time series data often exhibit repetitive patterns due to human behavior, machinery, or other measurable sources. Identifying these patterns manually can be challenging. Unsupervised learning approaches like PCA and DBSCAN enable us to discover these patterns.</p><h3><strong>Methodology</strong></h3><h4><strong>Data Generation</strong></h4><p>We generate synthetic waveform data to simulate time series patterns. The data consists of three distinct waveforms, each with added noise to simulate real-world variability. We’ll use the scikit-learn agglomerative clustering example authored by Gael Varoquaux (Figure 1). It is available under BSD 3-Clause or CC-0 licenses.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>np.random.seed(0)<br>n_features = 2000<br>t = np.pi * np.linspace(0, 1, n_features)<br><br>def sqr(x):<br>    return np.sign(np.cos(x))<br><br>X = []<br>y = []<br>for i, (phi, a) in enumerate([(0.5, 0.15), (0.5, 0.6), (0.3, 0.2)]):<br>    for _ in range(30):<br>        phase_noise = 0.01 * np.random.normal()<br>        amplitude_noise = 0.04 * np.random.normal()<br>        additional_noise = 1 - 2 * np.random.rand(n_features)<br>        additional_noise[np.abs(additional_noise) &lt; 0.997] = 0<br>        X.append(12 * ((a + amplitude_noise) * (sqr(6 * (t + phi + phase_noise))) + additional_noise))<br>        y.append(i)<br><br>X = np.array(X)<br>y = np.array(y)<br><br>plt.figure()<br>plt.axes([0, 0, 1, 1])<br>for l in range(3):<br>    plt.plot(X[y == l].T, alpha=0.5, label=f&#39;Waveform {l+1}&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;Unlabeled Data&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*XwhMavDXJAJ3TQl3858n7g.png" /><figcaption>Figure 1. Code and plot generated by author from scikit-learn agglomerative clustering algorithm developed by Gael Varoquaux</figcaption></figure><h4><strong>Accelerating PCA and DBSCAN Using Intel Extension for Scikit-learn</strong></h4><p>Both PCA and DBSCAN can be accelerated via a patching scheme using Intel Extension for Scikit-learn. Scikit-learn (often referred to as sklearn) is a Python module for machine learning (ML). Intel Extension for Scikit-learn is one of <a href="https://www.intel.com/content/www/us/en/developer/tools/oneapi/ai-analytics-toolkit.html#gs.bupe8a">Intel’s AI tools</a> that seamlessly accelerates scikit-learn applications on Intel CPUs and GPUs in single- and multi-node configurations. It dynamically patches scikit-learn estimators to improve ML training and inference by up to 100x with equivalent mathematical accuracy (Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*zWAcqzag5lJRwMdMGCeXlA.png" /><figcaption>Figure 2. <a href="https://raw.githubusercontent.com/intel/scikit-learn-intelex/master/doc/sources/_static/scikit-learn-acceleration.PNG">Intel(R) Extension for Scikit-learn* github repository</a></figcaption></figure><p>Intel Extension for Scikit-learn uses the scikit-learn API and can be enabled from the command-line or by modifying a couple of lines of your Python application prior to importing scikit-learn:</p><pre>from sklearnex import patch_sklearn<br>patch_sklearn()</pre><h4><strong>Dimensionality Reduction Using PCA</strong></h4><p>Before attempting to cluster 90 samples, each containing 2,000 features, we will use PCA to reduce dimensionality while retaining 99% of the variance in the dataset:</p><pre>from sklearn.decomposition import PCA<br><br>pca = PCA(n_components=4)<br>XPC = pca.fit_transform(X)<br><br>print(&quot;Explained variance ratio:&quot;, pca.explained_variance_ratio_)<br>print(&quot;Singular values:&quot;, pca.singular_values_)<br>print(&quot;Shape of XPC:&quot;, XPC.shape)</pre><p>We use a pairplot to look for visible clusters in the reduced data (Figure 3):</p><pre>import pandas as pd<br>import seaborn as sns<br><br>df = pd.DataFrame(XPC, columns=[&#39;PC1&#39;, &#39;PC2&#39;, &#39;PC3&#39;, &#39;PC4&#39;])<br>sns.pairplot(df)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*E65TRmDWeTi9CtfEXk0i4A.png" /><figcaption>Figure 3. Looking for clusters in the data after dimensionality reduction</figcaption></figure><h4><strong>Clustering with DBSCAN</strong></h4><p>Based on the pairplot, PC1 and PC2 seem to separate the clusters well, so we’ll use these components for DBSCAN clustering. We can also get an estimate of the DBSCAN EPS parameter. I chose 50 because the PC1 vs PC0 diagram suggests that this is a reasonable separation distance for the observed clusters:</p><pre><br>from sklearn.cluster import DBSCAN<br><br>clustering = DBSCAN(eps=50, min_samples=3).fit(XPC[:, [0, 1]])<br>labels = clustering.labels_<br><br>print(&quot;Cluster labels:&quot;, labels)</pre><p>We can plot the clustered data to see how well DBSCAN has identified the clusters (Figure 4):</p><pre>plt.figure()<br>plt.axes([0, 0, 1, 1])<br>colors = [&quot;#f7bd01&quot;, &quot;#377eb8&quot;, &quot;#f781bf&quot;]<br>for l, color in zip(range(3), colors):<br>    plt.plot(X[labels == l].T, c=color, alpha=0.5, label=f&#39;Cluster {l+1}&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;PCA + DBSCAN&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*BY6qcjRZCWr3GnE1M4xkDw.png" /><figcaption>Figure 4. Plot of clustered data generated using the previous code example</figcaption></figure><h3>Comparing with Ground Truth</h3><p>As you can see from Figure 4, the DBSCAN does a good job at finding the plausible colored clusters and compares well to the original ground truth data (Figure 1). In this case, the clustering recovered the underlying patterns used to generate the data perfectly. By using PCA for dimensionality reduction and DBSCAN for clustering, we can effectively identify and label patterns in time series data. This approach allows for the discovery of underlying structures in the data without the need for labeled samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f98851f8ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-analytics-software/clustering-time-series-with-pca-and-dbscan-f9f98851f8ec">Clustering Time Series with PCA and DBSCAN</a> was originally published in <a href="https://medium.com/intel-analytics-software">Intel Analytics Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Transformer-Based Time Series Predictor]]></title>
            <link>https://medium.com/intel-analytics-software/transformer-based-time-series-predictor-on-intel-tiber-developer-cloud-057fc485a22c?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/057fc485a22c</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[intel-tiber]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 22:10:01 GMT</pubDate>
            <atom:updated>2024-09-03T14:41:23.447Z</atom:updated>
            <content:encoded><![CDATA[<h4>Easy Time Series Analysis Using Intel Tiber Developer Cloud</h4><p>I’ve been working with several clients lately who all seemed to be focused on time series analysis. This was a great excuse to explore current and older methods of time series prediction and clustering. I decided to break this experimentation into two articles: this one, on time series prediction, and another on a time series clustering trick using principal components analysis and DBSCAN.</p><p><a href="https://medium.com/intel-analytics-software/clustering-time-series-with-pca-and-dbscan-f9f98851f8ec">Clustering Time Series with PCA and DBSCAN</a></p><p>A Google search on Hugging Face community indicates there is a model called <a href="https://huggingface.co/papers/2403.07815">Chronos</a> for this, but the GitHub location was missing from the model card, so a little more searching lead me to a nice starting example from <a href="https://github.com/amazon-science/chronos-forecasting">amazon-science</a>. An explanation of <a href="https://huggingface.co/papers/2403.07815">Chronos</a> and <a href="https://auto.gluon.ai/stable/index.html">AutoGluon</a> are beyond the scope of this article, but I encourage you to study the references. The concise description of what AutoGluon does, from their webpage, is:</p><pre>Via a simple fit() call, AutoGluon can train and tune<br>- simple forecasting models (e.g., ARIMA, ETS, Theta),<br>- powerful deep learning models (e.g., DeepAR, Temporal Fusion Transformer),<br>- tree-based models (e.g., LightGBM),<br>- an ensemble that combines predictions of other models<br><br>to produce multi-step ahead probabilistic forecasts for univariate time series data.</pre><h3><strong>Intel Tiber Developer Cloud</strong></h3><p>I decided to showcase my example using a free account on Intel Tiber Developer Cloud, which is an awesome and powerful sandbox for exploration. Below are the steps to get my initial project working. I hope to follow-up on this example in a future article showing how to quantize the pipeline and perhaps run it on <a href="https://www.intel.com/content/www/us/en/products/details/discrete-gpus/data-center-gpu/max-series.html">Intel Data Center GPU Max Series</a>. For now, the example uses a 4th Gen Intel Xeon Scalable Processor. I already have an account on the Intel Tiber Developer Cloud, but you can enroll for free at the link below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*7SB35-IjdB-oHTzaiRcD2Q.png" /><figcaption><a href="https://www.intel.com/content/www/us/en/developer/tools/devcloud/services.html">https://www.intel.com/content/www/us/en/developer/tools/devcloud/services.html</a></figcaption></figure><p>The next step was to launch my Jupyter Hub instance on Tiber by selecting “Training” in the lefthand menu panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*-E3iDXh0klbHw5q60QMF9g.png" /></figure><p>Next, I launched my Jupyter instance by clicking the “Launch JupyterLab” button in the upper right of the Training page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*0m9XYKs8JCX3Q6JuvyF8zQ.png" /></figure><p>Upon login, I am greeted with a JupyterLab interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSAmI--0vSbSFonBeN5RAA.png" /></figure><p>I added a folder called “Unsupervised” followed by a subfolder called “Chronos” as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*hKKgzhzqB9OoqaTZCkVMLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*QXXIpjHzoznAMSNGEFNSug.png" /></figure><p>From the Launcher, I created a new notebook that uses the preconfigured “PyTorch GPU” kernel. The code for the project can be found in my git repository: <a href="https://github.com/zmadscientist/ChronosTimeSeriesPredictor">ChronosTimeSeriesPredictor</a>. Launch a terminal session to run the Git commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*BBoNOFVYBQLt6AYp1WFNqQ.png" /></figure><p>This will create a browser tab with your Bash shell terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*9YmlcjfY-H4Ur1C2oC-gcg.png" /></figure><p>Simply mkdir Unsupervised, then git clone the repository in the directory, as follows:</p><pre>mkdir Unsupervised<br>cd Unsupervised/<br>git clone https://github.com/zmadscientist/ChronosTimeSeriesPredictor.git</pre><h3>Create a New Notebook for the Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*xyEKL1ECkWa6vRV_fayXpg.png" /></figure><p>I added the following text cell to describe the purpose of the notebook:</p><pre># Time Series Prediction<br><br>Note:<br>Stop all kernels and be sure to select the PyTorch GPU kernel<br>This data used in this exercise was synthesized after reconstructing and digitizing an electrical grid plot from Toronto-Hydro-Transformer-Monitors then finding the mean and standard deviation for every time slice in the constructed graph for several days&#39; worth of data. This provided a Gaussian distribution that could be sampled to generate an infinite number of days worth of data. Several such days of synthetic data have been saved in anomaly.csv.<br><br>We use this data as a starting point to generate new data in the desired Chronos format: anomalySeries.csv<br><br>You can follow the tutorial from Article: Forecasting with Chronos which was of great help getting started<br><br>https://auto.gluon.ai/stable/tutorials/timeseries/forecasting-chronos.html</pre><h4><strong>Retrieve the Data and Install the Libraries</strong></h4><p>I will be using time series data I generated for another project that is based on electrical grid data I found online from Toronto Hydro titled, <a href="https://www.scribd.com/document/452407468/Toronto-Hydro-Transformer-Monitors">Toronto-Hydro-Transformer-Monitors</a>.</p><p>Install the necessary libraries using pip. The key libraries are torch, torchvision, autogluon, and chronos. I included these lines in a Jupyter cell, simply uncomment and run the cell. The installation will take several minutes!</p><pre># !pip install -U pip<br># !pip install -U setuptools wheel<br># # CPU version of pytorch has smaller footprint - see installation instructions in<br># #pytorch documentation - https://pytorch.org/get-started/locally/<br># ! pip install torch==2.3.1 torchvision==0.18.1 - index-url https://download.pytorch.org/whl/cpu<br># ! pip install autogluon<br># !pip install git+https://github.com/amazon-science/chronos-forecasting.git</pre><p>Finally, run this cell to import the modules:</p><pre>from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>import torch<br>from chronos import ChronosPipeline<br>from tqdm.auto import tqdm</pre><h4>Explore the Data</h4><p>Notice the regular daily periodicity and the somewhat irregular nature of the electric grid values bounded and constrained within a statistical envelope for each day. This data was generated by tracking a mean and standard deviation for every ten-minute interval each day for multiple days. I modeled each time slice as having its own mean and standard deviation and assumed a Gaussian distribution that I later sample to generate an infinite amount of data:</p><pre>import matplotlib.pyplot as plt <br>import pandas as pd<br>df = pd.read_csv(&quot;anomalySeries.csv&quot;)<br>plt.plot( df.target[-500:])<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*RmCHRcBWK3NGGz2peOEA6A.png" /></figure><h4>Prepare the Chronos Pipeline Parameters</h4><pre>pipeline = ChronosPipeline.from_pretrained(<br>  &quot;amazon/chronos-t5-base&quot;,<br>  device_map=&quot;cpu&quot;, <br>  torch_dtype=torch.bfloat16,<br>)</pre><h4>Read the Time Series</h4><pre># Put into TimeSeries format<br>import matplotlib.pyplot as plt<br>data = TimeSeriesDataFrame(&quot;anomalySeries.csv&quot;)</pre><p>Specify a prediction length and fit a Chronos predictor using the Chronos_tiny model:</p><pre>prediction_length = 24<br>train_data, test_data = data.train_test_split(prediction_length)<br><br>predictor = TimeSeriesPredictor(prediction_length=prediction_length).fit(<br>    train_data, presets=&quot;chronos_tiny&quot;,<br>)</pre><h4>Fit the Training Data</h4><pre>predictor = TimeSeriesPredictor(prediction_length=prediction_length).fit(<br>    train_data,<br>    hyperparameters={<br>        &quot;Chronos&quot;: {<br>            &quot;model_path&quot;: &quot;tiny&quot;,<br>            &quot;batch_size&quot;: 64,<br>            &quot;device&quot;: &quot;cpu&quot;,<br>        }<br>    },<br>    skip_model_selection=True,<br>    verbosity=0,<br>)</pre><h4>Predict the Test Data</h4><pre>predictions = predictor.predict(test_data)<br>Len = data.shape[0]<br>predictor.plot(<br>    data=data, <br>    predictions=predictions, <br>    item_ids=[&quot;Series&quot;],<br>    max_history_length=Len,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0wlTyiYgpi__XfPHo5rbQ.png" /><figcaption>Prediction (orange line) for Test Data by Chronos</figcaption></figure><h3>Summary</h3><p>You can see how easy it is to obtain a free account on the <a href="https://www.intel.com/content/www/us/en/developer/tools/devcloud/services.html">Intel Tiber Developer Cloud</a> and use the Chronos model to quickly train and predict time series. I encourage you to give it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057fc485a22c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-analytics-software/transformer-based-time-series-predictor-on-intel-tiber-developer-cloud-057fc485a22c">Implementing a Transformer-Based Time Series Predictor</a> was originally published in <a href="https://medium.com/intel-analytics-software">Intel Analytics Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Monocular Depth Estimation to Mask an Image]]></title>
            <link>https://medium.com/intel-analytics-software/using-monocular-depth-estimation-to-mask-an-image-40bca39ed828?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/40bca39ed828</guid>
            <category><![CDATA[dpt]]></category>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[depth-estimation]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 19:32:30 GMT</pubDate>
            <atom:updated>2024-05-09T21:13:17.425Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or, How I Selected a Dinosaur and Isolated It Out of a Flat Image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1j4M8UNDn3dPLSHJpWFhA.png" /><figcaption>Image by author</figcaption></figure><p>In this article, I will guide you through the steps I took to create a clipped image with background clutter removed from the image. I will accomplish this using monocular depth estimation. This could potentially be used to automate structure from motion and other image-related tasks where you want to highlight or focus on a single portion of an image, particularly for identifying parts of the image that were closest to the camera. Specifically, I use depth estimation on a couple of images that I took at a natural history museum. The challenge I gave myself was to capture just the dinosaur in the foreground, eliminating the background murals, lights, and building structure. The cool thing about this algorithm is that it creates a depth estimate from a single image!</p><h3><strong>Monocular Depth Estimation (DPT)</strong></h3><p>Monocular depth estimation, aiming to infer detailed depth from a single image or camera view, finds applications in fields like generative AI, 3D reconstruction, and autonomous driving. However, deriving depth from individual pixels in a single image is challenging due to the under-constrained nature of the problem. Recent advancements attribute progress to learning-based methods, particularly with MiDaS, leveraging dataset mixing and scale-and-shift-invariant loss. MiDaS has evolved with releases featuring more powerful backbones and lightweight variants for mobile use. With the rise of transformer architectures in computer vision, including those pioneered by models like ViT, there’s been a shift toward using them for depth estimation. Inspired by this, MiDaS v3.1 incorporates promising transformer-based encoders alongside traditional convolutional ones, aiming for a comprehensive investigation of depth estimation techniques. The paper focuses on describing the integration of these backbones into MiDaS, providing a thorough comparison of different v3.1 models, and offering guidance on utilizing future backbones with MiDaS.</p><p>This DPT model, created by Intel, uses the Hugging Face <a href="https://huggingface.co/docs/transformers/model_doc/beit">BEiT</a> model as the backbone and adds a neck + head on top for monocular depth estimation. It is called dpt-beit-large-512 (but we have more compact resolutions as well). This model is based on a resolution of 512 x 512 internally, but images of any size can be inferred against this model. For more information, see a condensed explanation on Hugging Face Model Card, <a href="https://huggingface.co/Intel/dpt-beit-large-512">dpt-beit-large-512</a> or a deeper dive explanation in the paper, <a href="https://arxiv.org/pdf/2307.14460">MiDaS v3.1 — A Model Zoo for Robust Monocular Relative Depth Estimation</a> by Reiner Birkl, Diana Wofk, Matthias Muller.</p><h3>Coding Steps</h3><p>Install the requisite libraries from a bash terminal or a Jupyter notebook cell (remember to add the ! in front of pip) that are required by <a href="https://huggingface.co/Intel/dpt-beit-large-512">dpt-beit-large-512</a>:</p><pre># bash<br>pip install transformers==4.34.1<br>pip install intel_extension_for_transformers==1.2.2<br>pip install intel_extension_for_pytorch==2.1.100<br>pip install tqdm<br>pip install einops<br>pip install neural_speed==0.2<br>pip install torch==2.1.1</pre><p>Import the libraries in the Jupyter notebook, python script, or editor.</p><pre>import torch<br>print(torch.__version__)<br>import transformers<br>print(transformers.__version__)<br>from transformers import DPTImageProcessor, DPTForDepthEstimation<br>import torch<br>import numpy as np<br>from PIL import Image<br>import requests</pre><p>Load the image:</p><pre># python<br>path = &quot;image/DSC_0566.png&quot;<br>image = Image.open(path)<br>MAX_SIZE = (600, 400)<br>image.thumbnail(MAX_SIZE)</pre><p>Notice that the dinosaur, stegosaurus, is placed in front of a painted mural — making separation a more manual task with many common methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*kL0-XFoLPqjp_ofPK_3n4g.png" /><figcaption>Image by author</figcaption></figure><p>Load the Intel/dpt-beit-large-512 model and generate the depth estimate. Notice how the mural all but disappears while the stegosaurus pops to the front.</p><pre>processor = DPTImageProcessor.from_pretrained(&quot;Intel/dpt-beit-large-512&quot;)<br>model = DPTForDepthEstimation.from_pretrained(&quot;Intel/dpt-beit-large-512&quot;)</pre><pre># prepare image for the model<br> inputs = processor(images=image, return_tensors=&quot;pt&quot;)<br> with torch.no_grad():<br> outputs = model(**inputs)<br> predicted_depth = outputs.predicted_depth<br># interpolate to original size<br> prediction = torch.nn.functional.interpolate(<br> predicted_depth.unsqueeze(1),<br> size=image.size[::-1],<br> mode=&quot;bicubic&quot;,<br> align_corners=False,<br> )<br># prepare image for the model<br> inputs = processor(images=image, return_tensors=&quot;pt&quot;)<br> with torch.no_grad():<br> outputs = model(**inputs)<br> predicted_depth = outputs.predicted_depth<br># interpolate to original size<br> <br> prediction = torch.nn.functional.interpolate(<br> predicted_depth.unsqueeze(1),<br> size=image.size[::-1],<br> mode=&quot;bicubic&quot;,<br> align_corners=False,<br> )<br># visualize the prediction<br> output = prediction.squeeze().cpu().numpy()<br> formatted = (output * 255 / np.max(output)).astype(&quot;uint8&quot;)<br> depth = Image.fromarray(formatted)<br> depth</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*gPLwcGQk8Ldocqs-THVJbQ.png" /><figcaption>Image by author</figcaption></figure><p>Create BW mask from the depth estimate:</p><pre>Threshold = 45<br>a = np.array(depth)<br>b = np.where(a&gt;Threshold,a,0)<br>b[b&gt;Threshold] = 255<br>mask = Image.fromarray(b).convert(&#39;L&#39;)<br>black = Image.fromarray(a*0).convert(&#39;L&#39;)<br>mask.convert(&#39;RGB&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*W_Q0rjzJv1PeF_ChSDKg3Q.png" /></figure><p>Composite the image and the mask:</p><pre>out = Image.composite(image.convert(&#39;RGBA&#39;), black.convert(&#39;RGBA&#39;), mask.convert(&#39;1&#39;))<br>out.convert(&#39;RGB&#39;).show()</pre><p>Notice that the depth estimation completely masked out the background mural painting and let me select just the foreground dinosaur!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*CLILi4uerYZQu9m-1eBJqQ.png" /></figure><h3>Pottery in Museum Example:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*ekTPWfC6Lt_Lqyl89LEK8A.png" /><figcaption>Image by author</figcaption></figure><p>We’ll use the same code as above, but with two changes:</p><pre># first cell<br><br>path = &quot;image/DSC_0566.png&quot;<br>image = Image.open(path)<br>MAX_SIZE = (600, 400)<br>image.thumbnail(MAX_SIZE)</pre><pre># Threshold cell<br><br>Threshold = 155 # use 155 for Pottery<br>a = np.array(depth)<br>b = np.where(a&gt;Threshold,a,0)<br>b[b&gt;Threshold] = 255<br>mask = Image.fromarray(b).convert(&#39;L&#39;)<br>black = Image.fromarray(a*0).convert(&#39;L&#39;)<br>mask.convert(&#39;RGB&#39;).show()</pre><p>The following images show the depth estimate and the background removed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GidkndcyrD34KJ-xK0NLkA.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nM_3tfJlWrYJ14R5bdP6NQ.png" /><figcaption>image by author</figcaption></figure><p>You can experiment with these concepts and play with monocular depth estimation on the <a href="https://www.intel.com/content/www/us/en/developer/tools/devcloud/services.html?cid=sem&amp;source=sa360&amp;campid=2024_q1_satg_us_satgobm_satgobmpdt_traf_text-link_na_multi_cd_intel-developer-cloud-3500177611_google_b2b_oos_non-pbm_intel&amp;ad_group=generic_general-dev-cloud_b2b1-awa_multi&amp;intel_term=devcloud&amp;sa360id=43700079839960452&amp;gad_source=1&amp;gclid=Cj0KCQjw6PGxBhCVARIsAIumnWbSAy2Nnx2Kl6h7BYSnCYfxrsFtAuoXtyoRnccWb3ZJGahiooUy1KgaAlRcEALw_wcB&amp;gclsrc=aw.ds">Intel Developer Cloud</a>. It’s free to sign up and spend time on a really powerful server. The code for this article and the rest of the series is located on <a href="https://github.com/zmadscientist/DinosaurDepthMapClipping">GitHub</a>. For this article, experiment with the file: dpt_dino.ipynb<em>.</em> See the Hugging Face model card (<a href="https://huggingface.co/Intel/dpt-beit-large-512">https://huggingface.co/Intel/dpt-beit-large-512</a>) for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40bca39ed828" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-analytics-software/using-monocular-depth-estimation-to-mask-an-image-40bca39ed828">Using Monocular Depth Estimation to Mask an Image</a> was originally published in <a href="https://medium.com/intel-analytics-software">Intel Analytics Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Groundhog Day Prognostication on the future of AI]]></title>
            <link>https://medium.com/@zmadscientist/groundhog-day-prognostication-on-the-future-of-ai-96e6e03169a6?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e6e03169a6</guid>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[ai-pc]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[oneapi]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 18:15:35 GMT</pubDate>
            <atom:updated>2024-02-02T20:57:52.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uz49GttqTd5IwoD6qzC6yw.png" /><figcaption>DALL·E 2024–02–02 10.58.19 — A cartoon groundhog with glasses wearing a lab coat</figcaption></figure><p>I recently responded to a post on Reddit asking contributors to make a prediction that they feel will come true in the next 20 years especially regarding Artificial General Intelligence (AGI). So today, Feb 2, 2024, Groundhog day, I will make the following prognostications and reveal at the end if I see my groundhog shadow predicting another AI winter and dampening of the AI hype, or if I don’t see a shadow implying an early Spring for AI and possible establishment of AGI.</p><p><strong>First some level setting: </strong><br>I anticipate the emergence of Artificial General Intelligence (AGI) within the next 20 years but I envision it as an aggregation of specialized AI models rather than a single monolithic entity. I draw parallels with human intelligence, suggesting that just as individual humans excel in specific fields after education and training, AGI will thrive through the combination of various specialized AIs. My skepticism towards a monolithic AGI arises from the belief that, like humans, AI may possess flaws such as hallucinations, errors, and an inability to discern truth. Comparing to the high water mark of the diversity of human expertise, ranging from cardiology to creative arts, AI will also have high level moments. The key will be reducing or mitigating societal challenges when AI gets it wrong. The verdict: while a singular, flawless AGI may be unattainable, an assembly of carefully chosen, specialized AIs could collectively achieve what we currently define as AGI, meeting diverse human needs but not without challenges and imperfections.</p><p>After all, to quote Agent K (Tommy Lee Jones) from the 1997 movie Men in Black, <em>“A person is smart. People are dumb, panicky dangerous animals, and you know it” -</em> The same will be true for AI — Specialized AI will be smart, Generalized AGI will have societal flaws.</p><p><strong>Prediction</strong>: <strong>AI will provide a proof for one or more of the Clay mathematics Millennium problems.</strong> The seven problems, which were announced in 2000, are the Riemann hypothesis, P versus NP problem, Birch and Swinnerton-Dyer conjecture, Hodge conjecture, Navier-Stokes equation, Yang-Mills theory, and Poincaré conjecture. Mathematics proofs today involve highly specialized language, and influential papers provide new insights into techniques to solve logic problems and find patterns in that language or in patterns in logic — all these tasks are now a potentially open field for AI through some combination of LLMs, reinforcement learning, and pattern classification. My guess is that before 2030 one or more of these problems will be solved by AI and Mathematicians will invent a new set of math challenges to replace the current set.</p><p><strong>Prediction: New vaccines or medical treatments for diseases will arise specifically from advances in AI</strong></p><p>Google’s DeepMind AlphaFold is accelerating research in nearly every field of biology and in position to solve crucial problems like treatments for disease. I believe there will be big advancements in the field of Pharmaceuticals as a result of advances in protein folding and other biology related AI advances — learning to read DNA code better than we can today. Predictive health care will become a thing — predicting cancer or Alzheimer’s or Diabetes long before it can be tested clinically will lead to controversial treatments ahead of clinical diagnosis but will lead to improved health for many. Additionally, better prescriptive paths will be developed through AI. AI infused augmented reality devices and apps on phones will be common tools for diagnosing issues early.</p><p><strong>Prediction: New breed of digital assistant will be common in 10 years and make headlines</strong></p><p>A new type of digital assistant, much more powerful than anything today, Alexa on steroids, will find its way seamlessly into our lives in a continuity of experience and across our personal cloud spaces and social media to help inform and direct our steps, our career choices, our studies and more — helping especially the early adopters to have a significant advantage in the workplace. The Alexa killer will be announced in the next 10 years.</p><p><strong>Prediction: Big advances in stock market prediction thru AI, punctuated by big failures.</strong></p><p>Advances in Stock market analysis and AI driven index funds and fund managers leveraging AI will be the rule.</p><p>The main premise of Burton Malkiel’s “A Random Walk Down Wall Street” is the efficient market hypothesis, suggesting that it is difficult to consistently outperform the stock market through active stock picking and market timing. Malkiel argues that stock prices reflect all available information, and therefore, attempting to predict short-term price movements is akin to a random walk.</p><p>Malkiel’s premise will be tested by the success of funds whose underlying thesis centers on AI analytical tools and predictions. For a time, I predict that AI driven funds will beat the market until a financial glitch implicates AI algorithms as being culpable in a sharp market downturn — this will re-occur on multiple occasions — until an equilibrium establishes itself and the AI algorithms mature. Prediction the Stock market will become a very volatile place for the next 20 years, but funds run by AI will asymptotically beat historical returns on the stock market — challenging Malkiel’ premise.</p><p><strong>Prediction: AI will successfully model group behaviors and shape economic policy in the next 20 years</strong></p><p>New economic models will be discovered by AI which will help our understanding of both group behaviors and models in psychology. This will also feed the Stock market prediction models mentioned above.</p><p><strong>Prediction: The controversial idea of Universal Basic Income in the advent of job loss from pseudo-AGI will dominate political discussion</strong></p><p>On the other side of economic theory, the world will grapple on the political stage, once more, with the controversial idea of Universal Basic Income in the advent of job loss from pseudo-AGI — as people look to either limit AI in jobs roles or redefine how people are compensated and just what the future of “work” looks like. This will be the new controversial discussions we will be having in 20 years or less.</p><p><strong>Prediction:</strong> The hyped and hoped <strong>“Truth Detector” will NOT be found</strong> — though it will be claimed many times by people from all walks who believe one model or another favors their worldview and therefore must be the truth.</p><p><strong>Prediction</strong> — there will still be some mighty cold days ahead even if an early spring in AI is on the way. <strong>Hallucinations</strong>, overly emphatic model predictions that turn out to be wrong <strong>will make headlines</strong> and be part of our future, in 2024, and for a good chunk of the next 20 years</p><p><strong>Prediction: Paleontology and GIS mapping will benefit greatly from the new AI</strong></p><p>The ability to forecast where dinosaurs and other fossils might be found, and what species they represent and what environmental conditions were present will become apps on phones.</p><p>I am helping this future along by the way! This is me looking at my groundhog shadow. Come participate in my free Feb 6 workshop at PyTorch.org where I make a probabilistic heatmap of Jurassic dinosaur localities based on aerial photos trained to identify depositional environments! We will develop and AI model that runs quickly on Intel 4th generation Xeon Scalable processors as well as on Intel 1100 series GPU’s for the data center using Python, PyTorch, and some Intel AI libraries powered by oneAPI.</p><p><a href="https://community.linuxfoundation.org/events/details/lfhq-pytorch-foundation-presents-pytorch-webinar-dinosaur-bone-hunting-with-intel-ai/">PyTorch Webinar: Dinosaur Bone Hunting with Intel AI</a></p><p>Time: Feb 6 at 10 AM Pacific w duration of 1.5 hours</p><p><strong>Prediction: Model inference will be by far the dominant mode of interaction we have with AI in the next 20 years.</strong></p><p>While new models will be trained and get many headlines, the reality is that most of us will experience AI via apps and applications and API’s that inference against already built models in order to get answers to common everyday problems. This is related to the digital assistant topic I mentioned above. Hardware from laptops to cell phones to data center will have special instructions or special compute units to specifically handle the linear algebra and other common math operations required by AI — but especially for inference or using the AI to answer our questions. We are already seeing this come to pass. Intel just launched its new AI PC with AI-acceleration built into every Intel® Core™ Ultra processor. This provides enhanced collaboration, productivity, and creativity on your desktop. But this is just the beginning. More AI enhancements will abound as it is infused into all of computing. Big Large Language Models (LLMs) trained on the worlds knowledge make headlines — but efficient inference and use of these models in smaller form factors will rule the day and this will drive AI more and more into the data center with a renewed focus on inference.</p><p><strong>Final prediction</strong>: <strong>This groundhog cannot see its own shadow — AI Spring is around the corner!<br>The fusion of AI and quantum computing will usher in something very close to AGI — aggregated by specialty. </strong>This will change the way we think of compute. The idea of deterministic values from differential equations will yield to a general population that begins to think probabilistically. Computation will become more predictive with probabilistic values for various prescriptive alternative actions being the norm and people thinking about “expected values” in many more aspects of their lives — apps will reflect this change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e6e03169a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loop Replacement Strategies: Applications to Pandas Apply]]></title>
            <link>https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1999cab731a9</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[oneapi]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 21:21:17 GMT</pubDate>
            <atom:updated>2023-12-23T20:54:41.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*kMS9weShGXxldk5NoMWhTg.png" /><figcaption>Image: cartoon of a speeding pandas bear, edited by author</figcaption></figure><p>In a previous article, <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, I address why NumPy constructs, powered by Intel oneAPI, can achieve outsized performance and code readability and code maintainability advantages over a typical “roll your won” Python code segment.</p><p>In this article I want to apply the NumPy select tricks we learned in a previous article to accelerating a Pandas Apply statement hindered by conditional logic.</p><p>I will address the following:</p><ul><li>Apply WHERE or SELECT in NumPy powered by Intel oneAPI to dramatically speed up certain common Pandas bottlenecks</li><li>Achieve good performance using NumPy. Select on a Pandas data frame</li><li>Achieve even better performance by converting the date frame to to NumPy arrays</li></ul><p>It is important to know how to speed up Pandas natively via its dependence on NumPy. <strong>Pandas is powered by oneAPI via NumPy!</strong></p><p>When the opportunity arises it often highly profitable to leverage the NumPy way of solving a Pandas apply() performance issue. Due to the nature of the size of many data frames, it is often better to uncover a way to apply NumPy instead.</p><p>While not yet a part of this course AI Tools from Intel (formerly referred to as the Intel® AI Analytics Toolkit) has a component called Modin* which is a drop in replacement for Pandas and this package can dramatically speed up Pandas operations. Modin can be used for problems larger than can fit in your laptops memory for example and can distribute computations across a cluster of nodes. Our aim is to include Modin as a component of training in the future.</p><p>There are a number of excellent references regarding speeding up NumPy or more specifically Pandas using NumPy and I encourage you to review these resources.</p><h3>reference:</h3><ul><li><a href="https://www.youtube.com/watch?v=nxWginnBklU&amp;t=237s">Nathan Cheever Video: <strong>1000x faster data manipulation: vectorizing with Pandas and NumPy</strong></a>. His Advise is prescient!</li><li><a href="https://www.youtube.com/watch?v=EEUXKG97YRw">Jake VanderPlas Video: <strong>Losing your Loops Fast Numerical Computing with NumPy</strong></a>.</li><li><a href="https://jakevdp.github.io/PythonDataScienceHandbook/">Jake VanderPlas Book: <strong>Python Data Science Handbook</strong></a>.</li><li><a href="https://towardsdatascience.com/understanding-the-need-for-optimization-when-using-pandas-8ce23b83330c">Selvaratnam Lavinan article (towardsdatascience.com ): <strong>Understanding the need for optimization when using Pandas</strong></a></li></ul><p>I will experimenting with a conjured example of a weird conditional logic applied to columns of a Pandas data frame with an expensive log function thrown in for good measure.</p><pre>def my_function(x):<br>    return np.log(1+x)<br><br>def func(a,b,c,d,e):<br>    if e == 10:<br>        return c*d<br>    elif (e &lt; 10) and (e&gt;=7):<br>        return my_function(c+d)<br>    elif e &lt; 7:<br>        return my_function(a+b+100)</pre><p>Now we use our old friend Pandas APply to establish a timing baseline.</p><pre>%%time<br># naive loop method using pandas loc<br>import numpy as np<br><br># each iteration of the loop requires an interpretation of the instructions being used and this decoding takes time<br>    <br>t1 = time.time()<br><br>df[&#39;new&#39;] = df.apply(lambda x: func(x[&#39;a&#39;], x[&#39;b&#39;], x[&#39;c&#39;], x[&#39;d&#39;], x[&#39;e&#39;]), axis=1)<br><br>t2 = time.time()<br>print(&quot;time : {:5.2f}&quot;.format(t2-t1))<br>df.head()<br>baseTime = t2-t1<br>timing[&#39;Pandas Apply&#39;] =  t2 - t1<br>df.head()<br><br>output:<br>time :  8.37<br>CPU times: user 8.36 s, sys: 15.9 ms, total: 8.37 s<br>Wall time: 8.38 s</pre><p>Hmmmm, I thought it would be faster — it vectorizes right?</p><p>Oh — conditional logic can hamper vectorization.</p><p>Can I do something about it?</p><p>Maybe you read one time about a trick called masking. We will do the conditional logic to see an index or mask for our data frame and use different masks for different conditions.</p><pre># masked approach<br>t1 = time.time()<br>df[&#39;new&#39;] = df[&#39;c&#39;]  * df[&#39;d&#39;]  #default case e =10<br>mask = (df[&#39;e&#39;] &lt; 10) &amp; (df[&#39;e&#39;] &gt;= 7)<br>df.loc[mask,&#39;new&#39;] = (df[&#39;c&#39;] + df[&#39;d&#39;]).apply(lambda x : my_function(x))<br>mask = df[&#39;e&#39;] &lt; 7<br>df.loc[mask,&#39;new&#39;] = (df[&#39;a&#39;] + df[&#39;b&#39;]).apply(lambda x : my_function(x + 100))<br>t2 = time.time()<br>print(&quot;time :&quot;, t2-t1)<br>fastest_time = t2-t1<br>Speedup = baseTime / fastest_time<br>print(&quot;Speed up: {:4.0f} X&quot;.format(Speedup))<br>timing[&#39;unrolled with masks on df&#39;] = t2 - t1<br>df.head()<br><br>output:<br>time : 1.6978118419647217<br>Speed up:    5 X</pre><p>WOW! Masking to the rescue!</p><p>Still — I wonder if I could do better?</p><p>I watched a cool video on Youtube by a guy introducing me to the <strong>Numpy “Select” clause</strong>. He had so many great tips — But off the top of my head I can remember the “Select” trick.</p><p>If you want to get serious about speeding up your python check these two references out!</p><p>Seriously — Look up Nathan Cheever talk <a href="https://www.youtube.com/watch?v=nxWginnBklU&amp;t=237s">1000x faster data manipulation: vectorizing with Pandas and Numpy</a>. His Advise is precient!</p><p>While you are at it — Look up Jake VanderPlas talk <a href="https://www.youtube.com/watch?v=EEUXKG97YRw">Losing your Loops Fast Numerical Computing with NumPy</a>. I also recommend that you buy his book <a href="https://jakevdp.github.io/PythonDataScienceHandbook/">Python Data Science Handbook</a>.</p><p>Let’s try <strong>Numpy “Select” clause</strong></p><p>Notice that it cleans the code up alot!</p><ol><li>You create a list of tuple containing your condition.</li><li>You create another list of tuples containg the opration you wish tou apply</li><li>You call np.select(condlist, choicelist, default=0)</li></ol><pre><br># np.select(condlist, choicelist, default=0)<br>t1 = time.time()<br>################### add code here ###########<br>condition = [ (df[&#39;e&#39;] &lt; 10) &amp; (df[&#39;e&#39;] &gt;= 7),<br>              ( df[&#39;e&#39;] &lt; 7)]<br>choice = [ (df[&#39;c&#39;] + df[&#39;d&#39;]).apply(lambda x : my_function(x) ), <br>           (df[&#39;a&#39;] + df[&#39;b&#39;]).apply(lambda x : my_function(x + 100) ) ]<br>default = (df[&#39;c&#39;] * df[&#39;d&#39;])<br>np.select(condition, choice, default = default )<br>#############################################<br>np.select(condition, choice, default = default)<br>t2 = time.time()<br>print(&quot;time :&quot;, t2-t1)<br>timing[&#39;Numpy Select on Pandas df&#39;] = t2 - t1<br>df.head()<br><br>output:<br>time : 1.684462308883667</pre><p>Using NumPy.select with Pandas data frame operations yield a speedup of about 5X!</p><p>Not bad!</p><p>But, but I am using “numpy.select” and applying it to Pandas data frames.</p><p>Could we speed it up more if we drop the Pandas and go completely with NumPy? Maybe try masking, it is usally faster.</p><pre><br># Convert Pandas to numpy entirely<br>t1 = time.time()<br>npArr = df.to_numpy()  # convert to numpy<br>idx = {}  #intialize an indexing dictionary<br>for index, value in enumerate(df.columns):<br>    idx[value] = index<br>df.loc[:,&#39;new&#39;] = npArr[:,idx[&#39;c&#39;]] * npArr[:,idx[&#39;d&#39;]] #default case e =10<br>mask = (npArr[:,idx[&#39;e&#39;]] &lt; 10) &amp; (npArr[:,idx[&#39;e&#39;]] &gt;= 7)<br>df.loc[mask,&#39;new&#39;] =  my_function(npArr[mask,idx[&#39;c&#39;]] + npArr[mask,idx[&#39;d&#39;]])<br>mask = (npArr[:,idx[&#39;e&#39;]] &lt; 7)<br>df.loc[mask,&#39;new&#39;] = my_function(npArr[mask,idx[&#39;a&#39;]] + npArr[mask,idx[&#39;b&#39;]]  + 100)<br>t2 = time.time()<br>print(&quot;time :&quot;, t2-t1)<br>df.head()<br>fastest_time = t2-t1<br>Speedup = baseTime / fastest_time<br>print(&quot;Speed up: {:4.0f} X&quot;.format(Speedup))<br>timing[&#39;unrolled with Masks on dataframe&#39;] = t2 - t1<br>df.head()<br><br>output:<br>time : 0.06982827186584473<br>Speed up:  120 X</pre><p>WOW!! Now we are talking — something over 120X speedup!</p><p>Code looks a little messy though.</p><p>How about if we try the Numpy.Select trick again?</p><pre># np.select(condlist, choicelist, default=0)<br># Convert Pandas to numpy entirely<br>t1 = time.time()<br>npArr = df.to_numpy()  # convert to numpy<br><br>condition = [ (npArr[:,idx[&#39;e&#39;]] &lt; 10) &amp; (npArr[:,idx[&#39;e&#39;]] &gt;= 7),<br>              (npArr[:,idx[&#39;e&#39;]] &lt; 7)]<br><br>choice = [(my_function(npArr[:,idx[&#39;c&#39;]] + npArr[:,idx[&#39;d&#39;]]      )), <br>          (my_function(npArr[:,idx[&#39;a&#39;]] + npArr[:,idx[&#39;b&#39;]] + 100))]<br><br>tmp = np.select(condition, choice, default= (npArr[:,idx[&#39;c&#39;]] * npArr[:,idx[&#39;d&#39;]]) )<br><br>df.loc[:,&#39;new&#39;] = tmp<br>t2 = time.time()<br><br>print(&quot;time :&quot;, t2-t1)<br><br>fastest_time = t2-t1<br>Speedup = baseTime / fastest_time<br>print(&quot;Speed up: {:4.0f} X&quot;.format(Speedup))<br>timing[&#39;Numpy Select Pure&#39;] = t2 - t1<br>df.head()<br><br>output:<br>time : 0.041852712631225586<br>Speed up:  200 X</pre><p>200X speedup! Wow!</p><p>Plot the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*E-I3x5tP15D8Mx6hgQ6Ggg.png" /><figcaption>Chart: Speedups plotted using code referenced below on Xeon system referenced below</figcaption></figure><p>WOW!!! Hundreds time faster than Pandas Apply AND code is cleaner!</p><p>SHIP IT!</p><h3>Play with these concepts on the Intel Developer Cloud:</h3><p>Take the opportunity to play with replacing loop bound aggregations in your own code with NumPy aggregation functions instead.</p><p>For a sandbox to play in — register for a free account on the Intel Developer Cloud (cloud.intel.com), sign in and play by clicking on the icon in the lower left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*i5IIkD9Jj69VGYK-.png" /></figure><p>Image: Screenshot from cloud.intel.com</p><p>Then <strong>Launch JupyterLab </strong>on the shared access node in the icon on the right — see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*LipO1Y3SNyBdPJ4N.png" /></figure><p>Image: Screenshot from cloud.intel.com</p><h3><strong>Code</strong></h3><p>The code for this article and the rest of the series is located on <a href="https://github.com/IntelSoftware/NumPy_Optimizations">github</a>. For this article experiment with the file: 08_05_NumPy_Where_Select.ipynb</p><h3>Related Articles:</h3><h4>Article 1:</h4><p><a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1?source=your_stories_page-------------------------------------">Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library</a>. Explore the reasons why replacing inefficient Python loops with NumPy or PyTorch constructs is a great idea.</p><h4>Article 2:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-e57c8b068260?source=your_stories_page-------------------------------------">Python Loop Replacement: NumPy Optimizations Simple Stuff — ND array creation using NumPy, PyTorch, DPCTL</a>. Explore simple ways of creating , converting and transforming Lists into NumPy NDarrays — a very basic getting started.</p><h4>Article 3:</h4><p><a href="https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248?source=your_stories_page-------------------------------------">Introduction to NumPy* Universal functions (ufuncs). How I learned to stop worrying and let smart developers help me.</a></p><h4>Article 4:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362">Replacing Python loops: Aggregations and Reductions</a>. How to replace slow python loops by strategic function equivalents for aggregating data.</p><h4>Article 5:</h4><p><a href="https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df?source=your_stories_page-------------------------------------">Replacing Python loops: Fancy Slicing and Broadcasting</a>. Here I address fancy slicing and broadcasting to take advantage of key optimizations for loop replacement.</p><h4>Article 6:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355?source=your_stories_page-------------------------------------">Python Loop Replacement: PyTorch &amp; NumPy Optimizations. Not your SQL Select clause — Using Where and Select to vectorize conditional logic.</a></p><h4>Article 7: (current article)</h4><p><a href="https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9?source=your_stories_page-------------------------------------">Loop Replacement Strategies: Applications to Pandas Apply</a>. Examine how to accelerate Pandas Apply statement containing conditional logic.</p><h4>Article 8:</h4><p><a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">NumPy Functions Composed</a>. <a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">Compare Fast Inverse Square Root Method to NumPy ufuncs, Numba JIT, and Cython — Which One Wins?</a></p><h3><strong>Intel Developer Cloud System Configuration as tested:</strong></h3><p>x86_64<br>CPU op-mode(s): 32-bit, 64-bit<br>Address sizes: 52 bits physical, 57 bits virtual<br>Byte Order: Little Endian<br>CPU(s): 224<br>On-line CPU(s) list: 0–223<br>Vendor ID: GenuineIntel<br>Model name: Intel(R) Xeon(R) Platinum 8480+<br>CPU family: 6<br>Model: 143<br>Thread(s) per core: 2<br>Core(s) per socket: 56<br>Socket(s): 2<br>Stepping: 8<br>CPU max MHz: 3800.0000<br>CPU min MHz: 800.0000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1999cab731a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Loop Replacement: PyTorch & NumPy Optimizations]]></title>
            <link>https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e64ed2f355</guid>
            <category><![CDATA[conditional-statements]]></category>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[xeon]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 20:34:08 GMT</pubDate>
            <atom:updated>2023-12-23T20:55:13.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Loop Replacement: Handling Conditional Logic (PyTorch &amp; NumPy)</h3><h3>Not your SQL Select clause — Using Where and Select to vectorize conditional logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*ii8FsFTirgBmKa38TVf9Dg.png" /><figcaption>Image: Powerpoint* by author</figcaption></figure><p>In a previous article, <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, I address why NumPy constructs, powered by Intel oneAPI, can achieve outsized performance and code readability and code maintainability advantages over a typical “roll your won” Python code segment.</p><p>In this article I want to demonstrate how you can vectorize a loop even though it contains tricky conditional logic.</p><p>Summarized: Here are the steps you shoudl take.</p><ol><li>Find Large loop iteration loop</li></ol><p>2. If it contains conditional logic, consider pytorch.where, np.where or np.select</p><p>3. else try to find a NumPy or PyTorch replacement using UFuncs, aggregations, etc</p><h3>Numpy.where &amp; PyTorch.where</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*lNXzLdcM0Q5XGF9BcSLerw.png" /><figcaption>Image: Where statement is for more simple logic conditions — Powerpoint by author</figcaption></figure><p>One thing that could prevent us from effectively getting vector performance when converting a loop to a vector approach is when the original loop has if then else statements in it — called conditional logic</p><p>The Numpy &amp; PyTorch Where allows us to tackle conditional loops in a fast vectorized way</p><p>Apply conditional logic to an array to create a new column orupdate contents of an existing column</p><p><strong>Syntax:</strong></p><ul><li>numpy.where(condition, [x, y, ]/)</li><li>Return elements chosen from x or y depending on condition.</li></ul><p>To understand what NumPy where does, look at the simple example below See a simple example below to add 50 to all elements currently greater than 5</p><pre>a = np.arange(10)<br>np.where(a &gt; 5, a + 50, a )<br># if a &gt; 5 then return a + 50<br># else return a<br><br>output:<br>array([ 0,  1,  2,  3,  4,  5, 56, 57, 58, 59])</pre><p>This could come n handy for many AI applications, but let’s choose labeling data</p><p>There may be better wyas to binarize data but here is a simple example of converting conrinuous data into categorical values</p><p>arr = <strong>np.array([11, 1.2, 12, 13, 14, 7.3, 5.4, 12.5])</strong></p><p>Let’s say all values 10 and above represent a medical parameter threshold that indicates further testing, while values below 10 indicate normal range</p><p>We might like to print the values as words such as <strong>[‘More Testing’, ‘Normal’, ‘More Testing’, ‘More Testing’, …]</strong></p><pre>arr = np.array([11, 1.2, 12, 13, 14, 7.3, 5.4, 12.5])<br>np.where(arr &lt; 10, &#39;Normal&#39;, &#39;More Testing&#39;)<br><br>output:<br>array([&#39;More Testing&#39;, &#39;Normal&#39;, &#39;More Testing&#39;, &#39;More Testing&#39;,<br>       &#39;More Testing&#39;, &#39;Normal&#39;, &#39;Normal&#39;, &#39;More Testing&#39;], dtype=&#39;&lt;U12&#39;)</pre><p>Or we could binarize data for use in a classifier:</p><pre><br># Simple Numpy Binarizer Discretizer<br># convert continous data to discrete integer bins<br>arr = np.array([11, 1.2, 12, 13, 14, 7.3, 5.4, 12.5])<br>print(np.where(arr &lt; 6, 0, np.where(arr &lt; 12, 1, 2)))<br><br>output:<br>[1 0 2 2 2 1 0 2]</pre><p>NumPy where can be used to create index masks so that you can select or update masked items from an array.</p><p>In this example, I want to find all(rows, cols) of (all **multiples of **12 or all multiples of 9) in a 10x10 multiplication table and make all other values 0. Preserve the first row and first column as readable indexes for the table as follows:</p><pre>## one solution - preserves the indexing edges for easy checking<br>res = 0<br>re((MultiplicationTable%12 == 0) | (MultiplicationTable%9 == 0), MultiplicationTable, 0)<br>res[0,:] = MultiplicationTable[0,:]<br>res[:,0] = MultiplicationTable[:,0]<br>res<br><br>output:<br>array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],<br>       [ 2,  0,  0,  0,  0, 12,  0,  0, 18,  0],<br>       [ 3,  0,  9, 12,  0, 18,  0, 24, 27,  0],<br>       [ 4,  0, 12,  0,  0, 24,  0,  0, 36,  0],<br>       [ 5,  0,  0,  0,  0,  0,  0,  0, 45,  0],<br>       [ 6, 12, 18, 24,  0, 36,  0, 48, 54, 60],<br>       [ 7,  0,  0,  0,  0,  0,  0,  0, 63,  0],<br>       [ 8,  0, 24,  0,  0, 48,  0,  0, 72,  0],<br>       [ 9, 18, 27, 36, 45, 54, 63, 72, 81, 90],<br>       [10,  0,  0,  0,  0, 60,  0,  0, 90,  0]])</pre><h3>Numpy Where applied to California Housing data</h3><p>In AI context, this could be applying categorical classifier to otherwise continuous values. For example, California housing dataset the target price variable is continuous. in the following fictitious scenario, A new stimulus package is considered whereby new house buyers will be given a coupon worth 50,000 off toward purchase of houses in California whose price (prior to coupon) is between 250,0000 and 350,000. Other prices will be unaffected. Generate array with the adjusted targets</p><p>Lets compare the naive Python loop versus the NumPy Where clause — examine for readability, maintainability, speed, etc</p><pre># Ficticious scenario:<br>from sklearn.datasets import fetch_california_housing<br><br>california_housing = fetch_california_housing(as_frame=True)<br>X = california_housing.data.to_numpy()<br>buyerPriceRangeLo = 250_000/100_000<br>buyerPriceRangeHi= 350_000/100_000<br>T = california_housing.target.to_numpy() <br>t1 = time.time()<br>timing = {}<br>New = np.empty_like(T)<br>for i in range(len(T)):<br>    if ( (T[i] &lt; buyerPriceRangeHi) &amp; (T[i] &gt;= buyerPriceRangeLo) ):<br>        New[i] = T[i] - 50_000/100_000<br>    else:<br>        New[i] = T[i]<br>t2 = time.time()<br>plt.title( &quot;California Housing Dataset - conditional Logic Applied&quot;)<br>plt.scatter(T, New, color = &#39;b&#39;)<br>plt.grid()<br>print(&quot;time elapsed: &quot;, t2-t1)<br>timing[&#39;Loop&#39;] = t2-t1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*C76GctJxVqlwmQPe7M3oYA.png" /><figcaption>Chart 1: Naive loop implementation of house price coupon</figcaption></figure><p>Next, examine the NumPy Where approach:</p><pre>t1 = time.time()<br>#############################################################################<br>### Exercise: Addone moddify code below to compute same results as above loop<br>New = np.where((T &lt; buyerPriceRangeHi) &amp; (T &gt;= buyerPriceRangeLo), T - 50_000/100_000, T )<br>##############################################################################<br>t2 = time.time()<br><br>plt.scatter(T, New, color = &#39;r&#39;)<br>plt.grid()<br>print(&quot;time elapsed: &quot;, t2-t1)<br>timing[&#39;np.where&#39;] = t2-t1<br>print(&quot;Speedup: {:4.1f}X&quot;.format( timing[&#39;Loop&#39;]/timing[&#39;np.where&#39;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*SJ8g1T6KbW39UbIHgkuU4w.png" /><figcaption>Chart 1: NumPy Where implementation of house price coupon</figcaption></figure><h4>Code more readable, more maintainable, faster 13X</h4><p>As you can see, we generated the same data with NumPy where as we did with the original loop but we did so <strong>13X </strong>faster (the speedup amount may vary a bit).</p><h3>NumPy Select statement:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*KsvIq-rjICphu-woVwAsag.png" /><figcaption>Image: Select statement is for more simple logic conditions — Powerpoint by author</figcaption></figure><p>The select statement is available in NumPy , but not yet in PyTorch, although I will provide a code snippet which can emulate the select clause using PyTorch. The select statement handle much more complex logic conditions as compared to the where statement.</p><p>Apply conditional logic to an array to create a new column orupdate contents of an existing column. This method handles more complex conditional sceanrios than numpy where.</p><p><strong>Syntax:</strong></p><ul><li>[numpy.select(condlist, choicelist, default=0)[source]</li><li>Return an array drawn from elements in choicelist, depending on conditions.</li></ul><p>function return an array drawn from elements in choicelist, depending on conditions.</p><p>This is very useful function for handing conditionals that otherwise slow down and map or apply, or else add complexity in reading the code</p><p>First we will create some new data</p><pre>import numpy as np<br>import time<br><br>BIG = 10_000_000<br><br>np.random.seed(2022)<br>A = np.random.randint(0, 11, size=(BIG, 6)</pre><p>Now I will apply some crazy logic to updating various columns of the array</p><pre>timing = {}<br>t1 = time.time()<br>for i in range(BIG):<br>    if A[i,4] == 10:<br>        A[i,5] =  A[i,2] * A[i,3]<br>    elif (A[i,4] &lt; 10) and (A[i,4] &gt;=5):<br>        A[i,5] =   A[i,2] + A[i,3]<br>    elif A[i,4] &lt; 5:<br>        A[i,5] =   A[i,0] + A[i,1]<br>t2 = time.time()<br>baseTime = t2- t1<br>print(A[:5,:])<br>print(&quot;time: &quot;, baseTime)<br>timing[&#39;Naive Loop&#39;] = t2 - t1<br><br>output:<br>[[ 0  1  1  0  7  1]<br> [ 2  8  0  5  9  5]<br> [ 3  8  0  3  6  3]<br> [ 0 10 10  1  2 10]<br> [ 5  7  5  1  7  6]]<br>time:  5.937685012817383</pre><h4>Try Vectorizing with masks</h4><p>Just remove the references to i and remove the loop, create mask for each condition</p><pre># Try Vectorizing simply<br>t1 = time.time()<br>mask1 = A[:,4] == 10<br>A[mask1,5] =  A[mask1,2] * A[mask1,3]<br>mask2 = ((A[:,4].any() &lt; 10) and (A[:,4].any() &gt;=5))<br>A[mask2,5] =   A[mask2,2] + A[mask2,3]<br>mask3 = A[:,4].any() &lt; 5<br>A[mask3,5] =   A[mask3,0] + A[mask3,1]<br>t2 = time.time()<br>print(A[:5,:])<br>print(&quot;time :&quot;, t2-t1)<br><br>fastest_time = t2-t1<br>Speedup = baseTime / fastest_time<br>print(&quot;Speed up: {:4.0f} X&quot;.format(Speedup))<br>timing[&#39;Vector Masks&#39;] = t2 - t1<br><br>output:<br>[[ 0  1  1  0  7  1]<br> [ 2  8  0  5  9  5]<br> [ 3  8  0  3  6  3]<br> [ 0 10 10  1  2 10]<br> [ 5  7  5  1  7  6]]<br>time : 0.23482632637023926<br>Speed up:   25 X</pre><h4>Next, try NumPy.select — Much cleaner logic</h4><p>Put condition inside a list of tuples, put execution choice inside a list of tuples, and choose a default action</p><pre>condition = [ (A[:,4]  &lt; 10) &amp; (A[:,4] &gt;= 5),<br>              ( A[:,4] &lt; 5)]<br>choice = [ (A[:,2] + A[:,3]), <br>           (A[:,0] + A[:,1] ) ]<br>default = [(A[:,2] * A[:,3])]<br>A[:,5] = np.select(condition, choice, default= default )<br><br>output:<br>[[ 0  1  1  0  7  1]<br> [ 2  8  0  5  9  5]<br> [ 3  8  0  3  6  3]<br> [ 0 10 10  1  2 10]<br> [ 5  7  5  1  7  6]]<br>time : 0.4723508358001709<br>Speed up:   13 X</pre><pre>plt.figure(figsize=(10,6))<br>plt.title(&quot;Time taken to process {:,} records in seconds&quot;.format(BIG),fontsize=12)<br>plt.ylabel(&quot;Time in seconds&quot;,fontsize=12)<br>plt.xlabel(&quot;Various types of operations&quot;,fontsize=14)<br>plt.grid(True)<br>plt.xticks(rotation=-60)<br>plt.bar(x = list(timing.keys()), height= list(timing.values()), align=&#39;center&#39;,tick_label=list(timing.keys()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Kb1M5NzwOhu4AL5ukR-6Eg.png" /><figcaption>Plot: generated by author on Xeon system specified and code provided 08_05_NumPy_Where_Select.ipynb</figcaption></figure><p>Note: 13X speedup over Naive Python loop when using this NumPy.select in this simple example.</p><p>Next article — I will use the NumPy select to drastically speedup a Pandas Apply statement that is plagued with lots of conditional logic.</p><h3><strong>Play with these concepts on the Intel Developer Cloud:</strong></h3><p>Take the opportunity to play with replacing loop bound aggregations in your own code with NumPy aggregation functions instead.</p><p>For a sandbox to play in — register for a free account on the Intel Developer Cloud (cloud.intel.com), sign in and play by clicking on the icon in the lower left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*oj2t0MyT_wQUAqo5.png" /><figcaption>Image: Screenshot from cloud.intel.com</figcaption></figure><p>Then <strong>Launch JupyterLab </strong>on the shared access node in the icon on the right — see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*gEJhbFdm6vJks6zL.png" /><figcaption>Image: Screenshot from cloud.intel.com</figcaption></figure><h3><strong>Code</strong></h3><p>The code for this article and the rest of the series is located on <a href="https://github.com/IntelSoftware/NumPy_Optimizations">github</a>. For this article experiment with the file: 08_05_NumPy_Where_Select.ipynb</p><h3>Related Articles:</h3><h4>Article 1:</h4><p><a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1?source=your_stories_page-------------------------------------">Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library</a>. Explore the reasons why replacing inefficient Python loops with NumPy or PyTorch constructs is a great idea.</p><h4>Article 2:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-e57c8b068260?source=your_stories_page-------------------------------------">Python Loop Replacement: NumPy Optimizations Simple Stuff — ND array creation using NumPy, PyTorch, DPCTL</a>. Explore simple ways of creating , converting and transforming Lists into NumPy NDarrays — a very basic getting started.</p><h4>Article 3:</h4><p><a href="https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248?source=your_stories_page-------------------------------------">Introduction to NumPy* Universal functions (ufuncs). How I learned to stop worrying and let smart developers help me.</a></p><h4>Article 4:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362">Replacing Python loops: Aggregations and Reductions</a>. How to replace slow python loops by strategic function equivalents for aggregating data.</p><h4>Article 5:</h4><p><a href="https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df?source=your_stories_page-------------------------------------">Replacing Python loops: Fancy Slicing and Broadcasting</a>. Here I address fancy slicing and broadcasting to take advantage of key optimizations for loop replacement.</p><h4>Article 6: (current article)</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355?source=your_stories_page-------------------------------------">Python Loop Replacement: PyTorch &amp; NumPy Optimizations. Not your SQL Select clause — Using Where and Select to vectorize conditional logic.</a></p><h4>Article 7:</h4><p><a href="https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9?source=your_stories_page-------------------------------------">Loop Replacement Strategies: Applications to Pandas Apply</a>. Examine how to accelerate Pandas Apply statement containing conditional logic.</p><h4>Article 8:</h4><p><a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">NumPy Functions Composed</a>. <a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">Compare Fast Inverse Square Root Method to NumPy ufuncs, Numba JIT, and Cython — Which One Wins?</a></p><h3><strong>Intel Developer Cloud System Configuration as tested:</strong></h3><p>x86_64<br>CPU op-mode(s): 32-bit, 64-bit<br>Address sizes: 52 bits physical, 57 bits virtual<br>Byte Order: Little Endian<br>CPU(s): 224<br>On-line CPU(s) list: 0–223<br>Vendor ID: GenuineIntel<br>Model name: Intel(R) Xeon(R) Platinum 8480+<br>CPU family: 6<br>Model: 143<br>Thread(s) per core: 2<br>Core(s) per socket: 56<br>Socket(s): 2<br>Stepping: 8<br>CPU max MHz: 3800.0000<br>CPU min MHz: 800.0000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e64ed2f355" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing Python loops: Fancy Slicing and Broadcasting]]></title>
            <link>https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1edf554528df</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[broadcasting]]></category>
            <category><![CDATA[slicing]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 19:35:26 GMT</pubDate>
            <atom:updated>2023-12-23T20:55:55.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsQeT3dQR727jeRRpOuigw.png" /><figcaption>Image: “cartoon of a pie sliced into square pieces” +“cartoon of a pie sliced into pieces”, photoshop composite by the author</figcaption></figure><p>In a previous article, <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, I address why NumPy constructs, powered by Intel oneAPI, can achieve outsized performance and code readability and code maintainability advantages over a typical “roll your won” Python code segment.</p><p>In this article I want to address fancy slicing and broadcasting!</p><p><strong>Slicing — aka fancy slicing:</strong></p><p>Slicing in python, is a means to target a specified subrange of an array or a subrange of a string. It is specified by using “:” in the square bracket index range.</p><pre>a[start:stop]  # items start through stop-1<br>a[start:]      # items start through the rest of the array<br>a[:stop]       # items from the beginning through stop-1<br>a[:]           # a copy of the whole array</pre><p>It should be used rather than a loop to target or select a subrange for various operations. The slicing constructs are wired to handle cache optimization and SIMD vectorization in NumPy and PyTorch.</p><p>For machine learning , one place it is commonly used is for doing the necessary offsets for handling time series data.</p><p>sub-setting a smaller range of data when conducting a live demo and you don’t want to train on an entire dataset to show an audience.</p><p>I’ll consider a stock price prediction example for use with slicing.</p><p>It is common in time series data to predict a value x time units in the future. This is done by taking a label and shifting the indexes so that the future label aligns with features from the past.</p><p>Copying the data as a loop, becomes very inefficient, and for large arrays it is very time consuming.</p><p>Here a snippet of stock like data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*NLnsvXFTDTXpuMRSXwy9Mg.png" /><figcaption>Table 1: stock like time series data</figcaption></figure><p>The goal is to train a model to predict a stock price at time T+3 from all observation up to time T (so we want to predict three days into the future).</p><p>Table 2 shows how this offset label in time compares to the original times series data. Here we observation from up to Dec 20 to predict the price 133.7 that was later observed on Dec 23. We hope to build a predictor that predict out 3 days in advance. We would like to ultimately predict the prices for Dec 29, 30, 31 for which which we have data — before we commit our model into deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*2FBfFWJEj48FTcVgN0qwCQ.png" /><figcaption>Table2: Show alignment of X features to the predited future values under ‘Predict This’</figcaption></figure><p>A simple minded python loop centric way of creating this label column for y, is as follows:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>df = pd.read_csv(&#39;Assets/StockTimeSeries.csv&#39;)<br>X = df[&#39;Stock&#39;].to_numpy()<br>Toffset = 3<br>y = np.zeros([len(X)])<br>for i in range(len(X) - Toffset ):<br>    y[i] = X[i+Toffset]<br># predict for y the last three empty slots (NAN)<br>X,y<br><br>output:<br>(array([145.9933047, 142.333029 , 125.6291325, 133.715583 , 130.6002384,<br>        133.9623597, 139.7279166, 137.5097947, 135.1774904, 125.9596717,<br>        135.2106359, 142.6324476]),<br> array([133.715583 , 130.6002384, 133.9623597, 139.7279166, 137.5097947,<br>        135.1774904, 125.9596717, 135.2106359, 142.6324476,   0.       ,<br>          0.       ,   0.       ]))</pre><p>Next we refactor the above code to use slicing</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>df = pd.read_csv(&#39;Assets/StockTimeSeries.csv&#39;)<br>X = df[&#39;Stock&#39;].to_numpy()<br># Slicing for time series labels<br>y = X[3:] # train on X except last two, labels are shifting 3 days into the future<br># predict for y the last three empty slots (NAN)<br>X,y<br><br>(array([145.9933047, 142.333029 , 125.6291325, 133.715583 , 130.6002384,<br>        133.9623597, 139.7279166, 137.5097947, 135.1774904, 125.9596717,<br>        135.2106359, 142.6324476]),<br> array([133.715583 , 130.6002384, 133.9623597, 139.7279166, 137.5097947,<br>        135.1774904, 125.9596717, 135.2106359, 142.6324476]))</pre><p>To test the potential speedups using slicing, lets look at a different example, here a naive Python loop:</p><pre># try naive loop<br>num = 100_000_001<br>a = np.linspace(0, num - 1, num=num)<br>b = np.ndarray(num-1)<br><br>timing = {}<br><br>t1=time.time()<br><br>for i in range(len(a)-1):<br>    b[i] = a[i+1]<br><br>t2=time.time()<br>print(&quot;shift b w loop {} secs&quot;.format(t2-t1))<br>timing[&#39;loop&#39;] = (t2-t1)<br>b[:2], b[-2:]<br><br>output:<br>shift b w loop 12.460822582244873 secs<br>(array([1., 2.]), array([9.9999999e+07, 1.0000000e+08]))</pre><p>Next, we will try to speed this up using a list comprehension:</p><pre># try list comprehension <br>t1=time.time()<br><br>b = [a[i+1] for i in range(len(a)-1)] # shift b by 1<br><br>t2=time.time()<br>print(&quot;shift b {} secs&quot;.format(t2-t1))<br>timing[&#39;list comprehension&#39;] = (t2-t1)<br>b[:2], b[-2:]<br><br>output:<br>shift b 8.01001787185669 secs<br>([1.0, 2.0], [99999999.0, 100000000.0])</pre><p>Next, I will try using a couple of nested NumPy UFuncs (roll and delete):</p><pre># try ufunc np.roll<br>t1=time.time()<br><br>b = np.delete( np.roll(a,-1) , -1)  # numpy roll and delete last value<br><br>t2=time.time()<br>print(&quot;shift b {} secs&quot;.format(t2-t1))<br>timing[&#39;RollDelete&#39;] = (t2-t1)<br>b[:2], b[-2:]</pre><p>Now try slicing — fancy slicing!</p><pre># try fancy slicing<br>t1=time.time()<br>####### Insert corrected code below<br><br>b = a[1:]<br><br>##################################<br><br>t2=time.time()<br>print(&quot;shift b {} secs&quot;.format(t2-t1))<br>timing[&#39;slicing&#39;] = (t2-t1)<br>b[:2], b[-2:]<br>output:<br>shift b 3.24249267578125e-05 secs<br>(array([1., 2.]), array([9.9999999e+07, 1.0000000e+08]))</pre><p>Plot the results</p><pre>plt.figure(figsize=(10,6))<br>plt.title(&quot;Time taken to process {:,} records in seconds&quot;.format(num),fontsize=12)<br>plt.ylabel(&quot;Time in seconds&quot;,fontsize=12)<br>plt.yscale(&#39;log&#39;)<br>plt.xlabel(&quot;Various types of operations&quot;,fontsize=14)<br>plt.grid(True)<br>plt.xticks(rotation=-60)<br>plt.bar(x = list(timing.keys()), height= list(timing.values()), align=&#39;center&#39;,tick_label=list(timing.keys()))<br>print(&#39;Acceleration : {:4.0g} X&#39;.format(timing[&#39;loop&#39;]/(timing[&#39;slicing&#39;])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*TNnpzw5C1ixkGVFJXRpynQ.png" /><figcaption>Graph 1: Speedup of slicing in this time series example: over 1x10⁵ X speedup!</figcaption></figure><p><strong>Broadcasting:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*HaanGj4EnwB6CBpx232wpw.png" /><figcaption>Image: broadcasting: generated in Powerpoint* by author</figcaption></figure><p>According to <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html">Broadcasting</a> SciPy.org, <br>“The term <strong>broadcasting</strong> describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.”</p><p>In a <strong>Linear Algebra class</strong> there is no such notion at broadcasting</p><p>In Linear Algebra:</p><ul><li>Two matrices can be added or subtracted ONLY if their dimensions are exactly the same (lets say (both MxN)</li><li>Two matrices can be multiplied ONLY if their inner dimensions are the same A(5,2) x B (2,7) = (5,7)</li></ul><p>In NumPy and PyTorch, <strong>broadcasting</strong> is a way to speed up computation by essentially making the dimensions the correct size by copying data from the smaller dimension until the resulting array is suitable for Linear Algebra addition or multiplication.</p><p>The one exception: Outer product is the same in linear Algebra and NumPy, at least in the case of (Nx1) x (1xN) = (NxN)</p><h3>Broadcasting rules and conditions:</h3><p>For a set of arrays can be considered ‘broadcastable’, if this set of conditions that are met.</p><ol><li>The shape of the arrays are the same or the ending dimensions for both arrays match</li><li>If an array has a different number of dimension to the another array, then the array with the lesser dimension is extended by 1 until the number of dimension of both arrays are equal</li><li>If two arrays are to be broadcastable, then the array with dimension size of 1 is to behave in a manner that enables the array with lesser dimension to be expanded by duplication to the length of the second array. (eg. a (3,1) is promoted to (3,3) by copying to fill dimension</li></ol><p>For better intuition about broadcasting — watch this excellent presentation by: <a href="https://www.youtube.com/watch?v=EEUXKG97YRw">Jake Vanderplas <strong>Losing your Loops Fast Numerical Computing with NumPy</strong></a>.</p><h3>Example of normalizing California housing dataset</h3><p>This example combines NumPy <strong>Aggregations</strong> with <strong>Broadcasting</strong></p><p>But the <strong>Numpy vectorized</strong> code is <strong>MUCH more readable</strong> and easier to debug and explain</p><p>Here’s how the broadcasting works here for the Standardization method:</p><ul><li>X is two dimensional array</li><li>X.mean(axis = 0) is a vector (1,3)</li><li>X.std(axis = 0) is a vector (1,3)</li><li>both small vectors (1,3) are broadcast up to the dimension of X (3,3)</li><li>in Linear algebra class you have to add/subtract arrays of same dimensions A is two dimensional array</li></ul><p>Note: the scikit-learn standardize is about 2x faster that these methods. Always look to use optimized libraries such as these in deference to your own loops but ALSO in deference to your own NumPy rolled one liners — but let performance and readability be your guide here.</p><pre>from sklearn.datasets import fetch_california_housing<br><br>california_housing = fetch_california_housing(as_frame=True)<br>X = california_housing.data.to_numpy()<br><br>def standardizeLoop(X): # about 15 lines of code, more to go wrong<br>    C = X.shape[-1]<br>    L = len(X)<br>    tmp = np.zeros(X.shape)<br><br>    for col in range(C):<br>        mean = 0<br>        total = 0<br>        for row in range(len(X)):<br>            total += X[row, col]<br>        mean = total/L<br>        diff2 = 0<br>        for row in range(L):<br>            d = X[row,col] - mean<br>            diff2 += d*d<br>            tmp[row, col] = X[row, col] - mean<br>        for row in range(L):<br>            tmp[row, col] = tmp[row, col]/np.sqrt(diff2/(L))<br>    return tmp<br><br>def standardize(A): # one line of code<br>#     A is two dimensional array<br>#     A.mean(axis = 0) is a vector (1,3)<br>#     A.std(axis = 0) is a vector (1,3)<br>#     both scalars are broadcast up to the dimension of A (3,3)<br>#     in Linear algebra Class you have to add/subtract arrays of same dimensions<br>    #return (A - A.mean(axis=0))/A.std(axis=0)<br>    return (A - np.mean(A, axis=0))/np.std(A, axis=0)<br><br>print(&quot;standardize Loop&quot;)<br>print(standardizeLoop(X))<br><br>print(&quot;standardize NumPy&quot;)<br>print(standardize(X))<br></pre><pre>timing = {}<br>t1 = time.time()<br>standardizeLoop(X)<br>timing[&#39;loop&#39;] = time.time() -t1<br><br>t1 = time.time()<br>standardize(X)<br>timing[&#39;numpy&#39;] = time.time() -t1<br>print(timing)<br>print(f&quot;Acceleration {timing[&#39;loop&#39;]/timing[&#39;numpy&#39;]:4.1f} X&quot;)<br><br>output:<br>{&#39;loop&#39;: 0.1822032928466797, &#39;numpy&#39;: 0.0007750988006591797}<br>Acceleration 235.1 X</pre><p>In the above code, the broadcasting occurs in ths line:</p><pre>return (A - np.mean(A, axis=0))/np.std(A, axis=0)</pre><p>A is an array of shape (10000,), while np.mean(A, axis=0) is a scalar with dimension ().</p><p>We are combining shapes of (10000,) and () which requires that the scalar be stretched to match the dimensions of (1000,) in order to perform the operation.</p><p>By using broadcasting, we speed up our code over naive loop method by over 200X on this particular Xeon node.</p><p><strong>Play with these concepts on the Intel Developer Cloud:</strong></p><p>Take the opportunity to play with replacing loop bound aggregations in your own code with NumPy aggregation functions instead.</p><p>For a sandbox to play in — register for a free account on the Intel Developer Cloud (cloud.intel.com), sign in and play by clicking on the icon in the lower left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*Ym8k-M1DSZhbvXfY.png" /></figure><p>Then <strong>Launch JupyterLab </strong>on the shared access node in the icon on the right — see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*LK81BphUJDxOuQGR.png" /></figure><h3><strong>Code</strong></h3><p>The code for this article and the rest of the series is located on <a href="https://github.com/IntelSoftware/NumPy_Optimizations">github</a>. For this article experiment with the file: 08_04_NumPy_Broadcasting.ipynb</p><h3>Related Articles:</h3><h4>Article 1:</h4><p><a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library</a>. Explore the reasons why replacing inefficient Python loops with NumPy or PyTorch constructs is a great idea.</p><h4>Article 2:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-e57c8b068260">Python Loop Replacement: NumPy Optimizations Simple Stuff — ND array creation using NumPy, PyTorch, DPCTL</a>. Explore simple ways of creating , converting and transforming Lists into NumPy NDarrays — a very basic getting started.</p><h4>Article 3:</h4><p><a href="https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248">Introduction to NumPy* Universal functions (ufuncs). How I learned to stop worrying and let smart developers help me.</a></p><h4>Article 4:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362">Replacing Python loops: Aggregations and Reductions</a>. How to replace slow python loops by strategic function equivalents for aggregating data.</p><h4>Article 5: (current article)</h4><p><a href="https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df">Replacing Python loops: Fancy Slicing and Broadcasting</a>. Here I address fancy slicing and broadcasting to take advantage of key optimizations for loop replacement.</p><h4>Article 6:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355">Python Loop Replacement: PyTorch &amp; NumPy Optimizations. Not your SQL Select clause — Using Where and Select to vectorize conditional logic.</a></p><h4>Article 7:</h4><p><a href="https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9">Loop Replacement Strategies: Applications to Pandas Apply</a>. Examine how to accelerate Pandas Apply statement containing conditional logic.</p><h4>Article 8:</h4><p><a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884">NumPy Functions Composed</a>. <a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884">Compare Fast Inverse Square Root Method to NumPy ufuncs, Numba JIT, and Cython — Which One Wins?</a></p><h3><strong>Intel Developer Cloud System Configuration as tested:</strong></h3><p>x86_64<br>CPU op-mode(s): 32-bit, 64-bit<br>Address sizes: 52 bits physical, 57 bits virtual<br>Byte Order: Little Endian<br>CPU(s): 224<br>On-line CPU(s) list: 0–223<br>Vendor ID: GenuineIntel<br>Model name: Intel(R) Xeon(R) Platinum 8480+<br>CPU family: 6<br>Model: 143<br>Thread(s) per core: 2<br>Core(s) per socket: 56<br>Socket(s): 2<br>Stepping: 8<br>CPU max MHz: 3800.0000<br>CPU min MHz: 800.0000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1edf554528df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Loop Replacement: NumPy Optimizations]]></title>
            <link>https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bead33261362</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[reduction]]></category>
            <category><![CDATA[intel-oneapi]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 19:26:27 GMT</pubDate>
            <atom:updated>2023-12-23T20:56:47.477Z</atom:updated>
            <content:encoded><![CDATA[<h3>Replacing Python loops: Aggregations and Reductions</h3><h4>How to replace slow python loops by strategic function equivalents for aggregating data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wo9wORRXr7VdBsdDEuqgrw.png" /><figcaption>Image by Dall-E: cartoon boiling flacks connected to glassware “coiled condenser” doing distillation</figcaption></figure><p>In a previous article, <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, I address why NumPy constructs, powered by Intel oneAPI, can achieve outsized performance and code readability and code maintainability advantages over a typical “roll your won” Python code segment.</p><p>In this article I want to address common concepts for aggregating or reducing data dimensions using functions similar to sums and means and other aggregation functions implemented as Universal Functions in NumPy.</p><p><strong>Aggregations/ Reductions:</strong></p><p>Aggregations or reductions are means of compressing or shrinking the dimensionality of data into a summarized state using mathematical functions.</p><p>Some examples would be computing a sum, an average, the median, the standard deviation, or the mode of a column or row of data, as seen in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cBVmHh7lmOk-izGLlu-V-g.png" /><figcaption>Table 1: Examples of cpmmon aggregations</figcaption></figure><p>But there are more ways than these to aggregate data that are used commonly in data science and statistics.</p><p>Other common aggregations are min, max, argmin, argmax.</p><p>It is worthwhile exploring the wide set of methods provided by NumPy ufuncs which contain many of the aggregations.</p><p>Below is a table of aggregations commonly used in machine learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*l-2yQWEWRjyLx1xwK3uR7A.png" /><figcaption>Table 2: UFuncs commonly used in machine learning.</figcaption></figure><p><strong>Benefits of replacing “roll your own” Python loops with NumPy Aggregations:</strong></p><p>As I explained in <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, NumPy, powered by Intel oneAPI, can achieve higher levels of readability, maintainability, future proofing your code for new hardware and software library optimizations, and <strong>performance </strong>than a straight forward “roll your own” loop.</p><p>I’ll provide an example below of my “roll your own” Python code for computing the mean and standard deviation, since this si done frequently in machine learning, and compare the readbility and performance of my code versus a straightforward use of NumPy to acheive the same computation.</p><pre>rng = np.random.default_rng(2021)<br># random.default_range is the recommended method for generated random&#39;s<br># see blog &quot;Stop using numpy.random.seed()&quot; for reasoning<br># https://towardsdatascience.com/stop-using-numpy-random-seed-581a9972805f<br><br>a = rng.random((10_000_000,))<br>t1 = time.time()<br>timing = {} # collect timing information<br>S = 0<br>for i in range (len(a)): # compute the sum<br>    S += a[i]<br>mean = S/len(a) # compute the mean<br>std = 0<br>for i in range (len(a)):  # compute the sum of the differences from the mean<br>    d = a[i] - mean<br>    std += d*d<br>std = np.sqrt(std/len(a)) #compute the standard deviation<br>timing[&#39;loop&#39;] = time.time() - t1<br>print(&quot;mean&quot;, mean)<br>print(&quot;std&quot;, std)<br><br>print(timing)</pre><p>Compare the code above to the much more readable and maintainable code below:</p><pre>t1 = time.time()<br>print(a.mean())<br>print(a.std())<br><br>timing[&#39;numpy&#39;] = time.time() - t1<br>print(timing)<br>print(f&quot;Acceleration {timing[&#39;loop&#39;]/timing[&#39;numpy&#39;]:4.1f} X&quot;)<br></pre><p>As you can see, the NumPy code is much more readable ( 3lines of code versus 16 lines), more maintainable, and it is faster too. The timing comparison is as follows ‘naive loop’: 2.8 seconds, NumPy mean/std: .04 seconds. This is a speedup over the naive code by a factor of over 60X, see my article, <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a>, for the underlying reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*JhlztUDCiYdySW6kbE4cfw.png" /><figcaption>Chart 1: speedup of NumPy mean/std code over my naive Python implementation</figcaption></figure><h4>Flexibility of NumPy Aggregations</h4><p>Another aspect of many NumPy aggregations/ reductions is the ability to specify an axis over which to apply the reducing function. As an example, consider the numPy sum() function. Without an axis specifier it adds ALL the values in an N dimensions array to arrive at a scalr value. But, if you specify and axis, in the example below I specify axis=0, it returns a row vector that sums each column of the matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*fw6MGV5g24p_8cLJhuo_FQ.png" /><figcaption>Example 1: Summing on axis = 0</figcaption></figure><p>Alternatively, if I specify axis=1, I get a column vector whose entries are the sums of each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*tOxDk4R2Ikzg91rcJ3rrMQ.png" /><figcaption>Example 2: Summing on axis = 1</figcaption></figure><p>Flexibility is provided by specifying parameters for each aggregation function to accommodate variations in how the aggregation should be done as we see in the sum example above.</p><p>Take the opportunity to play with replacing loop bound aggregations in your own code with NumPy aggregation functions instead.</p><p>For a sandbox to play in — register for a free account on the Intel Developer Cloud (cloud.intel.com), sign in and play by clicking on the icon in the lower left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*DNd9NbNRM6qsu_QmLGQVCQ.png" /></figure><p>Then <strong>Launch JpyterLab </strong>on the shared access node in the icon on the right — see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUdB-i1aW8esWqYaXIzMzA.png" /></figure><h3><strong>Code</strong></h3><p>The code for this article and the rest of the series is located on <a href="https://github.com/IntelSoftware/NumPy_Optimizations">github</a>. For this article experiment with the file: <a href="https://github.com/IntelSoftware/NumPy_Optimizations/blob/main/08_03_NumPy_Aggregations.ipynb">08_03_NumPy_Aggregations.ipynb</a></p><h3>Related Articles:</h3><h4>Article 1:</h4><p><a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1?source=your_stories_page-------------------------------------">Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library</a>. Explore the reasons why replacing inefficient Python loops with NumPy or PyTorch constructs is a great idea.</p><h4>Article 2:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-e57c8b068260?source=your_stories_page-------------------------------------">Python Loop Replacement: NumPy Optimizations Simple Stuff — ND array creation using NumPy, PyTorch, DPCTL</a>. Explore simple ways of creating , converting and transforming Lists into NumPy NDarrays — a very basic getting started.</p><h4>Article 3:</h4><p><a href="https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248?source=your_stories_page-------------------------------------">Introduction to NumPy* Universal functions (ufuncs). How I learned to stop worrying and let smart developers help me.</a></p><h4>Article 4: (Current Article)</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362">Replacing Python loops: Aggregations and Reductions</a>. How to replace slow python loops by strategic function equivalents for aggregating data.</p><h4>Article 5:</h4><p><a href="https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df?source=your_stories_page-------------------------------------">Replacing Python loops: Fancy Slicing and Broadcasting</a>. Here I address fancy slicing and broadcasting to take advantage of key optimizations for loop replacement.</p><h4>Article 6:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355?source=your_stories_page-------------------------------------">Python Loop Replacement: PyTorch &amp; NumPy Optimizations. Not your SQL Select clause — Using Where and Select to vectorize conditional logic.</a></p><h4>Article 7:</h4><p><a href="https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9?source=your_stories_page-------------------------------------">Loop Replacement Strategies: Applications to Pandas Apply</a>. Examine how to accelerate Pandas Apply s</p><h4>Article 8:</h4><p><a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">NumPy Functions Composed</a>. <a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">Compare Fast Inverse Square Root Method to NumPy ufuncs, Numba JIT, and Cython — Which One Wins?</a></p><h3><strong>Intel Developer Cloud System Configuration as tested:</strong></h3><p>x86_64<br> CPU op-mode(s): 32-bit, 64-bit<br> Address sizes: 52 bits physical, 57 bits virtual<br> Byte Order: Little Endian<br> CPU(s): 224<br> On-line CPU(s) list: 0–223<br> Vendor ID: GenuineIntel<br> Model name: Intel(R) Xeon(R) Platinum 8480+<br> CPU family: 6<br> Model: 143<br> Thread(s) per core: 2<br> Core(s) per socket: 56<br> Socket(s): 2<br> Stepping: 8<br> CPU max MHz: 3800.0000<br> CPU min MHz: 800.0000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bead33261362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Chatbot on Intel Developer Cloud]]></title>
            <link>https://medium.com/intel-analytics-software/fast-on-ramp-neural-chatbot-on-intel-developer-cloud-no-coding-required-cd607bb1b872?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd607bb1b872</guid>
            <category><![CDATA[neuralchat]]></category>
            <category><![CDATA[fine-tuning-llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 00:29:19 GMT</pubDate>
            <atom:updated>2023-12-14T15:56:33.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42LddHuQFUhx6X7MBRQ9zA.jpeg" /><figcaption>DALL·E 2023–12–11 18.56.03 — a cartoon of bunnies driving a speeding car on a freeway with green overhead exit sign that says _Neural Chat_ (image by author)</figcaption></figure><h4><strong>A Fast On-Ramp to Chatbots with No Coding Required</strong></h4><p>Some of my Intel colleagues recently posted an article on easy creation of high-performance chatbots:</p><p><a href="https://medium.com/intel-analytics-software/neuralchat-simplifying-supervised-instruction-fine-tuning-and-reinforcement-aligning-for-chatbots-d034bca44f69">NeuralChat: Simplifying Supervised Instruction Fine-Tuning and Reinforcement Aligning</a></p><p>My aim is to demonstrate a fast on-ramp to playing with this chatbot based on the 7-billion parameter version of the Mistral foundation model. The neural-chat-7b model was fine-tuned on Intel Gaudi2 AI accelerators using several <a href="https://developer.intel.com/ai">Intel AI software</a> libraries. I am going to show you how to play with this model with prebaked code on the Intel Developer Cloud.</p><p>If you follow these instructions, you can register for a standard free account on Intel Developer Cloud and start playing with a Jupyter Notebook preconfigured for various large language models (LLMs) such as:</p><ul><li>Writer/camel-5b-hf</li><li>openlm-research/open_llama_3b_v2</li><li>Intel/neural-chat-7b-v3–1</li><li>HuggingFaceH4/zephyr-7b-beta</li><li>tiiuae/falcon-7b</li></ul><p>You can do all this without writing a single line of code. Simply type out a prompt and start playing. Powered by Intel Data Center GPU Max 1100s, this notebook provides a hands-on experience that doesn’t require deep technical knowledge.</p><p>Whether you’re a student, writer, educator, or just curious about AI, this guide is designed for you. LLMs have a wide range of applications, but experimenting with them can also be fun. Here, we’ll use some simple pretrained models to explore text generation interactively. Ready to try it out? Let’s set up our environment and start exploring the world of text generation with LLMs!</p><p>The short summary of your on-ramp instructions are listed here and shown in the screenshots below:</p><ol><li>Go to the <a href="https://www.intel.com/content/www/us/en/developer/tools/devcloud/services.html">Intel Developer Cloud</a>.</li><li>Click the “Get Started” button.</li><li>Subscribe to the “Standard — Free” service tier and complete your cloud registration.</li><li>To start up a free Jupyter Notebook session that uses the latest Intel CPUs and GPUs, click the “Training and Workshops” icon.</li><li>Click “Simple LLM Inference: Playing with Language Models.” This will launch a prepopulated Jupyter Notebook (<a href="https://github.com/rahulunair/genAI">simple_llm_inference.ipynb</a>).</li><li>Run all cells.</li><li>Select the model and options to try.</li><li>Select the options and text prompt you want to try out. For options, I suggest choosing a model such as Intel using “with_context” and a prompt similar to “what are the specifications for an NBA basketball, court dimensions, and basket height.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE7kVvUEwLzjmB75KZShsw.png" /></figure><h3><strong>Interactive Prompt</strong></h3><p>The interactive nature of the notebook makes it easy to enter a prompt and generate a response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A87ZZK_QG9nFqzx1_OzWdw.png" /><figcaption>Screenshot of interactive cell in the Jupyter notebook, simple_llm_inference.ipynb, demonstrating how to enter and submit the prompt</figcaption></figure><h3><strong>Generative AI Accuracy Reminder</strong></h3><p>Chatbots such as these are known to produce erroneous results at times and should not be relied upon for accurate or trustworthy answers. For example, when I ran the above notebook with the <em>“Without Context</em>” option and the prompt <em>“what are the specifications for an NBA basketball, court dimensions, and basket height,” </em>the models returned nonsensical answers, i.e.:</p><blockquote>“Bot: An NBA basketball has a diameter of 12 feet (3.7 meters), a height of 3 feet (0.91 meters) above the ground, and a width of 9 feet (2.7 meters)”</blockquote><p>The bot generated the following response when I used the <em>“With Context”</em> option:</p><blockquote>“Bot: . The specifications for an official NBA basketball include a circumference of 29.5 inches (75 cm) and a weight ranging from 20 to 22 ounces (567 to 624 grams). The height of the basketball hoop’s rim is 10 feet (3.05 meters) from the ground.. Regarding the court dimensions, it measures 94 feet (28.65 meters) in length and 50 feet (15.24 meters) in width.”</blockquote><p>While the last response is not absurdly wrong, to me, a layman, it should be double-checked with official NBA specs to ensure the accuracy!</p><h3><strong>Call to Action</strong></h3><p>Try out this no-code approach to experimenting with chatbot models using the standard free Intel Developer Cloud account and the ready-made Jupyter Notebook. Try your hand with different 7B parameter models and prompts of your own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd607bb1b872" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-analytics-software/fast-on-ramp-neural-chatbot-on-intel-developer-cloud-no-coding-required-cd607bb1b872">Neural Chatbot on Intel Developer Cloud</a> was originally published in <a href="https://medium.com/intel-analytics-software">Intel Analytics Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to NumPy* Universal functions (ufuncs)]]></title>
            <link>https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248?source=rss-bcad9f1c533b------2</link>
            <guid isPermaLink="false">https://medium.com/p/83dbbde6248</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python-optimization]]></category>
            <category><![CDATA[ufunc]]></category>
            <dc:creator><![CDATA[Bob Chesebrough]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 00:27:37 GMT</pubDate>
            <atom:updated>2023-12-23T20:57:52.533Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I learned to stop worrying and let smart developers help me.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkWqoc-egeJwSiq9NUScPQ.jpeg" /><figcaption>Image source: Production line icons (<a href="https://www.freepik.com/free-vector/production-line-icons_3949177.htm#query=function&amp;position=30&amp;from_view=search&amp;track=sph">macroventor</a> via freepik)</figcaption></figure><p><strong>What are Universal Functions?</strong></p><p>In NumPy, Universal Functions, ufuncs, are simply functions that operate on NumPy ND arrays in an conceptually element-by-element fashion, supporting <a href="https://numpy.org/doc/stable/user/basics.ufuncs.html#ufuncs-broadcasting">array broadcasting</a>, <a href="https://numpy.org/doc/stable/user/basics.ufuncs.html#ufuncs-casting">type casting</a>, and several other standard features. In reality, many ufuncs are accelerated via a mechanism called vectorization — or the application of single instruction multiple data (SIMD) registers and HW level instructions, perhaps in combination with high level memory optimizations provided by a library or vectorizing “C” compiler, all baked into a pre-built stock version of NumPy*. See my previous article <a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1">“Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library”</a> to get more detail on this.</p><p><strong>Let’s Explore Some Examples of “ufuncs”</strong></p><p>Universal Functions span a wide variety, likely thousands, of commonly used functions. From math “transcendental” functions, such as sines, cosines and tangents, to hyperbolic sines, cosines, and the like to inverse trig and inverse hyperbolic functions logarithm related and exponential related algorithms just to get started.</p><p>Math operations are included too, such as reciprocal, reciprocal, matmul and many, many more. Some of these functions can be invoked as “operators”, such as “+” — invoking addition, or “-“ invoking subtraction, and so on. Functions can be daisy chained too, such as:</p><pre>np.reciprocal(np.sqrt(a))</pre><p>Many bit twiddling functions are included to make it fast and efficient to compare or perform bit wise operations on one or two vectors. For example invoking bitwise AND or bitwise OR, bitwise shifts of numbers, exclusive or operations etc.</p><p>Similarly, logical functions comparing each position of two vectors to identify which positions vector A is greater then or less than vector B, as well as similar logical functions such as finding the locations where two vectors are equal, or performing a logical not on a single vector.</p><p>Then, floating point operations and test are included as well. Such as checking which locations in a vector is finite, where the “Not a Number” (nans) are located, finding where the elements of a vector are infinite (inf) etc.</p><p>Table 1 shows a partial summary of functions included as ufuncs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7mlNl_rU3X0N4VFQUDmGg.png" /><figcaption>Table 1. Partial summary of Universal Functions</figcaption></figure><p>In the code below, we see some simple minded code to round each element of a python list of floats:</p><pre>import random<br>random.seed(42)<br>num = 10_000_000<br>a = []<br>for i in range(num):  # assume we are given a random list, so don&#39;t time this<br>    a.append(random.random()*100) # don&#39;t time this<br><br>b = []<br>for i in range(num):<br>    b.append(round(a[i],5))</pre><p>Compare this above code to the faster and more succinct list comprehension in below:</p><pre>b = [round(x,5) for x in a] # assume we are given a random list</pre><p>Note that in all these following code examples, I convert the python list to a NumPy array — in actual practice, this conversion happens one time near the top of the code, and then we freely reuse the NumPy arrays for all manipulations after that. The speedups attained are more impressive when we take this into consideration. Then compare to the NumPy equivalent below:</p><pre>b = np.round(np.array(a), 5) #assume we strat with  python list</pre><p>The acceleration gained from applying NumPy to replace the loop is remarkable and the readability of the NumPy code is on the same order as the readability of the list comprehension code. See Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Ck8SYi9ucPE7-gHftC-Y6Q.png" /><figcaption>Compare wall clock time of different methods to Round a list of values. Measured on shared node on the new Intel Developer Cloud : Ubuntu 22, I see the following (Intel(R) Xeon(R) Platinum 8480L, 224 CPU, 503GB RAM</figcaption></figure><p>Next I’ll examine composition of functions or nesting or daisy chaining functions. Consider computing the reciprocal of the square root of a value, which is common in physics and engineering. Compare the following three loops for readability and speed:</p><p>Naive Python Loop:</p><pre>for i in range(len(a)):<br>  b.append(1.0/math.sqrt(a[i]))</pre><p>Python List Comprehension:</p><pre>b = [1.0/math.sqrt(x) for x in a]</pre><p>NumPy composed functions of reciprocal and sqrt:</p><pre>b = np.reciprocal(np.sqrt(a))</pre><p>In Figure 2. we se the acceleration provided by combining NumPy ufuncs over the Naive Loop and list comprehension methods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*P0luatRMNW4z7M2A-SJq4g.png" /><figcaption>Figure 2. NumPy Nested ufuncs is faster than Naive loop and list comprehensions methods. Measured on shared node on the new Intel Developer Cloud : Ubuntu 22, I see the following (Intel(R) Xeon(R) Platinum 8480L, 224 CPU, 503GB RAM</figcaption></figure><p><strong>Computing AI focused operations such as mean and std</strong></p><p>Below is code to compute the mean and std of an array, first by rolling my own python loops. Below is the Naive loop:</p><pre>S = 0<br>for i in range (len(a)):  # compute the Sum<br>    S += a[i]<br>mean = S/len(a)  # compute the mean<br>std = 0<br>for i in range (len(a)):  # zero the data around the mean<br>    d = a[i] - mean<br>    std += d*d<br>std = np.sqrt(std/len(a))  # compute the std</pre><p>Below is the NumPy approach. Compare how much more readable, maintainable the NumPy code is. It is also faster on existing hardware and will likely be faster on future hardware or software library updates.</p><pre>print(a.mean())<br>print(a.std())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*xdOugzMYGtC83foUJ-EwAA.png" /><figcaption>Figure 3. Compare computing mean and std using a naive loop versus using NumPy. Measured on shared node on the new Intel Developer Cloud : Ubuntu 22, I see the following (Intel(R) Xeon(R) Platinum 8480L, 224 CPU, 503GB RAM</figcaption></figure><p><strong>How can you determine if the Intel oneMKL library is accelerating your NumPy?</strong></p><p>First of all, the Stock version of NumPy has the Intel(R) oneMKL optimizations built in already. But if you wish to double check, run this python command:</p><pre>np.show_config()</pre><p>You should see output such as this — revealing the Intel oneAPI libraries referenced by NumPy:</p><pre>lapack_mkl_info:<br>    libraries = [&#39;mkl_rt&#39;, &#39;pthread&#39;]<br>    library_dirs = [&#39;/glob/development-tools/versions/oneapi/2023.1.2/oneapi/pytorch/1.13.10.2/lib&#39;]<br>    define_macros = [(&#39;SCIPY_MKL_H&#39;, None), (&#39;HAVE_CBLAS&#39;, None)]<br>    include_dirs = [&#39;/glob/development-tools/versions/oneapi/2023.1.2/oneapi/pytorch/1.13.10.2/include&#39;]</pre><p>Thousands of such examples could be provided but my hope is that I have motivated the use of ufuncs sufficiently for you to try them.</p><h3><strong>Code</strong></h3><p>The code for this article and the rest of the series is located on <a href="https://github.com/IntelSoftware/NumPy_Optimizations">github</a> primarily notebook: 08_02_NumPy_UFUNCS.ipynb</p><h3>Related Articles:</h3><h4>Article 1:</h4><p><a href="https://medium.com/@zmadscientist/accelerate-numerical-calculations-in-numpy-with-intel-oneapi-math-kernel-library-b6e001b74da1?source=your_stories_page-------------------------------------">Accelerate Numerical Calculations in NumPy With Intel oneAPI Math Kernel Library</a>. Explore the reasons why replacing inefficient Python loops with NumPy or PyTorch constructs is a great idea.</p><h4>Article 2:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-e57c8b068260?source=your_stories_page-------------------------------------">Python Loop Replacement: NumPy Optimizations Simple Stuff — ND array creation using NumPy, PyTorch, DPCTL</a>. Explore simple ways of creating , converting and transforming Lists into NumPy NDarrays — a very basic getting started.</p><h4>Article 3: (Current article)</h4><p><a href="https://medium.com/@zmadscientist/introduction-to-numpy-universal-functions-ufuncs-83dbbde6248?source=your_stories_page-------------------------------------">Introduction to NumPy* Universal functions (ufuncs). How I learned to stop worrying and let smart developers help me.</a></p><h4>Article 4:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-numpy-optimizations-bead33261362">Replacing Python loops: Aggregations and Reductions</a>. How to replace slow python loops by strategic function equivalents for aggregating data.</p><h4>Article 5:</h4><p><a href="https://medium.com/@zmadscientist/replacing-python-loops-fancy-slicing-and-broadcasting-1edf554528df?source=your_stories_page-------------------------------------">Replacing Python loops: Fancy Slicing and Broadcasting</a>. Here I address fancy slicing and broadcasting to take advantage of key optimizations for loop replacement.</p><h4>Article 6:</h4><p><a href="https://medium.com/@zmadscientist/python-loop-replacement-pytorch-numpy-optimizations-d2e64ed2f355?source=your_stories_page-------------------------------------">Python Loop Replacement: PyTorch &amp; NumPy Optimizations. Not your SQL Select clause — Using Where and Select to vectorize conditional logic.</a></p><h4>Article 7:</h4><p><a href="https://medium.com/@zmadscientist/loop-replacement-strategies-applications-to-pandas-apply-1999cab731a9?source=your_stories_page-------------------------------------">Loop Replacement Strategies: Applications to Pandas Apply</a>. Examine how to accelerate Pandas Apply s</p><h4>Article 8:</h4><p><a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">NumPy Functions Composed</a>. <a href="https://medium.com/@zmadscientist/numpy-functions-composed-98ff270b0884?source=your_stories_page-------------------------------------">Compare Fast Inverse Square Root Method to NumPy ufuncs, Numba JIT, and Cython — Which One Wins?</a></p><h3><strong>Intel Developer Cloud System Configuration as tested:</strong></h3><p>x86_64<br>CPU op-mode(s): 32-bit, 64-bit<br>Address sizes: 52 bits physical, 57 bits virtual<br>Byte Order: Little Endian<br>CPU(s): 224<br>On-line CPU(s) list: 0–223<br>Vendor ID: GenuineIntel<br>Model name: Intel(R) Xeon(R) Platinum 8480+<br>CPU family: 6<br>Model: 143<br>Thread(s) per core: 2<br>Core(s) per socket: 56<br>Socket(s): 2<br>Stepping: 8<br>CPU max MHz: 3800.0000<br>CPU min MHz: 800.0000</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83dbbde6248" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>