<?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 Dr. Deepak Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Dr. Deepak Kumar Singh on Medium]]></description>
        <link>https://medium.com/@deepak.engg.phd?source=rss-90d344ef909f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZYLXG_-XeLhTm1vO9QmQEQ.jpeg</url>
            <title>Stories by Dr. Deepak Kumar Singh on Medium</title>
            <link>https://medium.com/@deepak.engg.phd?source=rss-90d344ef909f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 05:49:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepak.engg.phd/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[On Reaching 100+ Followers]]></title>
            <link>https://medium.com/@deepak.engg.phd/on-reaching-100-followers-78b9cdc315e9?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b9cdc315e9</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 14:23:03 GMT</pubDate>
            <atom:updated>2021-11-19T14:23:03.519Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>​It has been a good time since I started publishing my work in Data Science on medium though I am from Electronics and Communication.</strong></p><p><strong>​​As followers increased with each published work I got motivation and enthusiasm to toil harder. My genre is dynamic which incorporated several programming languages and techniques however, on medium I found a platform to demonstrate my technical skills by creating effective works.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50YXrFDjy3x4i-IJG6-Axw.jpeg" /></figure><p><strong>I show my humble gratitude to all those who followed me and read my works which is undoubtedly very inspiring and appreciating. Thanks to those who followed me, thanks to the viewers too.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_-fAEMC645_TqyXFXh44w.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b9cdc315e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dimensionality Reduction with Scikit-Learn]]></title>
            <link>https://medium.com/@deepak.engg.phd/dimensionality-reduction-with-scikit-learn-ee5d2b69225b?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee5d2b69225b</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Fri, 12 Nov 2021 16:17:22 GMT</pubDate>
            <atom:updated>2021-11-12T16:17:22.655Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>As a matter of fact, when compression technology came along, we thought the future in 1996 was about voice. We got it wrong. It is about voice, video, and data, and that is what we have today on these cell phones.</blockquote><blockquote><strong>Steve Buyer</strong></blockquote><p><strong>Large datasets</strong> are increasingly widespread in many disciplines. In order to interpret such datasets, methods are required to drastically reduce their dimensionality in an interpretable way, such as most of the information in the data is preserved. <strong>Dimensionality reduction</strong>, an unsupervised machine learning method is used to reduce the number of feature variables for each data sample selecting set of principal features.</p><p>Many techniques have been developed for this purpose, but<strong> Principal Component Analysis</strong> (PCA) is one of the oldest and most widely used. Its idea is simple to reduce the dimensionality of a dataset, while preserving as much ‘variability’ (i.e. statistical information) as possible.</p><h3><strong>1.</strong> <strong>Principal Component Analysis</strong></h3><p><strong>PCA</strong> is a statistical technique to convert high dimensional data to low dimensional data by selecting the most important features that capture maximum information about the dataset. The features are selected on the basis of variance that they cause in the output. The feature that causes <strong>highest variance</strong> is the <strong>first principal component</strong>. The feature that is responsible for <strong>second highest variance</strong> is considered the <strong>second principal component</strong>, and so on. It is important to mention that principal components do not have any correlation with each other.</p><h3><strong>Advantages of PCA</strong></h3><p><strong>A. Data Visualization</strong>: The challenge in today’s world is the sheer volume of data, and the variables/features that define that data. To solve a problem where data is the key, you need extensive data exploration like finding out how the variables are correlated or understanding the distribution of a few variables. Considering that there are a large number of variables or dimensions along which the data is distributed, visualization can be a challenge and almost impossible.</p><p>Hence, PCA can do that for you since it projects the data into a lower dimension, thereby allowing you to visualize the data in a 2D or 3D space with a naked eye.</p><p><strong>B. Speeding Machine Learning (ML) Algorithm</strong>: Since PCA’s main idea is dimensionality reduction, you can leverage that to speed up your machine learning algorithm’s training and testing time considering your data has a lot of features, and the <strong>ML</strong> algorithm’s learning is too slow.</p><p>The <strong>Scikit-learn ML</strong> library provides <strong>sklearn.decomposition.PCA</strong> module that is implemented as a transformer object which learns n components in its <strong>fit()</strong> method. It can also be used on new data to project it on these components.</p><p>Performing PCA using <strong>Scikit-Learn</strong> is a <strong>two</strong>-step process:</p><p>i. Initialize the PCA class by passing the number of components to the constructor.</p><p>ii. Call the <strong>fit</strong> and then <strong>transform</strong> methods by passing the feature set to these methods. The transform method returns the specified number of <strong>principal components</strong>.</p><p>Here value of <strong>0.99</strong>, meaning <strong>99%</strong> of the variance of the original features has been retained. <strong>whiten=True</strong> transforms the values of each principal component so that they have 0 mean and 1 variance. If we put <strong>n_components</strong> in between 0 and 1, PCA returns the minimum amount of features that retain that much variance. Please note down we are reducing features when the <strong>data is linearly inseparable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*qA13tDPy09U8TYqKzweztQ.png" /><figcaption><strong>PCA Code 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*WoNUkk-GXQsPfrel_jAMrA.png" /><figcaption><strong>PCA Result 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Beqf_EkmkJUlJzti888XmA.png" /><figcaption><strong>PCA Result 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*eI-HdJPqp50zcLuX5mE48Q.png" /><figcaption><strong>PCA Result 3</strong></figcaption></figure><p>The PCA class contains <strong>explained_variance_ratio_</strong> which returns the variance caused by each of the principal components. The <strong>explained_variance</strong> variable is a float type array which contains variance ratios for each principal component. The values for the explained_variance variable looks like this for first three principal components:</p><p><strong>[0.24659629 0.18492191 0.13964843]</strong></p><p>It can be seen that the <strong>first principal component</strong> is responsible for <strong>24.65%</strong> variance. Similarly, the <strong>second principal component</strong> causes <strong>18.49%</strong> variance in the dataset. Collectively we can say that <strong>43.14%</strong> of the classification information contained in the feature set is captured by the <strong>first two principal components</strong>. <strong>Grayscale image</strong> is processed here as data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*BYtUKOHs_0cnaTWh5lEIcA.png" /><figcaption><strong>PCA Code 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*EUBfoGsnSO2_g8NY-8MxMw.png" /><figcaption><strong>PCA Result 4</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*NZymDNExAOe5cTHRL6P0DA.png" /><figcaption><strong>Explained Variance Ratio for PCA</strong></figcaption></figure><h3><strong>2.</strong> <strong>Kernel PCA</strong></h3><p><strong>Kernel Principal Component Analysis</strong> (KPCA) is a <strong>non-linear dimensionality reduction</strong> technique. It is an extension of PCA — which is a linear dimensionality reduction technique — using kernel methods. There are various <strong>kernels</strong> used in sklearn.decomposition module such as <strong>‘linear’</strong>, polynomial kernel (<strong>‘poly’</strong>), Gaussian radial basis function kernel (<strong>‘rbf’</strong>), sigmoid kernel (<strong>‘sigmoid’</strong>),<strong> ‘cosine’, ‘precomputed’</strong>, whereas ‘linear’ is default.</p><p>The aim of PCA is to do some classification task on our data. PCA will then be useful if the data are linearly separable. Kernel PCA was developed in an effort to help with the classification of data whose decision boundaries are described by non-linear function. The idea is to go to a higher dimension space in which the decision boundary becomes linear. We have used <strong>grayscale image</strong> as data file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Usok4McuM-wJuZZ43t_T4w.png" /><figcaption><strong>Kernel PCA Code</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*h1AP1oys99a3Y3MoOwHKeA.png" /><figcaption><strong>Kernel PCA Result</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*vMxVVWHHdJUvvA90qlXN6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*fF6kBsygGbkxJmr4mcKPMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*bFRDmvkGkVdTCXy12Wf9_g.png" /></figure><h3><strong>3.</strong> <strong>Sparse PCA</strong></h3><p><strong>Sparse PCA</strong> is a variant of PCA, with the goal of extracting the set of sparse components that best reconstruct the data. <strong>PCA</strong> has a disadvantage that the components extracted by PCA method have exclusively dense expressions, i.e. they have <strong>non-zero coefficients</strong> when expressed as linear combinations of the original variables. This can make interpretation difficult. In many cases, the real underlying components can be more naturally imagined as sparse vectors; for example in face recognition, components might naturally map the parts of faces. Sparse PCA is applied on <strong><em>make_regression</em></strong> dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*TAY32N8SjpREYyH9MK4HOg.png" /><figcaption><strong>Sparse PCA Code and Result</strong></figcaption></figure><h3><strong>4.</strong> <strong>Incremental PCA</strong></h3><p><strong>Incremental Principal Component Analysis</strong> (IPCA) is typically used as a replacement for PCA when the dataset to be decomposed is too large to fit in memory. <strong>IPCA</strong> builds a low-rank approximation for the input data using an amount of memory which is independent of the number of input data samples. It is still dependent on the input data features, but changing the batch size allows for control of memory usage. Incremental PCA is applied here on <strong><em>digits</em></strong> dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*-HyfMaQTjrnPX_ny-JA0XA.png" /><figcaption><strong>Incremental PCA Code</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*vWVrc13L4THlbYD2cUoGxQ.png" /><figcaption><strong>Incremental PCA Result</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*R1aoK1DlsTRrmGN-7fiuMQ.png" /><figcaption><strong>Explained Variance Ratio for Incremental PCA</strong></figcaption></figure><h3><strong>5.</strong> <strong>Fast</strong> <strong>Independent Component Analysis</strong></h3><p><strong>Independent Component Analysis</strong> (ICA) is used to estimate sources given noisy measurements. Imagine 3 instruments playing simultaneously and 3 microphones recording the mixed signals. ICA is used to recover the sources i.e. what is played by each instrument. Importantly, PCA fails at recovering our instruments since the related signals reflect non-Gaussian processes. Fast ICA is applied on <strong><em>digits</em></strong> dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*X2JEyNjMyK_vA5G1k_WQTw.png" /><figcaption><strong>Fast ICA Code and Result</strong></figcaption></figure><h3><strong>6.</strong> <strong>Linear Discriminant Analysis</strong></h3><p>Both <strong>PCA</strong> and <strong>Linear Discriminant Analysis</strong> (LDA) are linear transformation techniques: PCA is unsupervised (it ignores class labels) whereas <strong>LDA</strong> is a <strong>supervised machine learning </strong>which is used to distinguish two classes or groups.</p><p><strong>LDA</strong> can be used to perform supervised dimensionality reduction, by projecting the input data to a linear subspace consisting of the directions which maximize the<strong> separation between classes </strong>(in a precise sense discussed in the mathematics section below). The dimension of the output is necessarily less than the number of classes, so this is in general a rather strong dimensionality reduction, and only makes sense in a <strong>multiclass</strong> setting. In scikit-learn, LDA is implemented using <strong>LinearDiscriminantAnalysis.</strong> A parameter, <strong>n_components</strong>, indicating the number of features we want returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*b4d09GvcRqsr9HpKFjcZxA.png" /><figcaption><strong>LDA Code and Result</strong></figcaption></figure><h3><strong>7. Non-negative Matrix Factorization</strong></h3><p><strong>Non-negative Matrix Factorization</strong> (NMF) is an alternative approach to decomposition that assumes that the data and the components are non-negative. NMF is an <strong>unsupervised</strong> technique for linear dimensionality reduction. In NMF, original data (feature matrix) breaks up into <strong>multiple matrices </strong>(i.e. factorizes) representing the latent relationship between observations and their features.</p><p>NMF can be plugged in instead of PCA or its variants, in the cases where the data matrix does not contain negative values. NMF does not provide explained variance like PCA and other techniques do, so the best way to find the optimum value of <strong>n_components</strong> is by trying a range of values. We applied NMF on <strong><em>breast_cancer</em></strong> dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*pENWJIM30fuPk1MdZsZ5Hw.png" /><figcaption><strong>NMF Code</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*7rJqUrTVx6w_zJuimdNMRg.png" /><figcaption><strong>NMF Result 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*cE5ELIwSqwM9U5gXSBZqGw.png" /><figcaption><strong>NMF Result 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*zfhcaU0QS79wlC3iVzem6A.png" /><figcaption><strong>NMF Result 3</strong></figcaption></figure><h3><strong>8.</strong> <strong>Truncated Singular Value Decomposition</strong></h3><p><strong>Truncated Singular Value Decomposition</strong> (TSVD) is similar to PCA. This transformer performs linear dimensionality reduction by means of Truncated <strong>Singular Value Decomposition</strong> (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently. TSVD is implemented on <strong><em>breast_cancer</em></strong> dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*Zn_cgXoFdaJLdeTQbqyZMg.png" /><figcaption><strong>Truncated SVD Code 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*JHEDQK3tVfHHvPrjWy0Reg.png" /><figcaption><strong>Truncated SVD Code 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Gi1OvocrvNCT50vhe_iVmg.png" /><figcaption><strong>Truncated SVD Result 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*gmTM5aZT5yV2qq-8e5P3gA.png" /><figcaption><strong>Truncated SVD Result 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*fSausiZePxpQJmW_5Ar9bA.png" /><figcaption><strong>Truncated SVD Result 3</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*wnc3M7ckhMy9nc5LzYp6Jg.png" /><figcaption><strong>Truncated SVD Result 4</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*-r3AAXGZjRFEpFCUxCsLsA.png" /><figcaption><strong>Explained Variance Ratio for Truncated SVD</strong></figcaption></figure><h3><strong>9.</strong> <strong>Performance comparison</strong></h3><p>When we have a linear question in mind, dimensionality reduction can be implemented with various <strong>PCAs </strong>techniques, <strong>LDA</strong>, and <strong>NMF</strong>. In performance comparison of various dimensionality reduction techniques, we establish linear relationship between input and output variables. We have used <strong><em>wine</em></strong> dataset. The wine dataset is a classic and very easy multi-class classification dataset. Classes are<strong> class_0, class_1, </strong>and<strong> class_2</strong>. LDA tries to identify attributes that account for the most variance between classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*SD8CqzNV1Z9dkqxfaBD-FQ.png" /><figcaption><strong>Combined Code 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*zgCZ9ft6bq51lIs8Y9n4lA.png" /><figcaption><strong>Combined Code 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*Yu2aQHkw3TNkl0RLqtJ-Xw.png" /><figcaption><strong>Combined Code 3</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*GtXXoc6rPbHmY9gFi2ceBg.png" /><figcaption><strong>Combined Result 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*lf_UDFwRdEt95qhcNB7iBw.png" /><figcaption><strong>Combined Result 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*Q7lAedjwHNXxmjx7v4Hm4g.png" /><figcaption><strong>Combined Result 3</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*_Xnh-gN5SE94EkTcetw3pw.png" /><figcaption><strong>Combined Result 4</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*pzekmQ0aoBbHYryQ87-I8Q.png" /><figcaption><strong>Combined Result 5</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*NIjP97B5bAJPhWiMePVXHg.png" /><figcaption><strong>Combined Result 6</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*8QRTVrn0-nNaFNH12r-wdA.png" /><figcaption><strong>Combined Result 7</strong></figcaption></figure><p><strong>References:</strong> 1. Chris Albon, Machine Learning with Python Cookbook</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee5d2b69225b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numerical Data Analysis using Scikit-Learn]]></title>
            <link>https://medium.com/@deepak.engg.phd/numerical-data-analysis-using-scikit-learn-1d4d30906b86?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4d30906b86</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 09:28:47 GMT</pubDate>
            <atom:updated>2021-10-19T09:28:47.498Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>You can have data without information, but you cannot have information without data.</blockquote><blockquote><strong>Daniel Keys Moran</strong></blockquote><p>A data type which is expressed in numbers, rather than <strong>natural language</strong> description, is defined as <strong>Numerical data</strong>. Sometimes called quantitative data, numerical data is always collected in number form.</p><p>The <strong>sklearn.preprocessing</strong> package provides several common utility <strong>functions </strong>and<strong> transformer</strong> classes to change raw feature vectors into a representation that is more suitable for the downstream estimators.</p><p>In general,<strong> learning algorithms</strong> benefit from standardization of the <strong>data set</strong>. If some outliers are present in the set, robust scalers or transformers are more appropriate. The behavior of the different scalers, transformers, and normalizers on a data set has been observed throughout.</p><h3><strong>1.</strong> <strong>Scaling</strong></h3><p>The values of a <strong>numerical data</strong> (i.e. <strong>feature</strong>) are scaled within the range of 0 and 1.</p><p><strong>1A. Min Max Scaler:</strong> Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*7iqK85Kwck3cqjQfsXOS5Q.png" /><figcaption><strong>MinMaxScaler</strong></figcaption></figure><p>Also known as <strong>min-max scaling </strong>or<strong> min-max normalization</strong>, is the simplest method and consists in rescaling the range of features to scale the range in [0, 1] or [−1, 1]. Selecting the target range depends on the nature of the data. The general formula for a min-max of [0, 1] is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Rr8_PZjrEr1-WO96L9UWGQ.png" /></figure><h3><strong>2.</strong> <strong>Standardizing</strong></h3><p>Features are <strong>Standardized</strong> by removing the mean and scaling to unit variance or in other words, transformation of a feature to have a mean of 0 and a standard deviation of 1.</p><p><strong>2A. Standard Scaler:</strong> Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual features do not more or less look like standard normally distributed data (e.g. <strong>Gaussian</strong> with 0 mean and unit variance).</p><p>For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the<strong> L1</strong> and <strong>L2 regularizers</strong> of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*K1Z5lWA6HlpsPPzHSko3rw.png" /><figcaption><strong>Standard Scaler</strong></figcaption></figure><p>In machine learning, we can handle various types of data, e.g. audio signals and pixel values for image data, and this data can include multiple dimensions. Feature standardization makes the values of each feature in the data have zero-mean (when subtracting the mean in the numerator) and unit-variance. This method is widely used for normalization in many machine learning algorithms (e.g., <strong>SVM, Logistic Regression, and ANN</strong>). The general method of calculation is to determine the distribution mean and standard deviation for each feature. Next we subtract the mean from each feature. Then we divide the values (mean is already subtracted) of each feature by its SD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*5dWwWnvXNbP1qXWZ92nRXQ.png" /></figure><p><strong>2B. Robust Scaler: </strong>Standardize a dataset along any axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*ZfYcfcya_jMiJ0rqj9Fd1A.png" /><figcaption><strong>Robust Scaler</strong></figcaption></figure><h3><strong>3. Scaling Features to a Range</strong></h3><p>Scale each feature to the <strong>[-1, 1]</strong> range without breaking the sparsity.</p><p>This estimator scales each feature individually such that the maximal absolute value of each feature in the training set will be 1.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*W93xn3AU96cHV0uosqu4kw.png" /><figcaption><strong>MaxAbsScaler</strong></figcaption></figure><h3><strong>4.</strong> <strong>Normalization</strong></h3><p>The process of scaling individual samples to have unit norm is known as <strong>Normalization</strong>. This process is useful if you plan to use a quadratic form such as the dot-product or any other kernel to quantify the similarity of any pair of samples.</p><p>The function normalize provides a quick and easy way to perform this operation on a single array-like dataset, either using the <strong>l1, l2, or max norms</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*hZwjqb6dEftbik-qMjtS5g.png" /><figcaption><strong>Normalize (with l2)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*2oDonw8Rtl06iwpNKqgBVA.png" /><figcaption><strong>Normalize (with l1)</strong></figcaption></figure><h3><strong>5. Polynomial Features</strong></h3><p>Features created by raising existing features to an exponent are polynomial features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*6ItzsF4stEpZsxOwiHzH9A.png" /><figcaption><strong>Polynomial Features</strong></figcaption></figure><h3><strong>6. Function Transformer (Custom Transformer)</strong></h3><p>Often, you will want to convert an existing <strong>Python</strong> function into a transformer to assist in data cleaning or processing. You can implement a transformer from an arbitrary function with <strong>FunctionTransformer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*zhItf5E8yJw_2U08ZmMwYw.png" /><figcaption><strong>Function Transformer</strong></figcaption></figure><h3><strong>7. Binarizer</strong></h3><p>The process of thresholding numerical features to get Boolean values is <strong>Feature Binarization</strong>. This can be useful for downstream probabilistic estimators that make assumption that the input data is distributed according to a multi-variate <strong>Bernoulli</strong> distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WXdhW3GG3ejrHh1WTj-dMw.png" /><figcaption><strong>Binarizer</strong></figcaption></figure><h3><strong>8. Non-Linear Transformation</strong></h3><p>There are two types of Transformations: Quantile transforms and Power transforms. Both quantile and power transforms are based on monotonic transformations of the features and thus preserve the rank of the values along each feature.</p><p><strong>8A. Quantile: </strong>Quantile Transformer<strong> </strong>provides a non-parametric transformation to map the data to a <strong>uniform distribution</strong> with values between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*Jx-WTWarHtZGVZi8HK0YBA.png" /><figcaption><strong>Quantile Transformer</strong></figcaption></figure><p><strong>8B. Power:</strong> In many modeling scenarios, normality of the features in a dataset is desirable. Power transforms are a family of parametric, monotonic transformations that aim to map data from any distribution to as close to a <strong>Gaussian distribution</strong> as possible in order to stabilize variance and minimize skewness.</p><p>Power transformer currently provides two such power transformations, the <strong>Yeo-Johnson</strong> transform and the <strong>Box-Cox</strong> transform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*CLC80fkMLT8dzzYrfEP0mg.png" /><figcaption><strong>Power Transformer</strong></figcaption></figure><h3><strong>9. Discretization</strong></h3><p><strong>Discretization</strong>(otherwise known as <strong>quantization</strong> or <strong>binning</strong>) offers a way to partition continuous features into discrete values. Certain datasets with continuous features may benefit from discretization, because discretization can transform the dataset of continuous attributes to one with only nominal attributes.</p><p><strong>9A. KBinsDiscretizer</strong>: This function is used to bin continuous data into intervals.</p><p><strong>encode</strong>: Method used to encode the transformed result</p><p><strong>1. onehot: </strong>Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right.</p><p><strong>2. onehot-dense: </strong>Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right.</p><p><strong>3. ordinal: </strong>Return the bin identifier encoded as an integer value.</p><p><strong>strategy: </strong>Strategy used to define the widths of the bins.</p><p><strong>1. uniform: </strong>All bins in each feature have identical widths.</p><p><strong>2. quantile: </strong>All bins in each feature have the same number of points.</p><p><strong>3. kmeans: </strong>Values in each bin have the same nearest center of a 1D k-means cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*0R8sib-q1TG5VCbIr-uuqQ.png" /><figcaption><strong>KBinsDiscretizer</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*FfkFFyFba3NuyldADrLuMw.png" /><figcaption><strong>KBinsDiscretizer : Encode: All, Strategy: Uniform</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*D8J_UIIM_kNdNkfSeO9XPQ.png" /><figcaption><strong>KBinsDiscretizer : Encode: All, Strategy: Quantile</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*DFbDaCVjkNPPqIfsmmbTdg.png" /><figcaption><strong>KBinsDiscretizer : Encode: All, Strategy: kmeans</strong></figcaption></figure><h3><strong>10. Label Encoder</strong></h3><p><strong>Label Encoder</strong> is a utility class to help normalize labels such that they contain only values between 0 and n_classes-1. It can also be used to transform n<strong>on-numerical labels</strong> (as long as they are <strong>hashable</strong> and <strong>comparable</strong>) to <strong>numerical labels</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*jT_EFdZnMPu4y_jdZYrNag.png" /><figcaption><strong>Label Encoder</strong></figcaption></figure><h3><strong>11. Ordinal Encoder</strong></h3><p>We can use the Ordinal Encoder to convert <strong>categorical</strong> features to such <strong>integer codes</strong>. This estimator transforms each categorical feature to one new feature of integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*HcauFwMyhzIvaJErSQnDQA.png" /><figcaption><strong>Ordinal Encoder</strong></figcaption></figure><h3><strong>12. One-hot Encoder</strong></h3><p>There is another possibility available to convert categorical features to features that can be used with <strong>scikit-learn</strong> estimators is to use a one-of-K, also known as one-hot or dummy encoding. This type of encoding can be obtained with the <strong>OneHotEncoder</strong>, which transforms each categorical feature with categories possible values into categories binary features, with one of them 1, and all others 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*01ujpX2MfkZVk4Jda7PWfg.png" /><figcaption><strong>One-Hot Encoder</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*zRX5uH2cRatJaeunBUOjPw.png" /><figcaption><strong>One Hot Encoder: handle_unknown=ignore</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*R33Xg5NjPC1aaJTNkArzzA.png" /><figcaption><strong>One Hot Encoder: drop= first</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4d30906b86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenCV: Images Handling]]></title>
            <link>https://medium.com/@deepak.engg.phd/opencv-images-handling-593918a8c126?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/593918a8c126</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 17:40:22 GMT</pubDate>
            <atom:updated>2021-10-18T17:40:22.443Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>They’re very strong in memory. Didn’t do very much in microprocessors or digital signal processing.</blockquote><blockquote><strong>Jack Kilby</strong></blockquote><p>Classification between objects is a fairly easy task for us, but it has proved to be a complex one for machines and therefore image classification has been an important task within the field of computer vision, machine learning and image processing.</p><p>To work with images, we will go with <strong>Open Source Computer Vision Library</strong> (OpenCV). OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human.</p><h3><strong>1.</strong> <strong>Reading Images (imread)</strong></h3><p>In this step, we simply store the path to our <strong>image</strong> dataset into a variable and then we create a function to load folders containing images into arrays so that computers can deal with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*yo33r2q-epce5eJWmA4FeA.png" /><figcaption><strong>Reading Image</strong></figcaption></figure><p>It is integrated with various libraries, such as NumPy which is a highly optimized library for numerical operations. Data type of the loading image (which is in grayscale) is <strong>numpy.ndarray</strong>. The image is transformed in matrix whose elements correspond to individual pixels. In grayscale images, the value of an individual elements ranges from 0 (black) to 255 (white) whereas in color images, each element contains three values corresponding to blue, green, red values (<strong>BGR</strong>).</p><p>Use the function <strong>cv2.imshow()</strong> to display an image in a window. The window automatically fits to the image size.</p><p><strong>cv2.waitKey()</strong> is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event. If you press any key in that time, the program continues. If <strong>0</strong> is passed, it waits indefinitely for a key stroke.</p><p><strong>cv2.destroyAllWindows()</strong> simply destroys all the windows we created. If you want to destroy any specific window, use the function <strong>cv2.destroyWindow()</strong> where you pass the exact window name as the argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*nvoYCcGx5aQsUGuwXZgp3A.png" /><figcaption><strong>Reading Image in Grayscale</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*qfKk3sfo82Jz6IMQ_kMGkQ.png" /><figcaption><strong>Image in Grayscale</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*X1YMPYObuC3fUl3eoONgcg.png" /><figcaption><strong>Reading Image in Color</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*KIFs8M1nEq-oOrHtGg6iEQ.png" /><figcaption><strong>Image in Color</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*zZ5l2REIa-QEw-EN107uJw.png" /><figcaption><strong>Image Conversion in RGB</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*gciBJx_m_OGPn3mP8awECg.png" /><figcaption><strong>Image in RGB</strong></figcaption></figure><h3>2. <strong>Storing Images (imwrite</strong>)</h3><p>In this step, we saves images to the filepath specified. If the filepath is same from where we are reading the image, then <strong>imwrite</strong> command will overwrite existing file without outputting an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Q5G93TME61FQiXv32m9k0Q.png" /><figcaption><strong>Storing Image</strong></figcaption></figure><h3><strong>3.</strong> <strong>Resizing Images (resize)</strong></h3><p><strong>Image resizing</strong> refers to the scaling of images. Scaling comes in handy in many image processing as well as machine learning applications. It helps in reducing the number of <strong>pixels</strong> from an image and that has several advantages e.g. It can reduce the time of training of a neural network as more is the number of pixels in an image more is the number of input nodes that in turn increases the complexity of the model. Some common images sizes for ML are 32x32, 64x64, 96x96, and 256x256.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*fQJYauACJ6tHFWqGp143zg.png" /><figcaption><strong>Image Resize</strong></figcaption></figure><h3><strong>4.</strong> <strong>Cropping Images (slicing)</strong></h3><p>There is no specific function for cropping using <strong>OpenCV, NumPy</strong> array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*X-MuThmOgefcko5tO0jeVA.png" /><figcaption><strong>Cropping Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*OZyfRCmuWSwQv4QhZE1HWw.png" /><figcaption><strong>Image Cropped</strong></figcaption></figure><h3><strong>5.</strong> <strong>Blurring and Sharpening Images (blur/ filter2D)</strong></h3><p><strong>Blurring</strong> is the commonly used technique for image processing to removing the noise. It is generally used to eliminate the high-frequency content such as noise, edges in the image. The edges are being blurred when we apply blur to the image.</p><p>There are following blur functions available with OpenCV:</p><p>i.) <strong>Simple blurring</strong> (cv2.blur)</p><p>ii.) <strong>Weighted Gaussian blurring</strong> (cv2.GaussianBlur)</p><p>iii.) <strong>Median blurring</strong> (cv2.medianBlur)</p><p>iv.)<strong> Bilateral filtering</strong> (cv2.bilateralFilter)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*a4PbRsvboW3xrDdSa4eacg.png" /><figcaption><strong>Simple Blur</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*ueycpOpuJggX_1zcAm2HJg.png" /><figcaption><strong>Blurred Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ftJQTw_iJXtWfIkbiy-IPA.png" /><figcaption><strong>Simple Blur</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*_b6bqKtCSHss-69j1L-H1g.png" /><figcaption><strong>Blurred Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*EEmcvg0Wart0-2xarxREKw.png" /><figcaption><strong>Gaussian/Median/Bilateral Blur</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*BXIhVYhdkD0r3NutcHrZwQ.png" /><figcaption><strong>Gaussian Blurred Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*TpW68EqC-O4tkny-Neg9Tg.png" /><figcaption><strong>Median Blurred Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*huJEjz0HFIvbdKy415VzJg.png" /><figcaption><strong>Bilateral Filtered Image</strong></figcaption></figure><p><strong>Image Filtering</strong> is a technique to filter an image just like a one dimensional audio signal, but in 2D. In the program below, we shall learn how to filter an image using 2D Convolution with <strong>cv2.filter2D()</strong> function. The convolution happens between source image and kernel.</p><p><strong>Kernel</strong> is another array that is usually smaller than the source image, and defines the filtering action. A kernel could be a high pass, low pass, or a custom that can detect certain features in the image. Depth is an integer variable that specifies the <strong>depth</strong> in an output image (which is <strong>-1</strong> in this sample program).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*kVgQeQriE9GkDV5RaIxwEg.png" /><figcaption><strong>Image Blurring with Filter2D</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*6eco2TMrMkQlX17WraHmDQ.png" /><figcaption><strong>Blurred Image with Filter2D</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*nOROLF6fPrQS8Cf7LnsILg.png" /><figcaption><strong>Image Sharpening with Filter2D</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*ms79gR37szJxBTFHraZnyQ.png" /><figcaption><strong>Sharpened Image with Filter2D</strong></figcaption></figure><h3><strong>6.</strong> <strong>Image Contrast Enhancing (equalizeHist)</strong></h3><p>OpenCV provides <strong>equalizeHist()</strong> function to easily perform <strong>Histogram Equalization</strong> of an image. It improves the contrast and brightness of an image, in order to stretch out the intensity range. This functionality helps in face detection. It flattens the graylevel histogram of an image so that all intensities are as equally common as possible. We can easily improve lightning of the low contrast image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*ng-tz_llueeu4-1EV4oJPA.png" /><figcaption><strong>Image Contrast Enhancing with equalizeHist()</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*eq9yBsyDYVVP3hYuEZhhHA.png" /><figcaption><strong>Enhanced Contrast</strong></figcaption></figure><p>When we have a grayscale image, we can apply <strong>equalizeHist</strong> directly on the image but for color image we first need to convert the image to <strong>YUV</strong> (Y is luma or Brightness, U and V are color) color format. After successful conversion of the image into YUV format, we can apply equalizeHist and finally we can convert back to its original form of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*239gEFPYz4eRtqmKSAgORw.png" /><figcaption><strong>Color Image Contrast Enhancement</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*qOpmH780IMabBVmSr4vmFA.png" /><figcaption><strong>Color Image Enhanced Contrast</strong></figcaption></figure><h3><strong>7.</strong> <strong>Isolating Images Colors (inRange/bitwise_and)</strong></h3><p><strong>Isolating colors</strong> in OpenCV is simple and lucid. First, we need to convert the image to <strong>HSV</strong> (Hue, Saturation, and Value). Next, we specify some HSV values for the color blue. We create a mask, which uses an<strong> ‘inRange’</strong> statement, for our specific range. This is true or false, black or white. Next, we <strong>‘restore’</strong> our blueness by running a bitwise operation. Basically, we show color where there is the frame and the mask. The white part of the mask will be blue range that was converted to pure white, while everything else became black.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Mnxq4b0_-_GK03UO8uLttQ.png" /><figcaption><strong>Isolating Image Colors using inRange and bitwise_and</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*Gnvy6zTG_HiK-FOa3RinlQ.png" /><figcaption><strong>Isolating Image Colors</strong></figcaption></figure><h3><strong>8.</strong> <strong>Binarizing Images (adaptiveThreshold)</strong></h3><p><strong>Thresholding</strong> is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). Thresholding is a very popular segmentation technique, used for separating an object considered as a foreground from its background. A threshold is a value which has two regions on its either side i.e. below the threshold or above the threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*ASK1ZkPH4HRaw8FL2CuX1w.png" /><figcaption><strong>Image Binarizing</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*6e4EzDgVspKgmNw4iKzW6A.png" /><figcaption><strong>Image Binarizing</strong></figcaption></figure><h3><strong>9.</strong> <strong>Background Removal (grabCut)</strong></h3><p><strong>Foreground extraction</strong> refers to the process of employing image segmentation techniques and algorithms to extract the foreground (desired) and discard the background (undesired) part of an image or video feed.</p><p><strong>Grabcut</strong> is a robust computer vision algorithm for foreground extraction. The algorithm can be summarized as below –</p><p>i. Coordinates of a rectangle enclosing the region of interest are defined (area lying outside these coordinates are automatically defined as part of the background).</p><p>ii. The parts that are classified as ‘background’ in the above step are used as a reference to classify the pixels inside the user-defined-ROI. The Gaussian mixture model is used to label pixels as probable background/foreground.</p><p>iii. Each pixel is connected to its surrounding pixels and each edge is assigned a probability of being foreground or background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*HFQMnCO8FKdqrq1KUEPOuA.png" /><figcaption><strong>Image without Background with grabCut</strong></figcaption></figure><h3><strong>10.</strong> <strong>Edge Detection (Canny)</strong></h3><p><strong>Edge detection</strong> is an image-processing technique, which is used to identify the boundaries (edges) of objects, or regions within an image. Edges are among the most important features associated with images. We come to know of the underlying structure of an image through its edges.</p><p><strong>Canny Edge Detection</strong> is one of the most popular edge-detection methods in use today because it is so robust and flexible. The algorithm itself follows a three-stage process for extracting edges from an image.</p><p>i. Calculating Intensity Gradient of the Image</p><p>ii. Suppression of False Edges</p><p>iii. Hysteresis Thresholding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*LhRa-FcgTYwoDQjfo2zhOQ.png" /><figcaption><strong>Edge Detection with Canny</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*sP-EvoZjVIfQ5JE-JE-1xA.png" /><figcaption><strong>Image Edge Detection</strong></figcaption></figure><h3><strong>11.</strong> <strong>Corner Detections (cornerHarris/dilate/goodFeaturesToTrack)</strong></h3><p>OpenCV has the function <strong>cornerHarris()</strong> for the purpose of detecting corners. It takes the following parameters:</p><p><strong>img</strong> — Input image, it should be grayscale and float32 type.</p><p><strong>size_of_block</strong> — size of the neighbour around each pixel used for corner detection.</p><p><strong>aperture </strong>— Aperture parameter of Sobel derivative used.</p><p><strong>free_parameter</strong> — Harris detector free parameter in the equation (larger values correspond to identifying softer corners.)</p><p><strong>Dilate</strong>: This operation consists of convolving an image with some kernel, which can have any shape or size, usually a square or circle.</p><p>OpenCV has a function, <strong>cv2.goodFeaturesToTrack()</strong>. It finds N strongest corners in the image by Shi-Tomasi method (or Harris Corner Detection). As usual, image should be a grayscale image. Then you specify number of corners you want to find. Then you specify the quality level, which is a value between 0–1, which denotes the minimum quality of corner below which everyone is rejected. Then we provide the minimum Euclidean distance between corners detected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*hTGjoKqDHGyivjp2Hj3S-w.png" /><figcaption><strong>Corner Detection with Harris and dilate</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ypIyqF6APeuaqvMGngUVSA.png" /><figcaption><strong>Corner Detection with goodFeaturesToTrack</strong></figcaption></figure><h3><strong>12.</strong> <strong>Feature Creation</strong></h3><p>In this part, we need to convert an image into an observation for machine learning. With the help of <strong>NumPy’s flatten</strong> function, an image containing multidimensional array convert into a vector containing the observation’s values.</p><p>If image is in grayscale, each pixel represented by one value i.e. either 1 for white or 0 for black. In case of color image, pixels are represented by three channels i.e. red, green, and blue. So in grayscale image, feature values are equal to number of pixel whereas in color image, feature values are multiple of 3 to its pixel contained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*fkYmuHZuBXWpko378oczZA.png" /><figcaption><strong>Feature Creation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*suqi8qKX2byBhP1PQjwVwA.png" /><figcaption><strong>Feature Creation for Grayscale Image</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*zaHgZf7rsENayJnwLbv5DA.png" /><figcaption><strong>Feature Creation for Color Image</strong></figcaption></figure><h3><strong>12.1.</strong> <strong>Encoding Mean Color</strong></h3><p>Here we need to calculate the mean of red, green, and blue channel values for a color image to make three color features representing the mean color in the image. This property of encoding mean color is useful to classify images according to their colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*xxtpbysEPqQUWxIoZ0Rphg.png" /><figcaption><strong>Encoding Mean Color</strong></figcaption></figure><h3><strong>12.2.</strong> <strong>Encoding Color Histograms (calcHist)</strong></h3><p>With this we can create a set of features representing the colors appearing in an image. A histogram is a representation of the distribution of values in data. It can be visualized as a plot that gives a high-level intuition of the intensity (pixel value) distribution.</p><p>OpenCV comes with an in-built <strong>cv2.calcHist()</strong> function for histogram. The parameters are:</p><p>i. <strong>img</strong>: source image of type uint8 or float32. it should be given in as a list, i.e., <strong>[loading_image]</strong>.</p><p>ii. <strong>channels</strong>: it is also given in as a list []. It the index of channel for which we calculate histogram. For example, if input is grayscale image, its value is <strong>[0]</strong>. For color image, you can pass [0],[1] or [2] to calculate histogram of red, green or blue channel, respectively.</p><p>iii. <strong>mask</strong>: mask image. To find histogram of full image, it is set as <strong>None</strong>. However, if we want to get histogram of specific region of image, we should create a mask image for that and give it as mask.</p><p>iv. <strong>histSize</strong>: this represents our BIN count. Need to be given in []. For full scale, we pass <strong>[256]</strong>.</p><p>v. <strong>ranges</strong>: Normally, it is <strong>[0,256]</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*raJIiGSXLzO5eDP2wQXB8Q.png" /><figcaption><strong>Encoding Color Histogram with calcHist</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*3LYNKGpnYLbmT4y-XQU8Aw.png" /><figcaption><strong>Color Histogram Plot</strong></figcaption></figure><p><strong>References</strong>: 1. Chris Albon, Machine Learning with Python Cookbook</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=593918a8c126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: TensorFlow Datasets]]></title>
            <link>https://medium.com/@deepak.engg.phd/part-3-tensorflow-datasets-de4a5de93324?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4a5de93324</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Mon, 04 Oct 2021 10:04:57 GMT</pubDate>
            <atom:updated>2021-10-04T10:04:57.128Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>There are definitely some academic statisticians who just don’t understand why what I do is statistics, but basically I think they are all wrong. What I do is fundamentally statistics. The fact that data science exists as a field is a colossal failure of statistics. To me, that is what statistics is all about. It is gaining insight from data using modelling and visualization. Data munging and manipulation is hard and statistics has just said that’s not our domain.</blockquote><blockquote><strong>Hadley Wickham</strong></blockquote><p>The <strong>tf.data.Dataset </strong>API supports writing descriptive and efficient input pipelines. Dataset usage follows a common pattern:</p><ol><li><strong>Create</strong> a source dataset from your input data.</li><li>Apply dataset <strong>transformations</strong> to preprocess the data.</li><li><strong>Iterate</strong> over the dataset and process the elements.</li></ol><p>Iteration happens in a streaming fashion, so the full dataset does not need to fit into memory.</p><h3><strong>1.</strong> <strong>Source Datasets:</strong></h3><p>A source for datasets can be a NumPy array, tensors in memory, or some other source. If the source involves tensors, use <strong>tf.data.Dataset.from_tensors()</strong> to combine the input, otherwise <strong>use tf.data.Dataset.from_tensor_slices()</strong> if you want a separate row for each input tensor. To process lines from files, use To process lines from files, use <strong>tf.data.TextLineDataset(). </strong>On the other hand, if the input data is located on disk in a <strong>TFRecord </strong>format (which is recommended), construct a<strong> tf.data.TFRecordDataset(). </strong>If we need to create a dataset of all files matching a pattern, use<strong> tf.data.Dataset.list_files().</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*KOYt-n7_tHpMgMgEi7sGbw.png" /><figcaption><strong>Creating Datasets</strong></figcaption></figure><p>The <strong>tf.data.FixedLengthRecordDataset</strong> reads fixed length records from binary files and creates a dataset where each record becomes an element of the dataset. In <strong>tf.data.Dataset.from_generator</strong>, it creates a Dataset whose elements are generated by generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*l017IOiM7RHS47hh7bO86Q.png" /><figcaption><strong>Creating Dataset 1</strong></figcaption></figure><h3><strong>2.</strong> <strong>&amp; 3. Transformations and Iterations:</strong></h3><p>Once you have a dataset, you can apply transformations to prepare the data for your model:</p><h3>Methods</h3><h3>i). as_numpy_iterator() and map</h3><p>A <strong>as_numpy_iterator()</strong> function returns an iterator which converts all elements of the dataset to numpy.</p><p>Map transformation applies <strong>map_func</strong> to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*q6TeeEOoBDSHjQbjP6RMmg.png" /><figcaption><strong>as_numpy_iterator() &amp; map</strong></figcaption></figure><h3><strong>ii). filter and apply</strong></h3><p>In <strong>filter</strong> function, the dataset is filter out according to predicate. Whereas in apply function, it applies a transformation function to the dataset. A <strong>apply</strong> enables chaining of custom Dataset transformations, which are represented as functions that take one Dataset argument and return a transformed Dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*6FQwM-v-dFAdPwAl6EwmGw.png" /><figcaption><strong>Filter &amp; Apply</strong></figcaption></figure><h3>iii). batch</h3><p>Batch function combines consecutive elements of this dataset into batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*TXFyZP6qG8z6JBe6_aC7tg.png" /><figcaption><strong>Batch</strong></figcaption></figure><h3>iv). range and take</h3><p><strong>Range</strong> function creates a Dataset of a step-separated range of values while <strong>take</strong> function creates a Dataset with at most count elements from this dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*u-t0fofIo_DTP7in59m-Iw.png" /><figcaption><strong>Range &amp; Take</strong></figcaption></figure><h3>v). cache</h3><p>This function is used for <strong>caches</strong> the elements in this dataset.</p><p>The first time the dataset is iterated over, its elements will be cached either in the specified file or in memory. Subsequent iterations will use the cached data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*j4J-QJcB8AfaGAnkTzUhpQ.png" /><figcaption><strong>Cache</strong></figcaption></figure><h3>vi). flat map</h3><p>It maps <strong>flat_map</strong> across the dataset and flattens the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*p-F_Vhv0Dnu6VfH0hp7zGw.png" /><figcaption><strong>Flat map</strong></figcaption></figure><h3><strong>vii). repeat and shuffle</strong></h3><p>In repeat, the dataset repeats so each original value is seen count times while <strong>shuffle</strong> randomly shuffles the elements of the dataset. <strong>reshuffle_each_iteration</strong> controls whether the shuffle order should be different for each epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*IkKlTFrGvvbicJcdw9pCWw.png" /><figcaption><strong>Repeat &amp; Shuffle</strong></figcaption></figure><h3>viii. Concatenate and Zip</h3><p><strong>Concatenate</strong> method creates a dataset by concatenating the given dataset with the dataset.</p><p><strong>Zip</strong> method creates a dataset by zipping together the given datasets. This method has similar semantics to the built-in zip() function in Python, with the main difference being that the datasets argument can be a <strong>nested structure</strong> of Dataset objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*LSgCwTKgmhBl1mzZIQ7JdA.png" /><figcaption><strong>Concat &amp; Zip</strong></figcaption></figure><h3>ix. window</h3><p>This function returns a dataset of <strong>“windows”</strong>. Each “window” is a dataset that contains a subset of elements of the input dataset. These are finite datasets of size size (or possibly fewer if there are not enough input elements to fill the window and <strong>drop_remainder</strong> evaluates to <strong>False</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*F7rqMIQOgjcoTsrha0pJtQ.png" /><figcaption><strong>Window</strong></figcaption></figure><p>The<strong> shift</strong> argument determines the number of input elements to shift between the start of each window. If windows and elements are both numbered starting at 0, the first element in window k will be element <strong>k * shift</strong> of the input dataset. In particular, the first element of the first window will always be the first element of the input dataset.</p><p>The <strong>stride</strong> argument determines the stride between input elements within a window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*Vv8MlW9HF90KDbQ7S41x4Q.png" /><figcaption>Window 1</figcaption></figure><h3><strong>4.</strong> <strong>TFDS</strong></h3><p>A <strong>tensorflow_datasets </strong>(tfds) defines a collection of datasets ready-to-use with TensorFlow.</p><p>Each dataset is defined as a <strong>tfds.core.DatasetBuilder</strong>, which encapsulates the logic to download the dataset and construct an input <strong>pipeline</strong>, as well as contains the dataset documentation (version, splits, number of examples, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*devoMelXkocL5X65yOoEOA.png" /><figcaption><strong>TFDS</strong></figcaption></figure><p><strong>References:</strong> 1. www.tensorflow.org</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4a5de93324" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Important TensorFlow Functions for Data Operations and Training]]></title>
            <link>https://medium.com/@deepak.engg.phd/part-2-important-tensorflow-functions-for-data-operations-and-training-297bbd907f15?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/297bbd907f15</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 07:04:23 GMT</pubDate>
            <atom:updated>2021-09-30T07:04:23.788Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I deeply believe that any business that doesn’t make an investment in machine learning in 2017 will fall behind their competition.</blockquote><blockquote>When data volume swells beyond a human’s ability to discern the patterns in it — when a company is faced with truly big data — we need a new form of intelligence. GIS, infused with artificial intelligence, can help executives make better decisions.</blockquote><blockquote><strong>Mansour Raad (ESRI)</strong></blockquote><p>This part demonstrates the key concepts of how <strong>TensorFlow</strong> is built and how it works with complex and intuitive examples. In this part, a collection of TF 2 code samples that show you how to use various APIs that are commonly used in <strong>machine learning</strong>. More specifically, you will see a TF 2 code that involves training a <strong>CNN</strong> (Convolutional Neural Network) in the following section.</p><h3><strong>1.</strong> <strong>Mapping Function</strong></h3><p>The simplest version of <strong>map_fn</strong> repeatedly applies the callable <strong>fn</strong> to a sequence of elements from first to last. The elements are made of the tensors unpacked from <strong>elems</strong>. <strong>dtype</strong> is the data type of the return value of <strong>fn</strong>. Users must provide <strong>dtype</strong> if it is different from the data type of <strong>elems</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*-3sErz8R-jFOMDjf3dFxGg.png" /><figcaption><strong>Map_fn (with NumPy array)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*dgS8AX2Wo3eNkiei1Uk6ow.png" /><figcaption><strong>Map_fn (with Tensor)</strong></figcaption></figure><p>Comparison of<strong> speed</strong> performance of <strong>NumPy</strong> and <strong>TensorFlow</strong> is not that important part for study, as in simple calculations NumPy is little faster than TensorFlow but at the same time TensorFlow performs better in complex problems.</p><h3><strong>2.</strong> <strong>Unique and Where</strong></h3><p><strong>Unique</strong> operation returns a tensor<strong> y</strong> containing all of the unique elements of <strong>x</strong> sorted in the same order that they occur in x; x does not need to be sorted. This operation also returns a tensor <strong>idx</strong> the same size as <strong>x</strong> that contains the index of each value of x in the unique output y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JiveY442P7eombbaRQRzeA.png" /><figcaption><strong>Unique Function</strong></figcaption></figure><p><strong>Where</strong> operator return the elements where Condition is True (<strong>multiplexing</strong> x and y).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*v1-EeRElFI20XjXYaLy5Rg.png" /><figcaption><strong>Where Function</strong></figcaption></figure><h3><strong>3.</strong> <strong>Save and Restore</strong></h3><p><strong>TensorFlow</strong> objects may contain trackable state, such as <strong>tf.Variables, tf.keras.optimizers.Optimizer</strong> implementations, <strong>tf.data.Dataset</strong> iterators, <strong>tf.keras.Layer</strong> implementations, or <strong>tf.keras.Model</strong> implementations. These are called <strong>trackable</strong> objects.</p><p>A<strong> Checkpoint</strong> object can be constructed to save either a single or group of trackable objects to a checkpoint file. It maintains a <strong>save_counter</strong> for numbering checkpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*um5Udr-8uagIILFM2j5T2A.png" /><figcaption><strong>Save and Restore</strong></figcaption></figure><h3><strong>4. Tile, Concat, Stack and Repeat</strong></h3><p><strong>Tile</strong> operation creates a new tensor by <strong>replicating</strong> input multiples times. The output tensor’s <strong>i’th</strong> dimension has <strong>input.dims(i) * multiples[i]</strong> elements, and the values of input are replicated<strong> multiples[i]</strong> times along the <strong>‘i’th dimension</strong>. For example, tiling [a b c d] by [2] produces [a b c d a b c d].</p><p>In,<strong> tf.concat concatenates</strong> tensors along one dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Q9vSz-ke2svqprj8OdK1Fw.png" /><figcaption><strong>Tile and Concat</strong></figcaption></figure><p>In<strong> Stack,</strong> it packs the list of tensors in values into a tensor with <strong>rank</strong> one higher than each tensor in values, by packing them along the axis dimension.</p><p>In <strong>tf.repeat</strong>, the command <strong>repeat</strong> elements of input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*a5w4qUT1SJ4iFOq76Xpexw.png" /><figcaption><strong>Stack and Repeat</strong></figcaption></figure><h3><strong>5.</strong> <strong>Ragged Tensor</strong></h3><p>A <strong>RaggedTensor</strong> is a tensor with <strong>one or more <em>ragged dimensions</em></strong>, which are dimensions whose slices may have <strong>different lengths</strong>. The total number of dimensions in a RaggedTensor is called its <strong><em>rank</em></strong>, and the number of ragged dimensions in a RaggedTensor is called its <strong><em>ragged-rank</em></strong>.</p><p><strong>row_starts:</strong> a vector with shape [nrows], which specifies the start offset of each row. Equivalent to row_splits[:-1].</p><p><strong>row_limits:</strong> a vector with shape [nrows], which specifies the stop offset of each row. Equivalent to row_splits[1:].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aHEPOxNO5TeCfsnT1HqXEQ.png" /><figcaption><strong>RaggedTensor Operations</strong></figcaption></figure><h3><strong>6.</strong> <strong>TFRecord and tf.train.Example</strong></h3><p>The <strong>TFRecord</strong> format is a simple format for storing a sequence of binary records. The <strong>TFRecord</strong> file format is a record-oriented binary format that you can use for training data.</p><p><strong>Protocol buffers </strong>are a cross-platform, cross-language library for efficient serialization of structured data. Protocol messages are defined by <strong>.proto files</strong>, these are often the easiest way to understand a message type. There are two protocol buffer message types available for a <strong>TFRecord</strong>: the <strong>Example </strong>message type and the <strong>SequenceExample</strong> message type.</p><p>The <strong>tf.train.Example </strong>message (or <strong>protobuf</strong>) is a flexible message type that represents a {“string”: value} mapping. It is designed for use with TensorFlow and is used throughout the higher-level APIs such as TFX. You can store any type of data, including images, in the<strong> tf.train.Example</strong> format.</p><p>Fundamentally, a <strong>tf.train.Example</strong> is a {“string”: <strong>tf.train.Feature</strong>} mapping.</p><p>The <strong>tf.train.Feature</strong> message type can accept one of the following <strong>three</strong> types . Most other generic types can be coerced into one of these:</p><ol><li><strong>tf.train.BytesList</strong> (the following types can be coerced)</li></ol><ul><li>string</li><li>byte</li></ul><p><strong>2. tf.train.FloatList</strong> (the following types can be coerced)</p><ul><li>float (float32)</li><li>double (float64)</li></ul><p><strong>3. tf.train.Int64List</strong>(the following types can be coerced)</p><ul><li>bool</li><li>enum</li><li>int32</li><li>uint32</li><li>int64</li><li>uint64</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*28gbN9eJNHg5w4HjsZXpnQ.png" /><figcaption><strong>Command: TFRecord and tf.train.Example</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*dAZflYJ8oP0OqJTDtumyuw.png" /><figcaption><strong>Output: TFRecord and tf.train.Example</strong></figcaption></figure><h3><strong>7.</strong> <strong>TensorBoard: TensorFlow’s visualization toolkit</strong></h3><p><strong>TensorBoard</strong> provides the visualization and tooling needed for <strong>machine learning</strong> experimentation:</p><ol><li>Tracking and visualizing metrics such as loss and accuracy</li></ol><p>2. Visualizing the model graph (ops and layers)</p><p>3. Viewing histograms of weights, biases, or other tensors as they change over time</p><p>4. Projecting embeddings to a lower dimensional space</p><p>5. Displaying images, text, and audio data</p><p>6. Profiling TensorFlow programs and much more</p><h3><strong>8.</strong> <strong>One Hot Encoding</strong></h3><p><strong>Machine learning</strong> algorithms cannot work with categorical data directly. Categorical data must be converted to numbers.</p><p>A <strong>one hot</strong> encoding is a representation of <strong>categorical</strong> variables as binary vectors. This first requires that the categorical values be <strong>mapped</strong> to <strong>integer</strong> values. Then, each integer value is represented as a binary vector that is all zero values except the index of the integer, which is marked with a 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*URw83I9n50cu8jMntuyxHQ.png" /><figcaption><strong>Command: One Hot Encoding</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*XhzImub5nSdYDB5VGyw3aA.png" /><figcaption><strong>Output: One Hot Encoding</strong></figcaption></figure><p><strong>References:</strong> 1. www.tensorflow.org</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=297bbd907f15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Introduction to TensorFlow for Artificial Intelligence]]></title>
            <link>https://medium.com/@deepak.engg.phd/part-1-introduction-to-tensorflow-for-artificial-intelligence-70708b01427e?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/70708b01427e</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 09:52:53 GMT</pubDate>
            <atom:updated>2021-09-22T09:52:53.785Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Artificial Intelligence, deep learning, machine learning — whatever you’re doing if you don’t understand it — learn it. Because otherwise you’re going to be a dinosaur within 3 years.</blockquote><blockquote><strong>Mark Cuban</strong></blockquote><p><strong>TensorFlow</strong> is an end-to-end open source platform for <strong>Artificial Intelligence</strong> (Machine Learning) . It has a comprehensive, flexible ecosystem of tools, libraries and community resources that lets researchers push the state-of-the-art in AI and developers easily build and deploy AI powered applications.</p><p>Let us now consider the following important features of <strong>TensorFlow</strong>:</p><p><strong>A.</strong> It includes a feature of that defines, optimizes and calculates mathematical expressions easily with the help of multi-dimensional arrays called tensors.</p><p><strong>B.</strong> It includes a programming support of deep neural networks and machine learning techniques.</p><p><strong>C.</strong> It includes a high scalable feature of computation with various data sets.</p><p><strong>D.</strong> TensorFlow uses GPU computing, automating management. It also includes a unique feature of optimization of same memory and the data used.</p><h3><strong>Installing TensorFlow and Getting Started</strong></h3><p>Use pip to install <strong>“Tensorflow”</strong> in the system. The command used for installation is mentioned as below:</p><p><strong><em>pip install tensorflow</em></strong></p><p>Execute the following command to initialize the installation of TensorFlow (for Python version 3.5) in Anaconda:</p><p><strong><em>conda create — name tensorflow python=3.5</em></strong></p><p>After successful environmental setup, it is important to activate TensorFlow module.</p><p><strong>activate tensorflow</strong></p><p>To check the version of TensorFlow is installed, we need to use the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*PlHEHZdwXKET00vuCl9L9w.png" /><figcaption><strong>Version Details</strong></figcaption></figure><p>TensorFlow 2.x (TF 2) <strong>eager execution mode</strong> makes code much easier to write compared to <strong>TF 1.x </strong>code (which used <strong>deferred execution mode</strong>).</p><h3><strong>What is Tensor?</strong></h3><p><strong>Tensors</strong> are <strong>multi-dimensional arrays</strong> with a uniform type (i.e. the data types). It is some sorts of similarity with <strong>NumPy</strong>, tensors are (kind of) like np.arrays .</p><p>All tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one.</p><h3><strong>Scalars, Vectors, and Matrices</strong></h3><p><strong>Scalar</strong> can be defined as one-dimensional vector, which include only magnitude and no direction. Examples weight of an object.</p><p>An array of numbers, which is either continuous or discrete, is defined as a <strong>vector</strong>. ML algorithms deal with fixed length vectors for better output generation.</p><p><strong>Matrix</strong> can be defined as multi-dimensional arrays, which are arranged in the format of rows and columns. The <strong>size</strong> of matrix is defined by row length and column length</p><p>The <strong>rank</strong> of scalar is 0 i.e. scalar is also called as rank-0 tensor, vector is rank-1 tensor and traditionally, a rank-2 tensor is referred to as a matrix.</p><p>There is a linkage between tensors and shapes. A rank-1 tensor has a shape of dimension 1, a rank-2 tensor a shape of dimension 2, and a rank-3 tensor of dimension 3.</p><h3><strong>Data Types</strong></h3><p>The Tensorflow supports the following <strong>data types</strong>:</p><p><strong>floating point:</strong> tf.float32, tf.float64</p><p><strong>integers:</strong> tf.int8, tf.int16, tf.int32, tf.int64</p><p><strong>unsigned integers:</strong> tf.uint8, tf.unit16</p><p><strong>strings:</strong> tf.string</p><p><strong>booleans:</strong> tf.bool</p><p><strong>complex numbers:</strong> tf.complex64, tf.complex128</p><p><strong>integer with quantuized ops:</strong> tf.qint8, tf.qint32, tf.quint8</p><h3><strong>1.</strong> <strong>Primitive types</strong></h3><p>TensorFlow supports <strong>tf.constant()</strong> and <strong>tf.Variable()</strong> as primitive types. <strong>tf.constant()</strong> will create tensors on the current device. Inputs which are already tensors maintain their placements unchanged. The <strong>Variable()</strong> constructor requires an initial value for the variable, which can be a <strong>tensor</strong> of any type and shape. This initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods.</p><p>TF provides a number of functions that instantiate basic tensors in memory. The simplest of these are <strong>tf.zeros()</strong> and <strong>tf.ones()</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*G_HX324wGGluEIPZSVlYZQ.png" /><figcaption><strong>Tensor for Ones</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*2p9WM_iqPZPD1TSA7jn57g.png" /><figcaption><strong>Constant &amp; Variables</strong></figcaption></figure><p>Python function <strong>const_mul()</strong> with <strong>TF 2</strong> code that would otherwise be included in a TF 1.x <strong>tf.Session() code block</strong>. Specifically, z would be included in a <strong>sess. run()</strong> statement, along with a <strong>feed_dict</strong> that provides values for <strong>const_a</strong> and <strong>const_b</strong>. Fortunately, a decorated Python function in TF 2 makes the code look like <strong>“normal”</strong> Python code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*L9rUpeg4LlmahmofpGFSZQ.png" /><figcaption><strong>Constant Multiplication</strong></figcaption></figure><p><strong>TF 2</strong> eliminates global collections and their associated Application Programming Interface (<strong>API</strong>), such as <strong>tf.get_variable, tf.variable_scope, </strong>and<strong> tf.initializers. global_variables.</strong> Whenever you need a<strong> tf.Variable</strong> in TF 2, construct and initialize it directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*B-1umX58hQ_S6ulkVUchqw.png" /><figcaption><strong>Assigning Values to Tensor</strong></figcaption></figure><h3><strong>2. Fill</strong></h3><p><strong>tf.fill</strong> creates a tensor<strong> filled</strong> with a scalar value. This operation creates a tensor of shape dims and fills it with value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*DuPYoJOFsBBW1Q1x7jCErQ.png" /><figcaption><strong>Fill</strong></figcaption></figure><h3><strong>3.</strong> <strong>Random Tensors Sampling</strong></h3><p>Random normal generates new sets of random values from a <strong>normal distribution</strong>. Whereas truncated normal generates sets from a <strong>truncated normal distribution</strong>.</p><p>Uniform random generates random values from a <strong>uniform distribution</strong>. The generated values follow a uniform distribution in the range (<strong>minval, maxval)</strong>. The lower bound <strong>minval</strong> is included in the range, while the upper bound <strong>maxval</strong> is excluded.</p><p>In shuffle, tensor <strong>shuffles</strong> randomly along its first dimension. The tensor is shuffled along dimension 0, such that each <strong>value[j]</strong> is mapped to one and only one <strong>output[i]</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ERRFYy2KgTQyQ_HbcL28RQ.png" /><figcaption><strong>Input: Random Distribution and Shuffling</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*ju286Tj6FbUns3EFPpu0CQ.png" /><figcaption><strong>Output: Random Distribution and Shuffling</strong></figcaption></figure><h3><strong>4.</strong> <strong>Rank and Shape</strong></h3><p>The rank of a tensor is not the same as the <strong>rank</strong> of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as “order”, “degree”, or “ndims.”</p><p>Whereas, <a href="https://www.tensorflow.org/api_docs/python/tf/shape"><strong>tf.shape</strong></a> returns a 1-D integer tensor representing the shape of input. For a scalar input, the tensor returned has a <strong>shape</strong> of (0,) and its value is the empty vector (i.e. []).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*sJmMj59C4ANnVXxD50wcTQ.png" /><figcaption><strong>Rank &amp; Shape</strong></figcaption></figure><h3><strong>5.</strong> <strong>Cast</strong></h3><p>It <strong>casts</strong> a tensor to a new type (i.e. <strong>data type</strong>). The operation supports data types of uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64, complex64, complex128, bfloat16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*g41YZ7lEXjJn0u9mZF9efQ.png" /><figcaption><strong>Casting</strong></figcaption></figure><h3><strong>6.</strong> <strong>Matrix Operations</strong></h3><p><strong>TF</strong> provides a variety of amenities for working with <strong>matrices</strong>. (Matrices by far are the most common type of tensor used in practice). In particular, TF provides shortcuts to make certain types of commonly used matrices. Various matrix operations are performed below in which <strong>matrix multiplication</strong> is important as it is widely used in <strong>ML</strong> methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*7I30ByjiyG42D6kpMB6ihA.png" /><figcaption><strong>Input: Various Matrix Operations</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*DCDXTJAtT1a45iFo__M-0w.png" /><figcaption><strong>Output: Various Matrix Operations</strong></figcaption></figure><h3><strong>7.</strong> <strong>Reshape</strong></h3><p>The <a href="https://www.tensorflow.org/api_docs/python/tf/reshape"><strong>tf.reshape</strong></a> does not change the order of or the total number of elements in the tensor, and so it can reuse the underlying data buffer. This makes it a fast operation independent of how big of a tensor it is operating on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aZ0vuZ5ym-A422DDDF16zQ.png" /><figcaption><strong>Reshape Tensor</strong></figcaption></figure><h3><strong>8.</strong> <strong>Imperative and Declarative</strong></h3><p>In this program, machine code instructs the machine to perform a <strong>primitive</strong> addition operation on <strong>two registers</strong>, one containing <strong>4</strong>, and the other containing<strong> 6</strong>. The result is then <strong>10</strong>. This style of programming is called <strong>imperative</strong> since the program tells the computer explicitly which actions to perform. In a <strong>declarative</strong> system, a computer program is a high-level description of the computation that is to be performed. It does not instruct the computer exactly how to perform the computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*dMzE3KkvqXHT8VFiwkeI-A.png" /><figcaption><strong>Imperative &amp; Declarative</strong></figcaption></figure><p>TF 2 introduced the <strong>@tf.function “decorator”</strong> for Python functions that defines a <strong>graph</strong> and performs <strong>session execution</strong>: it’s sort of a “successor” to <strong>tf.Session()</strong> in <strong>TF 1.x.</strong> Since graphs can still be useful, <strong>@tf.function</strong> transparently converts Python functions into functions that are <strong>“backed”</strong> by <strong>graphs</strong>. This decorator also converts tensor-dependent Python control flow into TF control flow, and also adds control dependencies to order read and write operations to a <strong>TF 2</strong> state. Remember that <strong>@tf.function</strong> works best with <strong>TF 2</strong> operations instead of <strong>NumPy</strong> operations or Python primitives.</p><h3><strong>9.</strong> <strong>Arithmetic Operations</strong></h3><p>The following program shown below is to perform the four <strong>arithmetic</strong> operations on tensors in <strong>TF 2</strong>: <strong>addition, subtraction, multiplication, and division</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*xl1rnmk1CpRn-cIK8iHyTA.png" /><figcaption><strong>Arithmetic Operations</strong></figcaption></figure><p>Arithmetic operations involving<strong> TF 2</strong> constants and variables can also perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*RqPeXKqqsQRyuS2JCjHAeQ.png" /><figcaption><strong>Arithmetic Operations 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*K9A8HVfnc7oDCA0KfcOXMw.png" /><figcaption><strong>Arithmetic Operations 2</strong></figcaption></figure><h3><strong>10.</strong> <strong>Reduction Operation</strong></h3><p>TF supports different kinds of reduction. <strong>Reduction</strong> is an operation that removes one or more dimensions from a tensor by performing certain operations across those dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*sEJYqKZ_l9Ix6Rl4obj6mg.png" /><figcaption><strong>Various Reduction Operations</strong></figcaption></figure><h3><strong>11.</strong> <strong>String</strong></h3><p><strong>tf.string</strong> is a dtype, which is to say you can represent data as strings (variable-length byte arrays) in tensors. The <strong>strings</strong> are atomic and cannot be indexed the way Python strings are. The length of the string is not one of the axes of the tensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*8LRnlNw5KbEBYTbBYbDX0A.png" /><figcaption><strong>String</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*3ejoRdn5GL11yKJdpoRxsw.png" /><figcaption><strong>String: Split &amp; Join</strong></figcaption></figure><p>Please note, a <strong>ragged constant</strong> is a set of elements that have different lengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*-w0Sh_4slUVNqnKBOLlVug.png" /><figcaption><strong>String: Decoding &amp; Encoding</strong></figcaption></figure><h3><strong>12.</strong> <strong>Convert to Tensor</strong></h3><p>This function <strong>converts</strong> Python objects of various types to Tensor objects. It accepts Tensor objects, numpy arrays, Python lists, and Python scalars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*ipH5rqjpIveu4IoegOL3Jw.png" /><figcaption><strong>Convert to Tensor</strong></figcaption></figure><h3><strong>13.</strong> <strong>Gradient</strong></h3><p>TF provides the <strong>tf.GradientTape API</strong> for automatic differentiation; that is, computing the gradient of a computation with respect to some inputs, usually <strong>tf.Variable</strong>s. TensorFlow <strong>“records”</strong> relevant operations executed inside the context of a <strong>tf.GradientTape</strong> onto a <strong>“tape”</strong>. TF then uses that tape to compute the gradients of a “recorded” computation using reverse mode differentiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*q9KxILmS4wYp_K2UtIwalQ.png" /><figcaption><strong>GradientTape</strong></figcaption></figure><p>The <strong>variable x</strong>, followed by a with statement that initializes the <strong>variable y</strong> with the expression <strong>x*x</strong>. Next, the v<strong>ariable grad</strong> is initialized with the derivative that is returned by the <strong>grad_tape</strong>, and then evaluated with the <strong>current value of x</strong>.</p><p>By default <strong>GradientTape</strong> will automatically watch any trainable variables that are accessed inside the context. If you want fine grained control over which variables are watched you can disable automatic tracking by passing <strong>watch_accessed_variables=False</strong> to the tape constructor.</p><p>In case<strong> derivatives</strong>, the next code block shows you a function <strong>y</strong>, its <strong>first</strong> <strong>derivative y’</strong>, and its <strong>second derivative y’’</strong>:</p><p><strong><em>y = 4*x*x*x</em></strong></p><p><strong><em>y’ = 4*3*x*x</em></strong></p><p><strong><em>y’’ = 12*2*x</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RwxymoR23OsANIiYJJrtFw.png" /><figcaption><strong>GradientTape: Nested Loop</strong></figcaption></figure><h3><strong>14.</strong> <strong>Equal and Maximum Values</strong></h3><p>The TF 2 <strong>tf.argmax() API </strong>determines the index values containing maximum values on a row-wise basis or on a column-wise basis for a TF 2 tensor. Just to be sure you understand the previous statement: the TF 2 <strong>tf.argmax() API</strong> determines the index values that contain maximum values and not the actual <strong>maximum values</strong> in those index positions. <strong>equal() </strong>is used to perform element by <strong>equality</strong> comparison. It performs argument broadcasting before applying the comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*qW5n4ZG-RNMY3tosXlUH6A.png" /><figcaption><strong>argmax &amp; equal</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*GPNiXTR4W08DRAX_Wv9JNQ.png" /><figcaption><strong>Combined argmax &amp; equal</strong></figcaption></figure><p><strong>References:</strong> 1. <a href="http://www.tensorflow.org/">www.tensorflow.org</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70708b01427e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Common and Uncommon Types and Operations in Python]]></title>
            <link>https://medium.com/@deepak.engg.phd/important-common-and-uncommon-types-and-operations-in-python-70da972bd928?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/70da972bd928</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 06:02:36 GMT</pubDate>
            <atom:updated>2021-09-16T06:02:36.451Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code — not in reams of trivial code that bores the reader to death.</blockquote><blockquote><strong>Guido van Rossum</strong></blockquote><p>Before we begin with the code, let’s first create a vivid representation of Python Conceptual Hierarchy. <strong>Python</strong> programs can be disintegrated into modules, statements, expressions, and objects. As follows:</p><p>1. Programs are collaboration of modules.</p><p>2. Modules incorporate statements.</p><p>3. Statements comprise of expressions.</p><p>4. Expressions form and process objects.</p><p>Python’s <strong>built-in object</strong> types and some of the syntax used to code their literals — that is, the expressions that generate these objects. The following table below shows the important build-in object types:</p><p><strong>Numbers: </strong>12345, 1.2345, 1+2j, 0b123, Decimal(), Fraction()</p><p><strong>Strings: </strong>‘python’, “Mark’s”, b’a\x01c’, u’sp\xc4m’</p><p><strong>Lists: </strong>[1, 2,[3, ‘four’], 5.6], list(range(5))</p><p><strong>Dictionaries: </strong>{‘beverages’: ‘drink’, ‘desert’: ‘sweet’}, dict(hours=5)</p><p><strong>Tuples: </strong>(2, ‘eggs’, 4, ‘U’), tuple(‘junk’), namedtuple</p><p><strong>Sets: </strong>set(‘xyz’), {‘x’, ‘y’, ‘z’}</p><h3><strong>1.</strong> <strong>Immutability</strong></h3><p>Every object in Python is classified as either immutable (<strong>unchangeable</strong>) or not. In terms of the core types, numbers, strings, and tuples are immutable; lists, dictionaries, and sets are not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*YN4FgGGoJFeyQBO5aMR0Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*jux7EHmITpKBx_jhg9v6hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*G5G_iSnn5ib5eFJ4-VaTKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*PHjeTwSAd5xb7ZcrT2ZOMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*hsMzGX_TU3eo4ywQptLvyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*pcTntZvB6QBNIe2Z5r_wKQ.png" /></figure><h3><strong>2.</strong> <strong>Formatting (String Function)</strong></h3><p>The <strong>format()</strong> method formats the specified value(s) and insert them inside the string&#39;s placeholder. The placeholder is defined using curly brackets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*4k3YoZK36Vzvth99LYPG3g.png" /></figure><h3><strong>3.</strong> <strong>Splitting (String Function)</strong></h3><p>A <strong>split()</strong> function in Python splits the string at the specified separator, and returns a list. In this fashion, strings can be converted or split into list. Whereas <strong>rsplit()</strong> method splits a string into a list, starting from the right. If no “max” is specified, this method will return the same as the <strong>split()</strong> method. A <strong>splitlines()</strong> method splits the string at line breaks and returns a list. The splitting is done at line breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*Vf3TJhZkof05s2wWWsj9Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*CJG0tFPDqr5npaWwCvLB6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*cZaErSpclxqzO4xhQu-w_w.png" /></figure><h3><strong>4.</strong> <strong>Stripping (String Function)</strong></h3><p>Python’s <strong>strip()</strong> function is a part of built-in functions available in the Python library. The <strong>strip()</strong> method removes given characters from start and end of the original string. By default,<strong> strip()</strong> function removes white spaces from start and end of the string and returns the same string without white spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*2SIPiVFfeAIvyckQ7m-lhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*FSu-WcXKekzFzb5nLFsMmA.png" /></figure><h3><strong>5.</strong> <strong>Find and Replace ( String Function)</strong></h3><p>Python String <strong>find()</strong> is a function available in Python library to find the index of the first occurrence of a substring from the given string. The string <strong>find()</strong> function will return -1 instead of throwing an exception, if the specified substring is not present in the given string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*7blOJubnN2eUisl1bFsfQg.png" /></figure><p>The Python function <strong>rfind()</strong> is similar to find() function with the only difference is that <strong>rfind()</strong> gives the highest index for the substring given and <strong>find()</strong> gives the lowest i.e the very first index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*0NHyuMSZTPFujvUIWETEjw.png" /></figure><p>If the value is not found, the <strong>rfind()</strong> method returns -1, but the rindex() method will raise an exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*CMDQCvgSvV9Bs9Foc88KHw.png" /></figure><p>The Python’s <strong>replace()</strong> is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*gxwHAsL5nLS4ss1ryWPRIg.png" /></figure><h3><strong>6.</strong> J<strong>oin (on Tuple and Dictionary)</strong></h3><p>The<strong> join()</strong> method takes all items in an iterable and joins them into one string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*qiW32hX5HVd0uw8C-b5R0A.png" /></figure><h3><strong>7.</strong> P<strong>op (List Function)</strong></h3><p>Python list <strong>pop()</strong> is an inbuilt function in Python that removes and returns the last value from the list or the given index value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*aUEDgwiz1wKE4GqkphDhIw.png" /></figure><h3><strong>8.</strong> <strong>Reversed</strong></h3><p>In Python Build-in function, <strong>reversed()</strong> method returns an iterator that accesses the given sequence in the reverse order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*F6sVUT5Nr9CiFATGS3QUGw.png" /></figure><h3><strong>9.</strong> <strong>Enumerate</strong></h3><p>The <strong>enumerate()</strong> method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RU_-QI5ZOHykXU5no18vfA.png" /></figure><h3><strong>10. Frozenset</strong></h3><p>The <strong>frozenset()</strong> is an inbuilt function in Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Q-uY-L-eSEZYt_aAw5iuQg.png" /></figure><h3><strong>11.</strong> <strong>Zip and Set</strong></h3><p>The <strong>zip()</strong> function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.</p><p>The<strong> set()</strong> function creates a set object. The items in a set list are unordered, so it will appear in random order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*u9rguNRPIuSRxLDa5TU0Qw.png" /></figure><h3><strong>12.</strong> <strong>Bytearray and Memoryview</strong></h3><p>The <strong>bytearray()</strong> function returns a bytearray object. It can convert objects into bytearray objects, or create empty bytearray object of the specified size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*NlNEe2DTL18l88mnpJuUeg.png" /></figure><p>The <strong>memoryview()</strong> method returns a memory view object of the given object. The memoryview object allows Python code to access the internal data of an object that supports the buffer protocol without copying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*NtUKizBcQQhQ0dDswTvsBA.png" /></figure><h3><strong>13.</strong> <strong>Compile</strong></h3><p>Consider a situation where we have a piece of Python code in a string and we want to compile it so that we can later run it when needed. The compile method does this task. It takes sourcecode as input and returns a code object which is ready to be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*XQGf-FAjQ5y9FQuYlBsicw.png" /></figure><h3><strong>14.</strong> <strong>Extend( List function)</strong></h3><p>The Python <strong>extend()</strong><em> </em>method iterates over an iterable like string, list, tuple, etc., and adds each element of the iterable to the end of list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*68RQmmA5WtnI2fladglP6Q.png" /></figure><h3><strong>15.</strong> <strong>Keys (Dict function)</strong></h3><p>The <strong>keys()</strong> method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary.</p><p>The <strong>fromkeys()</strong> method returns a dictionary with the specified keys and the specified value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*yepGqju1R5CBHiQW6YkDIg.png" /></figure><h3><strong>16.</strong> <strong>Difference (Dict function)</strong></h3><p>The <strong>difference() </strong>method returns a set that contains the difference between two sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*sSrYeuUczPVz-fwruULxXA.png" /></figure><p>The <strong>difference_update()</strong> method removes the items that exist in both sets.The <strong>difference_update()</strong> method is different from the difference() method, because the <strong>difference()</strong> method <em>returns a new set</em>, without the unwanted items, and the <strong>difference_update()</strong> method <em>removes</em> the unwanted items from the original set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Sa8qQhfVSS7auNPNSPgU-w.png" /></figure><p>The <strong>symmetric_difference()</strong> method returns a set that contains all items from both set, but not the items that are present in both sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*3g8-v06QGSJwchf1h1tv0g.png" /></figure><p>The <strong>symmetric_difference_update()</strong> method updates the original set by removing items that are present in both sets, and inserting the other items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*dDN_-RxrtwvVrW2_v1k8rw.png" /></figure><h3><strong>17.</strong> <strong>Discard and Remove (Dict function)</strong></h3><p>The built-in method, <strong>discard()</strong> in Python, removes the element from the set only if the element is present in the set (same as<strong> remove()</strong>). If the element is not present in the set, then no error or exception is raised and the original set is printed but in <strong>remove()</strong> if the element is not present in the set, then an error or exception is raised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*S1RziK4RcnCmURULTXEyQA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70da972bd928" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: NLP-Text Corpora and Lexical Database]]></title>
            <link>https://medium.com/@deepak.engg.phd/part-2-nlp-text-corpora-and-lexical-database-ab4749e2ab0b?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4749e2ab0b</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 06:52:23 GMT</pubDate>
            <atom:updated>2021-09-05T06:52:23.347Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In our daily lives as programmers, we process text strings a lot. So I tried to work hard on text processing, namely the string class and regular expressions. Regular expressions are built into the language and are very tuned up for use.</blockquote><blockquote><strong>Yukihiro Matsumoto</strong></blockquote><p>Corpora are large collections of linguistic data. In fact, <strong>corpora</strong> are not always just random collections of data. Many corpora are designed to contain a careful balance of material in one or more genres.</p><p>Corpora are designed to achieve specific goal in <strong>NLP</strong>: data should provide best representation for the task. Such tasks are for example: word sense disambiguation, coreference resolution, machine translation and part of speech tagging.</p><h3><strong>1. Access to Text Corpora:</strong></h3><p><strong>Linguistic data</strong>, or corpora contains dozens of individual texts-one per addresses. There are varieties of text corpora which we will examine one by one.</p><p><strong>A.</strong> <strong>Gutenberg Corpus:</strong></p><p>Project Gutenberg includes small section of texts from electronic text archive. <strong>Gutenberg</strong> contains some 25,000 free electronic books, hosted as <a href="http://www.gutenberg.org/"><strong>http://www.gutenberg.org/</strong></a>.</p><p>First we load the <strong>NLTK</strong> package, and then file identifiers in the <strong>Gutenberg corpus</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*QYHWKieoXoqBtQrqmgLPTA.png" /></figure><p>Let’s pick up<em> Paradise Lost by Milton</em> and give it a short name milton, then find how many words it contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*0uk5dCKLmlDHZ8vmjCYLag.png" /></figure><p>Book Paradise Lost contains 96825 words including symbols and punctuations.</p><p>To examine data from <strong>nltk.corpus</strong>, you have to employ the following pair of statements to perform concordance and other tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LAJRFl4zIqFzofXleuM8Ag.png" /></figure><p><strong>Python</strong> provides another version of the import statement to avoid cumbersome to type such long names all the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*Am3jbgm6Uv9RLRpwbfqruw.png" /></figure><p>This program displays <strong>seven</strong> statistics for each text: number of sentence, number of words used, total number of characters, number of vocabulary used, average sentence length, average word length and the number of times each vocabulary item appears in each text on an average. The <strong>raw()</strong> function gives us the contents of the file without any linguistics processing. For example, <em>len(gutenberg.raw(‘melville-moby_dick.txt’)</em> tells how many letters occur in the text, including the spaces between words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uO6W9_pk2qAgb-ZIBTGSLw.png" /></figure><p>The <strong>sents() </strong>function divides the text up into its sentences, where each sentence is a list of words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EupRSSJXGuAJJYLYND9a1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*Qnf056UpUzXyL331Hdb_-Q.png" /></figure><p><strong>B.</strong> <strong>Web and Chat Text:</strong></p><p>NLTK’s small collection of <strong>web text</strong> includes content from a Firefox discussion forum, movie script of Pirates of the Caribbean, personal advertisements, and wine reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*PfVjFIS9G-bX0UU4hLfrVg.png" /></figure><p>There is a <strong>corpus</strong> of <strong>instant messaging chat sessions</strong>. The corpus contains over 10,000 posts, organized into 15 files. The filename contains the date, chatroom, and number of posts e.g. 10–19–30s_705posts.xml contains 705 posts gathered from the 30s chat room on 10/19/2006.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*0EMDnnp65TepjZFDf12WMg.png" /></figure><p><strong>C.</strong> <strong>Brown Corpus:</strong></p><p>The first million-word electronic corpus in English, created in 1961 at <strong>Brown University</strong>. This corpus contains text from 500 sources, and the sources have been categorized by genre, such as news, editorial, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*Pk180tl1o467M3gn0seKKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7I-ktngR1xUXyehHWq253A.png" /></figure><p>The<strong> brown corpus</strong> is a meaningful resource for studying systematic differences between genres, a kind of linguistic inquiry known as stylistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*s9LtVZmQ-CrlYr6A-rRPeQ.png" /></figure><p><strong>D. Reuters Corpus:</strong></p><p>This <strong>corpus</strong> contains 10,788 news documents totaling 1.3 million words. They are classified into 90 topics and they are grouped into two sets, called training and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*sDdhjIC_NScBcoZf9HdsJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*IBcaQWquoYps8l2jbBIh9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*A3a0QQF0tjcCZQNeuAOIvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gSMFeDLuPGfiNmkuzzDGXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*9Q4itxFJ6nrkHTedtpEpWA.png" /></figure><p><strong>E. Inaugural Address Corpus:</strong></p><p>Inaugural address corpus is a collection of 55 texts, one for each presidential address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*JfoGFjxTKoNr6w7zlCPVAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*8sE5ruz8nLtcmrVbITZcIA.png" /></figure><p>Here we will use <strong>conditional frequency distributions</strong> to obtain counts for each corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aoUek60GKT1GZEw_mSWA9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*4oLy5d_wRBxycJY6qGYyMg.png" /></figure><p><strong>F. Annotated Text Corpus:</strong></p><p>Many texts corpora contain <strong>linguistic annotations</strong>, representing part-of-speech tags, named entities, syntactic structures, semantic roles, and so forth. For more information and data packages containing corpora and corpus samples, download them via <a href="http://www.nltk.org/data"><strong>http://www.nltk.org/data</strong></a> and for how to access them, please go for <strong>Corpus HOWTO</strong> at <a href="http://www.nltk.org/howto"><strong>http://www.nltk.org/howto</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*T-lr_9E4MXPweuWHIOf_Jw.png" /></figure><p><strong>G. Corpus in other languages:</strong></p><p><strong>NLTK </strong>comes with corpora for many languages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*SiUOXDOO6USAThcZoknwCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*br5-osoFBR0JM1t20IpioA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*afzXAQPutu46e8Wnpl1cFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Rhp7iCKJPDXCNv9rI2wp5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*dGdbv7LAJxrn9HdNmz4cOQ.png" /></figure><p><strong>H. Text Corpus Structure:</strong></p><p>It is a collection of texts. Isolated structure is the simplest kind of corpus which doesn’t have any particular organization such as <strong>Gutenberg, webtext, udhr</strong> etc,. Some corpus are structured into categories such as <strong>genre</strong> (Brown corpus); some categorized as <strong>overlap</strong>, such as topic categories (Reuters Corpus), some are represented as <strong>language distributed over time</strong> (Inaugural Address corpus).</p><p><strong>I.</strong> <strong>Creating your Own Corpus:</strong></p><p>First load own collection of text files with the help of NLTK’s <strong>PlaintextCorpusReader</strong>. Second parameter of PlaintextCorpusReader <strong>initializer</strong> can be a list of fields, like [‘x.txt’, ‘text/x.txt’] or a pattern that matches all fields. We have to assign location of the files to <strong>corpus_root</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*PDK9ZYrUbNyZXlqkvOZNOg.png" /></figure><h4><strong>1.1.</strong> <strong>Conditional Frequency Distributions (CFD):</strong></h4><p>A <strong>CFD</strong> is a collection of frequency distributions, computed based on a condition. The <strong>condition</strong> will often be the category of the text such as counting words appearing in a text collection (Condition: Romance in brown corpus; cute, Monday, will appear 3, 1, 4 times respectively)|</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*VXTeaN_gvwkgocQZnyWJlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Lj0wo8L8jLyY9Cz0Mj_Jeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*pKcIC0_1q6IzdMK7G0Nk3A.png" /></figure><p><strong>1.2.</strong> <strong>Random Text with Bigrams:</strong></p><p>Bigram or word pair can be created using <strong>conditional frequency distribution</strong>. The predefined <strong>bigrams()</strong> function builds a list of consecutive word pairs from a list of words available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zm8Bb9xc1UL9EVnUwYABBg.png" /></figure><h3><strong>2. Lexical Database or Resources:</strong></h3><p>A lexicon is a collection of words and/ or phrases along with associated information, like part-of-speech and sense definitions. Lexical resources are created to enrich the text as they are secondary to texts.</p><p><strong>Lexicon</strong> entry consists of a lemma along with additional information. Two distinct words having the same spelling are called <strong>homonyms</strong>.</p><p>e.g. Bank, where money is kept and Bank, River bank. Here Bank is <strong>Lemma</strong></p><p><strong>2.1. Wordlist Corpora:</strong></p><p>NLTK includes some corpora that are nothing more than wordlists. These <strong>unusual or misspelled words</strong> are widely included in a text corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aF5KLdv0QRD9gWRj4fnjrg.png" /></figure><p>There is a corpus of high frequency words (such as also, to, the) which we need to filter out before processing. This corpus contains of <strong>stopwords</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ZPqvF37Ff8FMCzJhbhkA0Q.png" /></figure><blockquote>A <strong>wordlist</strong> is useful for solving word <strong>puzzles</strong>.</blockquote><blockquote><strong>How many words of four letters or more can you make from these (j,a,n,m,d,s,b,p,i)? Each word must contain p.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*KRHj0kE7t8FaN9S2RdUYVA.png" /></figure><p>A <strong>wordlist corpus</strong> also includes Names corpus, containing 8000 first name categorized by gender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*GuwwMSXmcJxagfMr-GFvoQ.png" /></figure><p>Try to find <strong>CFD</strong> of names corpus, where table and plot depicts the condition in which focus is on the first letter of the <strong>names</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*jofSPyWjPrrJTEA0u2JYsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*23g0aijh9p9d1dyrxRzyyA.png" /></figure><p><strong>2.2. Carnegie Mellon</strong> <strong>University (CMU) Pronouncing Dictionary:</strong></p><p>A richer kind of lexical resource is a <strong>table or spreadsheet</strong>. NLTK includes the CMU pronouncing dictionary for U.S English. Earlier it contained 127012 words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*1hSTnddW2htmuJHaTLRUNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*U45-t27WS7Rzdmd5O7RHOQ.png" /></figure><p>Observe that<strong> tunison</strong> has two <strong>pronunciations</strong>: one-syllable ‘T’, ‘AH1’, ’N’, ‘IH0’, ‘S’, ‘AH0’, ’N’, and the two-syllable ‘T’, ‘UW1’, ’N’, ‘IH0’, ‘S’, ‘AH0’, ‘N’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*RlHpBnyVYAGzaPgu1Z1SKw.png" /></figure><p>The program just shows the scans of <strong>lexicon</strong> looking for <strong>dict_entries</strong> whose pronunciation consists of five <strong>phones (phonetic codes of distinct labels)</strong>.</p><p>The phones contain digits to represent <strong>primary stress</strong> as <strong>1</strong>, <strong>secondary stress</strong> as <strong>2</strong>, and <strong>no stress</strong> as <strong>0</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*aQsCAwZZjDgMBsHUWqFM3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*50oUVGIBcfC5zo65CCpwhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zXOn9B-THl3iI5IyRuo9YA.png" /></figure><p><strong>2.3. Comparative Wordlists:</strong><br>Comparative wordlist is another example of a <strong>tabular lexicon</strong>. NLTK includes lists of about 200 common words in several languages or we called it as <strong>Swadesh wordlists</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*gS98HBzzKzRHuaL6LZNRbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*72R4y_tFv8T6b6xf7OFh6g.png" /></figure><p>We can <strong>convert</strong> languages into a simple dictionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*bjZmi0oQwpamKXR10e_2KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*0OAsGs-0pvAkqF5vPsT6IA.png" /></figure><p>We can add other source languages to <strong>translator</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*UlTzAhmms_yWR3TA9sU5Fg.png" /></figure><p>Here we can compare words in various <strong>languages</strong> in particular sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*HT7bvUYK_t6M2wMZyNEJNA.png" /></figure><p><strong>2.4. Toolbox Lexicons:</strong><br>A toolbox file consists of a collection of entries, where each entry is made up of one or more fields. Most fields are repeatable or optional, which means this <strong><em>lexical resources cannot be treated as a table or spreadsheet</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Vo1ttRCQ_O1d-gJ4kHgnwQ.png" /></figure><p>The <strong>Rotokas</strong> language is spoken on the island of <strong>Bouganville, Papua New Guinea</strong>.</p><h3><strong>3. WordNet:</strong></h3><p>NLTK includes the English <strong>WordNet</strong>, with 155,287 words and 117,659 synonym sets. WordNet is a semantically oriented dictionary of English, similar to a traditional <strong>thesaurus</strong> but with richer structure.</p><p><strong>3.1. Sense and Synonyms: </strong><br>We replace a word cloth in sentence (A.) with fabric and material to get (B.) and (C.) respectively. The meaning of the sentence remains pretty much same.</p><p>A. The cloth of a dress is soft and adorable <br>B. The fabric of a dress is soft and adorable<br>C. The material of a dress is soft and adorable</p><p>We can explore these words using <strong>WordNet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*he3nSm0TOK4FNMF1yYkGQw.png" /></figure><p>The entity fabric.n.01 and framework.n.02 are called a <strong>synset</strong> i.e. <strong>synonym set</strong>, a collection of <strong>synonymous words </strong>or<strong> lemmas</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*0C7ijdbQwwRx216eEgwoNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*lBsP5urgWqgIwDKl9Yq9ZA.png" /></figure><p><strong>WordNet</strong> navigates the lexical relations between the synset such as <em>hyponyms, hypernyms, meronyms, holonyms, entails and antonyms.</em><br><strong>Hyponyms</strong> give abstract concepts of the word that are more specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pq-kIxeE5gOB0mwhYitVug.png" /></figure><p>Some words have multiple paths, because they can be classified in more than one way. <strong>Hypernyms</strong> and <strong>hyponyms</strong> are called lexical relations because they relate one synset to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*4_vwUXc_G-lgxckMtKolGA.png" /></figure><p>Another way to navigate the <strong>WordNet</strong> network is from items to their components i.e. <strong>meronyms</strong> and to the things they are contained in i.e. <strong>holonyms</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*B8SeRorJTUsosydzEl4Epw.png" /></figure><p>There are also relationships between <strong>verbs</strong>. For example, the act of writing involves the act of spelling, so writing <strong>entails</strong> spellings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*-TJm1iaqk8PpUAxu0R7YuQ.png" /></figure><p>Some lexical relationships hold between lemmas e.g. <strong>antonyms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*MI_eeRqVm_0eu8Z8YaF9og.png" /></figure><h3><strong>4. Semantic Similarity:</strong></h3><p>Semantic Similarity, or Semantic Textual Similarity, is a task in the area of <strong>NLP</strong> that scores the relationship between texts or documents using a defined metric.<br>In the following example panther is very specific, whereas feline is more general and physical_entity is completely general.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aQ8PfcPLPxIUF0uMQDW6XQ.png" /></figure><p>We can quantify this concept of generality by looking up the depth of each <strong>synset</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*zbbbli29V_wH9q9245mxpg.png" /></figure><p>Similarity measures have been defined over the collection of WordNet <strong>synsets</strong> that incorporate this insight. <strong>path_similiarty</strong> assigns score in the range 0–1 based on the shortest path that connects the concepts in the <strong>hypernym</strong> hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*soR7g5RQwJDOZI4u9p0MbQ.png" /></figure><p><strong>References: 1. S</strong>teven bird, <strong>E</strong>wan klein, and <strong>E</strong>dward loper; <strong>N</strong>atural <strong>L</strong>anguage <strong>P</strong>rocessing with<strong> P</strong>ython</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4749e2ab0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: NLP- “Language Processing with Python”]]></title>
            <link>https://medium.com/@deepak.engg.phd/part-1-nlp-language-processing-with-python-d151b84adb57?source=rss-90d344ef909f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d151b84adb57</guid>
            <dc:creator><![CDATA[Dr. Deepak Kumar Singh]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 05:40:10 GMT</pubDate>
            <atom:updated>2021-07-22T05:40:10.927Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“The voice that navigated was definitely that of a machine, and yet you could tell that the machine was a woman, which hurt my mind a little. How can machines have genders? The machine also had an American accent. How can machines have nationalities? This can’t be a good idea, making machines talk like real people, can it? Giving machines humanoid identities?”<br>― <strong>Matthew Quick, </strong><a href="https://www.goodreads.com/work/quotes/25337922"><strong>The Good Luck of Right Now</strong></a></blockquote><p>Natural Language Processing (NLP) is a branch of <strong>artificial intelligence</strong> that helps computers understand, interpret and manipulate human language. NLP draws from many disciplines, including computer science and computational linguistics, in its pursuit to fill the gap between human communication and computer understanding.</p><p><strong>Why is NLP important?</strong></p><p><strong><em>Large volumes of textual data</em></strong></p><p>NLP helps computers communicate with humans in their own language and scales other language-related tasks. For example, NLP makes it possible for computers to read text, hear speech, interpret it, measure sentiment and determine which parts are important.</p><p><strong><em>Structuring a highly unstructured data source</em></strong></p><p>Human language is astoundingly complex and diverse. We express ourselves in infinite ways, both verbally and in writing. There are not only hundreds of languages and dialects, but within each language there is a unique set of grammar and syntax rules, terms and slang. When we write, we often misspell or abbreviate words, or omit punctuation. When we speak, we have regional accents, and we mumble, stutter and borrow terms from other languages.</p><p><strong>How does NLP work?</strong></p><p>These underlying tasks are often used in higher-level NLP capabilities, such as:</p><p>· <strong>Content categorization</strong> — A linguistic-based document summary, including search and indexing, content alerts and duplication detection.</p><p>· <strong>Topic discovery and modelling — </strong>Accurately captures the meaning and themes in text collections, and apply advanced analytics to text, like optimization and forecasting.</p><p>· <strong>Contextual extraction — </strong>Automatically pulls structured information from text-based sources.</p><p>· <strong>Sentiment analysis — </strong>Identifying the mood or subjective opinions within large amount of text, including average sentiment and opinion mining.</p><p>· <strong>Speech-to-text and text-to-speech conversion — </strong>Transforming voice commands into written text, and vice versa.</p><p>· <strong>Document summarization — </strong>Automatically generating synopses of large bodies of text.</p><p>· <strong>Machine translation — </strong>Automatic translation of text or speech from one language to another.</p><h3>Getting started with Natural Language Toolkit (NLTK)</h3><p><strong>NLTK</strong> is a leading platform for building Python programs to work with human language data.</p><p>First you have to install <strong>nltk</strong>, for this use following command</p><blockquote><strong>pip install nltk</strong></blockquote><p>For anaconda user, it is already installed so you don’t need to bother otherwise try the following command mentioned below</p><blockquote><strong>conda install nltk</strong></blockquote><p>once you have done with installation part, import nltk library in Python interpreter and download the required data for book (in our case)</p><p><strong>Note: </strong>Here we will treat text as raw data for the program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*cJ3LYs_TQUGoDJ8rNgvSzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*pD8n8hWGQVUSINz4r8pgdw.png" /></figure><p>One the data is downloaded to your machine, use the following command, it will load all items from <strong>NLTK’s book module</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*F5RjW3A_gUDEc3R9f0QetQ.png" /></figure><p>We want to find out about these <strong>texts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*8K31AX4dTNKBDsmifzy4vg.png" /></figure><p><strong>Searching Text</strong></p><p>There are various ways to examine the <strong>content of a text</strong>. A concordance view shows every occurrence of a given word, together with some context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*jYguxx2Tuu7MHBOaqBdb2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*PeL6YuO6qAYOhW29Mu1xhQ.png" /></figure><p>Distributional similarity: find other words which appear in the same contexts as the specified word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*dBUXf8fhbQAmPZdG103-Rw.png" /></figure><p>In <strong>common contexts</strong>, command find context where all the specified words can appear; and return a <strong>frequency distribution</strong> mapping each context to the number of times the context was used. Whereas, <strong>dispersion plot</strong> is a plot showing the distribution of the words through the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*RCgYDEZZFnFGT71lIg2eAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*8PsyqAIAjPdFtQX_TrfwxA.png" /></figure><p>Let’s try to generate some random text in various styles. Once text is generated it will appear same for number of times you would run this command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mC-im3P5MiBrTs6gffo70w.png" /></figure><p><strong>Counting Vocabulary</strong></p><p>In this section, we will play with different texts of the book module which are differing in the <strong>vocabulary</strong> they use. After this you have a new sense of the richness and diversity of language.</p><p>The term <strong>len</strong> provides the length of something, which we will apply here to the book of Chat corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*uxIr4UZLs99U8xYCRsXYyg.png" /></figure><p>So Chat corpus has 45010 words and punctuation symbols, or <strong>“token”. </strong>A token is the technical name for a <strong>sequence of characters</strong>- such as beautiful, her, or +.</p><p>With <strong>sorted</strong> command, text is sorted in the list of vocabulary items, start with punctuation symbols and thereafter with A and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*vfhQUkxkFWBHj-F9Wc9PPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*3Atx6aaMeTEUEH2uykXJ0g.png" /></figure><p>This shows that each word is used around <strong>7 times</strong> on average</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*zwYOS8jY0krUGy9BmmQoOg.png" /></figure><p>The <strong>block of code</strong> that does a task (like calculating lexical diversity or percentage in our case) is called <strong>function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*0b5kDbFoPiKygRzZ4eDeMg.png" /></figure><p><strong>A Closer Look at Python: Texts as Lists of Words</strong></p><p><strong>Lists</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*riMVnIX2jf5NK28tAjEl-g.png" /></figure><p><strong>Indexing Lists</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Jel327H4o96yWnOR1wVkUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*kILTGRUZrWkTvDJvgN7EfQ.png" /></figure><p>Now, use an<strong> index</strong> that is too large, we get an error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*qiOAns-Qoep_Fdnyq1xByg.png" /></figure><p>A closer look at <strong>slicing</strong>, the slice 3:7 includes sentence elements at indexes 3, 4, 5, 6 and 7</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*T7iieKZE5kEztzLKZyLz6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*O7YYZJoyaqW_w7g2C6Uo4g.png" /></figure><p>We can modify the element of a list by assigning to one of its <strong>index values.</strong> We can replace the entire slice with new material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*C7Lb5xb5ymzQEhwAAryq-w.png" /></figure><p>The consequence of this last change is that the list has only four elements.</p><p><strong>Variable</strong></p><p><strong>Variable </strong>can be equal to expression. The name of variable can be anything you like e.g. sentence, Another_SentencE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zrf-mwFCRJvVClv7AxfBcw.png" /></figure><p>Remember that capitalized words appear before lowercase words in sorted list.</p><p><strong>Strings</strong></p><p>We used to access the elements of a listed work with individual words, or strings. We can assign a<strong> string </strong>to a variable, index a string, slice a string, or perform multiplication and addition with strings and we can join the words of a list to make a string and split the string into a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*3ZGZy-ee_V_BARtvjm2c-A.png" /></figure><p><strong>Computing with language: Statistics</strong></p><p>In nltk, <strong>FreqDist</strong> provides you with the raw counts (i.e. frequencies of words) in the text. It is a <strong>‘distribution’ </strong>since it tells us how the total number of word tokens in the text are distributed across the vocabulary items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*nsnHMDcz3mODYwatYUuH9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*oImFf6bkk5I2fa_pYp5KRw.png" /></figure><p><strong>Hapaxes</strong></p><p><strong>Hapaxes</strong> are the words occur once only. We can see that there are 3408 words out of 69213 in text9 which occur once only as shown below in the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5Sas6nWLjaoNZOmg5AjgGQ.png" /></figure><p><strong>Fine-Grained Selection of Words</strong></p><p>We would like to find the words from the vocabulary of the text which are more than let’s say 14 characters long.</p><p>Let’s call this property P, so that P (w) is true if and only if w is more than 14 characters long.</p><blockquote><strong>w for w in V if P(w)</strong></blockquote><p>This means <strong>“the set of all w such that w is an element of Vocab (the vocabulary) and w has property P.</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*JJZX0yA5xC4jt-j3Ev5xZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_io92Yf_-Qc-mEfAjDTFBA.png" /></figure><p>In this example,<strong> len(word)&gt;9</strong> ensures that the words are longer than nine words and <strong>Freq_Dist_1[word]</strong> ensures that these words occur more than ten times.</p><p><strong>Collocations and Bigrams</strong></p><p>A collocation is a sequence of words that occur together unusually often. Thus tube light is a <strong>collocation</strong>. To get a handle on collocations, we start off by extracting from a text a list of word pairs, also known as <strong>bigrams</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*RdipR-zqGvkahXomEH-XYA.png" /></figure><p><strong>Counting other things</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*SM79GHpdqa8kp43MlyGuwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*vxHmJfe2h1aPfhMKjdeFzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*AOjR4yGQT8NbDmARc8FzqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9PmU6ZiBVt68nmCVCyqECg.png" /></figure><p><strong>Making Decisions and Taking Control</strong></p><p><strong>Conditional</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*meKYYfSq0UYhXB1j_98IAg.png" /></figure><p><strong>Comparison operator</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*azRuc4GgI0-8epVJCdS4mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*KG2SjSE0OdM4MGzKId6_JQ.png" /></figure><p><strong>Nested Code Blocks</strong></p><p>Mostly programming languages execute a block of code when a <strong>conditional</strong> expression, or if statement, is satisfied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*M52pN7lyjjcKJHfADferMg.png" /></figure><p><strong>Looping with Conditions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Vg7JbvR3S_RGIKrMpHTxqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*MDyo_Ncv0Ip-WDt05k9dcw.png" /></figure><p><strong>References: 1. Steven bird, Ewan klein, and Edward loper; Natural Language Processing with Python</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d151b84adb57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>