<?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 Pratyaksh Bhalla on Medium]]></title>
        <description><![CDATA[Stories by Pratyaksh Bhalla on Medium]]></description>
        <link>https://medium.com/@pb642001?source=rss-ab19d634dd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7s-Hb0zSrL1OoNxyFStI_g.jpeg</url>
            <title>Stories by Pratyaksh Bhalla on Medium</title>
            <link>https://medium.com/@pb642001?source=rss-ab19d634dd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:01:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pb642001/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[Mlxtend]]></title>
            <link>https://medium.com/data-science-community-srm/mlxtend-af073ebd0c51?source=rss-ab19d634dd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/af073ebd0c51</guid>
            <category><![CDATA[data-mapping]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Pratyaksh Bhalla]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 00:23:08 GMT</pubDate>
            <atom:updated>2020-03-23T00:23:08.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mlxtend — Plotting Made Easier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cn9SKGTg26J6dK3V" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction:</strong></h3><p>Every little bit and piece of Exploratory Analysis, Every step, and Every code written towards the modeling of a machine learning algorithm is completely based on the plots, graphs, and visualizations of the data set and features. Mlxtend makes that not only possible but extremely easy. Plots like category scatter plots, decision region plots, cumulative distribution functions and other complicated data visualizations are nothing more than features of the library that with few parameter definitions perform those complicated graphs in a few lines of code.</p><blockquote><em>For the complete documentation of the Mlxtend.plotting library, </em><a href="http://rasbt.github.io/mlxtend/api_subpackages/mlxtend.plotting/#ecdf"><em>click here</em></a></blockquote><p>We will be going through the following plots in this article but the mlxtend library has its grasps beyond this article and the plots stated here we would encourage you to go ahead and take a look in those plots as well. This is an extremely underused library but it is extremely helpful. We promise!!</p><p><strong>Lets Begin:</strong></p><h3>category_scatter:</h3><p>This is a scatter plot with category influence, it plots the various data points with their respective categories.</p><pre>import pandas as pd<br>from io import StringIO</pre><pre>csvfile = &quot;&quot;&quot;label,x,y<br>class1,10.0,8.04<br>class1,10.5,7.30<br>class2,8.3,5.5<br>class2,8.1,5.9<br>class3,3.5,3.5<br>class3,3.8,5.1<br>class1, 10.0, 5.5<br>class 2, 10, 6.3<br>class1, 7.9, 5.2<br>class3, 1.2, 5.9<br>class3, 10.0,0.3<br>class1, 7.2, 0.4<br>class2,5.0, 0.2<br>class1, 5.0, 7.0<br>class2, 10, 0.9<br>class3, 10, 8.9<br>class2, 5.3, 1.9<br>class1, 2.0, 9.8<br>class3, 3.0, 4.2<br>class1,12.0,9.04<br>class1,4.5,6.30<br>class2,6.3,3.5<br>class2,7.1,4.9<br>class3,8.5,2.5<br>class3,2.8,4.1<br>class1, 9.0, 4.5<br>class 2, 9.1, 9.3<br>class1, 8.2, 3.2<br>class3, 10.2, 1.9&quot;&quot;&quot;</pre><pre>df = pd.read_csv(StringIO(csvfile))<br>df</pre><p>This is the making of the dataset and we will be filling in the parameters in the category_scatter() function</p><p>parameters:</p><ul><li>x : str or int</li></ul><p><em>DataFrame column name of the x-axis values or integer for the variables</em></p><ul><li>y : str</li></ul><p><em>DataFrame column name of the y-axis values or integer for the variables</em></p><ul><li>data : Pandas DataFrame object</li><li>markers : str</li></ul><p><em>Markers that are cycled through the label category.</em></p><ul><li>colors : tuple</li></ul><p><em>Colors that are cycled through the label category.</em></p><ul><li>alpha : float (default: 0.7)</li></ul><p><em>Parameter to control the transparency.</em></p><ul><li>markersize : float (default` : 20.0)</li></ul><p><em>Parameter to control the marker size.</em></p><ul><li>legend_loc : str (default: &#39;best&#39;)</li></ul><p><em>Location of the plot legend {best, upper left, upper right, lower left, lower right} No legend if legend_loc=False</em></p><p>AND NOW COMES THE CODE:</p><pre><strong>from</strong> mlxtend.plotting <strong>import</strong> category_scatter  </pre><pre>fig = category_scatter(x=&#39;x&#39;, y=&#39;y&#39;, label_col=&#39;label&#39;,                         data=df, legend_loc=&#39;upper left&#39;)</pre><p>This simple line of code can perform the category scatter plot for the above given .csv dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*wLDanp5SkV1wYpZcZQlX3Q.png" /><figcaption>category scatter plot.</figcaption></figure><h3>checkerboard_plot:</h3><p>Creating the dataset for the checkerboard plot:</p><p>A checkerboard plot is nothing but a 2-d representation of the matrix of n x m dimensions.</p><pre>from mlxtend.plotting import checkerboard_plot<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre>ary = np.random.random((5, 4))</pre><p>Looking into the parameters:</p><ul><li>ary : array-like, shape = [n, m]</li></ul><p><em>A 2D array.</em></p><ul><li>cell_colors : tuple or list (default: (&#39;white&#39;, &#39;black&#39;))</li></ul><p><em>Tuple or list containing the two colors of the checkerboard pattern.</em></p><ul><li>font_colors : tuple or list (default: (&#39;black&#39;, &#39;white&#39;))</li></ul><p><em>Font colors corresponding to the cell colors.</em></p><ul><li>figsize : tuple (default: (2.5, 2.5))</li></ul><p><em>Height and width of the figure</em></p><ul><li>fmt : str (default: &#39;%.1f&#39;)</li></ul><p><em>Python string formatter for cell values. The default ‘%.1f’ results in floats with 1 digit after the decimal point. Use ‘%d’ to show numbers as integers.</em></p><ul><li>row_labels : list (default: None)</li></ul><p><em>List of the row labels. Uses the array row indices 0 to n by default.</em></p><ul><li>col_labels : list (default: None)</li></ul><p><em>List of the column labels. Uses the array column indices 0 to m by default.</em></p><ul><li>fontsize : int (default: None)</li></ul><p><em>Specifies the font size of the checkerboard table. Uses matplotlib’s default if None.</em></p><p>If we apply some of these parameters to our checkerboard_plot() function we can beautify the visualization :</p><p>plotting the checkerboard plot:</p><pre>checkerboard_plot(ary, <br>               col_labels=[&#39;category %d&#39; % i for i in range(1, 6)],<br>               row_labels=[&#39;sample %d&#39; % i for i in range(1, 6)],<br>               cell_colors=[&#39;red&#39;, &#39;black&#39;],<br>               font_colors=[&#39;black&#39;, &#39;white&#39;],<br>               figsize=(7.5, 5),<br>               fontsize = 200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*V59E9W0JNJTSxDMmyaZSvg.png" /></figure><h3>heatmap:</h3><p>For this particular plot we will be using the data set from <a href="https://raw.githubusercontent.com/rasbt/python-machine-learning-book-2nd-edition/master/code/ch10/housing.data.txt"><em>here</em></a>.</p><p>The heatmap is a graphical representation of the data distribution and density of data throughout the matrix</p><p>Here is the data production</p><pre>import numpy as np<br>import pandas as pd</pre><pre>df = pd.read_csv(&#39;<a href="https://raw.githubusercontent.com/rasbt/&#39;">https://raw.githubusercontent.com/rasbt/&#39;</a><br>                 &#39;python-machine-learning-book-2nd-edition&#39;<br>                 &#39;/master/code/ch10/housing.data.txt&#39;,<br>                 header=None,<br>                 sep=&#39;\s+&#39;)</pre><pre>df.columns = [&#39;sample %d&#39; % i for i in range(1, 15)]<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*CCUuHHlsP5jCpeKu1qfWXg.png" /><figcaption>dataset</figcaption></figure><p>heatmap parameters:</p><ul><li>conf_mat : array-like, shape = [n_rows, n_columns]. Basically, a <em>2D array.</em></li><li>hide_spines : bool (default: False)</li></ul><p><em>Hides axis spines if True.</em></p><ul><li>hide_ticks : bool (default: False)</li></ul><p><em>Hides axis ticks if True</em></p><ul><li>figsize : tuple (default: (2.5, 2.5))</li></ul><p><em>Height and width of the figure</em></p><ul><li>cmap : matplotlib colormap (default: None)</li></ul><p><em>Provides predefined color sequences to the map</em></p><ul><li>colorbar : bool (default: True)</li></ul><p><em>Shows a colorbar if True</em></p><ul><li>row_names : array-like, shape = [n_rows] (default: None)</li></ul><p><em>List of row names to be used as y-axis tick labels.</em></p><ul><li>column_names : array-like, shape = [n_columns] (default: None)</li></ul><p><em>List of column names to be used as x-axis tick labels.</em></p><ul><li>column_name_rotation : int (default: 45)</li></ul><p><em>Number of degrees for rotating column x-tick labels.</em></p><ul><li>cell_fmt : string (default: &#39;.2f&#39;)</li></ul><p><em>Format specification for cell values.</em></p><ul><li>cell_font_size : int (default: None)</li></ul><p><em>Font size for cell values</em></p><p>The code for the display of the heat map:</p><pre>from mlxtend.plotting import heatmap<br>import matplotlib.pyplot as plt<br>cols = [&#39;sample 1&#39;, &#39;sample 5&#39;, &#39;sample 9&#39;, &#39;sample 12&#39;, &#39;sample 14&#39;]<br>cm = np.corrcoef(df[cols].values.T)<br>heatmap(cm, <br>        column_names=cols, <br>        row_names=cols,<br>        cmap = &#39;magma&#39;,<br>        figsize =(7.5, 7.5),<br>        cell_font_size = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bhsQg_UuxNKpsu_0_PR5Kg.png" /><figcaption>heatmap</figcaption></figure><h3>plot_confusion_matrix:</h3><p>As the name suggests this method of the library plots the confusion matrix it is extremely straight forward</p><p>code for the given dataset:</p><pre>import numpy as np<br>cm1 = np.array([[1, 4, 5], [4, 7, 9], [2, 9, 8]])</pre><p>PARAMETERS:</p><ul><li>conf_mat : array-like, shape = [n_classes, n_classes]</li></ul><p><em>Confusion matrix input</em></p><ul><li>hide_spines : bool (default: False)</li></ul><p><em>Hides axis spines if True.</em></p><ul><li>hide_ticks : bool (default: False)</li></ul><p><em>Hides axis ticks if True</em></p><ul><li>figsize : tuple (default: (2.5, 2.5))</li></ul><p><em>Height and width of the figure</em></p><ul><li>cmap : matplotlib colormap (default: None)</li></ul><p><em>color sequence</em></p><ul><li>colorbar : bool (default: False)</li></ul><p><em>Shows a color bar if True</em></p><ul><li>show_absolute : bool (default: True)</li></ul><p><em>Shows absolute confusion matrix coefficients if True. At least one of </em><em>show_absolute or </em><em>show_normed must be True.</em></p><ul><li>show_normed : bool (default: False)</li></ul><p><em>Shows normed confusion matrix coefficients if True. The normed confusion matrix coefficients give the proportion of training examples per class that are assigned the correct label. At least one of </em><em>show_absolute or </em><em>show_normed must be True.</em></p><ul><li>class_names : array-like, shape = [n_classes] (default: None)</li></ul><p><em>List of class names. If not </em><em>None, ticks will be set to these values. </em><strong><em>Returns</em></strong></p><p>Code for the confusion matrix plot:</p><pre>from mlxtend.plotting import plot_confusion_matrix</pre><pre>plot_confusion_matrix(cm1,cmap = &#39;winter_r&#39;,figsize = (7.5, 7.5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*YI5zY2EPZNhIYFujJpjUQw.png" /><figcaption>confusion matrix</figcaption></figure><h3>plot_decision_regions:</h3><p>This is the most important and heroic of the methods in fact the other methods are also available in other libraries but this particular method reduces a 14 lines code in 2 lines</p><p>We will be using the iris dataset for this plot thsu the code for the dataset is pretty straight forward:</p><pre>from sklearn import datasets<br># Loading some example data<br>iris = datasets.load_iris()<br>X = iris.data[:, [0, 2]]<br>y = iris.target</pre><p>This is a simple classification problem and hence is very straight forward to use a classifier; We will be using a logistic regression</p><pre>from sklearn.linear_model import LogisticRegression<br>classifier = LogisticRegression(random_state = 0)<br>classifier.fit(X, y)</pre><p>Unlike other plots I will be showing the code to plot the decision regions without the library first:</p><pre>from matplotlib.colors import ListedColormap<br>X_set, y_set = X, y<br>X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),<br>                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))<br>plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),<br>             alpha = 0.75, cmap = ListedColormap((&#39;black&#39;, &#39;green&#39;, &#39;blue&#39;)))<br>plt.xlim(X1.min(), X1.max())<br>plt.ylim(X2.min(), X2.max())<br>for i, j in enumerate(np.unique(y_set)):<br>    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],<br>                c = ListedColormap((&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;))(i), label = j)<br>plt.title(&#39;Logistic Regression&#39;)<br>plt.xlabel(&#39;X&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*y4RVHYlRodW5t-p6gXFYtA.png" /><figcaption>contour plot</figcaption></figure><p>The above code and plot is extremely tough to understand and comprehend as well thus Now we use the mlxtend library</p><pre>from mlxtend.plotting import plot_decision_regions<br>plot_decision_regions(X, y ,clf = classifier, zoom_factor= 10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*KwVYXKNa_sk29H5aEaBC3w.png" /><figcaption>plot_decision_regions</figcaption></figure><p>Isn’t it simpler, far more convenient and beautiful. So now let&#39;s see the parameters:</p><ul><li>X : array-like, shape = [n_samples, n_features]</li></ul><p><em>Feature Matrix.</em></p><ul><li>y : array-like, shape = [n_samples]</li></ul><p><em>True class labels.</em></p><ul><li>clf : Classifier object.</li><li>feature_index : array-like (default: (0,) for 1D, (0, 1) otherwise)</li></ul><p><em>Feature indices to use for plotting. The first index in </em><em>feature_index will be on the x-axis, the second index will be on the y-axis.</em></p><ul><li>filler_feature_values : dict (default: None)</li></ul><p><em>Only needed for number features &gt; 2. Dictionary of feature index-value pairs for the features not being plotted.</em></p><ul><li>filler_feature_ranges : dict (default: None)</li></ul><p><em>Only needed for number features &gt;2. Dictionary of feature index-value pairs for the features not being plotted. Will use the ranges provided to select training samples for plotting.</em></p><ul><li>X_highlight : array-like, shape = [n_samples, n_features] (default: None)</li></ul><p><em>An array with data points that are used to highlight samples in </em><em>X.</em></p><ul><li>res : float or array-like, shape = (2,) (default: None)</li></ul><p><em>This parameter was used to define the grid width, but it has been deprecated in favor of determining the number of points given the figure DPI and size automatically for optimal results and computational efficiency. To increase the resolution, it’s is recommended to use to provide a </em><em>dpi argument via matplotlib, e.g.,plt.figure(dpi=600)`.</em></p><ul><li>zoom_factor : float (default: 1.0)</li></ul><p><em>Controls the scale of the x- and y-axis of the decision plot.</em></p><ul><li>hide_spines : bool (default: True)</li></ul><p><em>Hide axis spines if True.</em></p><ul><li>legend : int (default: 1)</li></ul><p><em>Integer to specify the legend location. No legend if legend is 0.</em></p><ul><li>markers : str</li></ul><p><em>Scatterplot markers.</em></p><ul><li>colors : str (default: &#39;red, blue, limegreen, gray, cyan&#39;)</li></ul><p><em>Comma-separated list of colors.</em></p><ul><li>scatter_kwargs : dict (default: None)</li></ul><p><em>Keyword arguments for underlying matplotlib scatter function.</em></p><ul><li>contourf_kwargs : dict (default: None)</li></ul><p><em>Keyword arguments for underlying matplotlib contourf function.</em></p><ul><li>scatter_highlight_kwargs : dict (default: None)</li></ul><p><em>Keyword arguments for underlying matplotlib scatter function.</em></p><h3>plot_learning_curves</h3><p>A very useful plot is to understand the learning standards and curves for a training/development and testing set of the dataframe. This method simplifies the operation as instead of making different instances plots and plotting them together we just use the method with the right parameters. let&#39;s see how it&#39;s done.</p><p>code for the dataset:</p><pre>from mlxtend.preprocessing import shuffle_arrays_unison<br>from mlxtend.data import iris_data<br>from sklearn.neighbors import KNeighborsClassifier<br>X, y = iris_data()<br>X, y = shuffle_arrays_unison(arrays=[X, y], random_seed=123)<br>X_train, X_test = X[:100], X[100:]<br>y_train, y_test = y[:100], y[100:]<br>clf = KNeighborsClassifier(n_neighbors=5)</pre><p>This is a simple classification problem and we are using the K nearest neighbors method to solve the classification problem</p><p>Parameters:</p><ul><li>X_train : array-like, shape = [n_samples, n_features]</li></ul><p><em>Feature matrix of the training dataset.</em></p><ul><li>y_train : array-like, shape = [n_samples]</li></ul><p><em>True class labels of the training dataset.</em></p><ul><li>X_test : array-like, shape = [n_samples, n_features]</li></ul><p><em>Feature matrix of the test dataset.</em></p><ul><li>y_test : array-like, shape = [n_samples]</li></ul><p><em>True class labels of the test dataset.</em></p><ul><li>clf : Classifier object.</li><li>train_marker : str (default: &#39;o&#39;)</li></ul><p><em>Marker for the training set line plot.</em></p><ul><li>test_marker : str (default: &#39;^&#39;)</li></ul><p><em>Marker for the test set line plot.</em></p><ul><li>suppress_plot=False : bool (default: False)</li></ul><p><em>Suppress matplotlib plots if True. Recommended for testing purposes.</em></p><ul><li>print_model : bool (default: True)</li></ul><p><em>Print model parameters in plot title if True.</em></p><ul><li>style : str (default: &#39;fivethirtyeight&#39;)</li></ul><p><em>Matplotlib style</em></p><ul><li>legend_loc : str (default: &#39;best&#39;)</li></ul><p><em>Where to place the plot legend: {‘best’, ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’}</em></p><p>Code for the plot:</p><pre>from mlxtend.plotting import plot_learning_curves<br>plot_learning_curves(X_train, y_train, X_test, y_test, clf)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*srShAyN0KNz5m3jQtHpd4Q.png" /></figure><p>It&#39;s pretty clear and extremely helpful plot, it shows the exact learning plot and testing curve, every analyst uses these plots extensively, and this library does what you need.</p><h3>plot_linear_regression:</h3><p>We came across multiple graphs for classification and other models but when it comes to linear regression we cannot overlook the visualization and neither does mlxtend. So lets code for the dataset</p><pre><strong>import</strong> numpy <strong>as</strong> np  <br>X = np.array([4, 8, 13, 26, 31, 10, 8, 30, 18, 12, 20, 5, 28, 18, 6, 31, 12,    12, 27, 11, 6, 14, 25, 7, 13,4, 15, 21, 15])  <br>y = np.array([14, 24, 22, 59, 66, 25, 18, 60, 39, 32, 53, 18, 55, 41, 28, 61, 35,    36, 52, 23, 19, 25, 73, 16, 32, 14, 31, 43, 34])  </pre><p>Parameters:</p><ul><li>X : numpy array, shape = [n_samples,]</li></ul><p><em>Samples.</em></p><ul><li>y : numpy array, shape (n_samples,)</li></ul><p><em>Targets</em></p><pre><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt <br><strong>from</strong> mlxtend.plotting <strong>import</strong> plot_linear_regression<br>intercept, slope, corr_coeff = plot_linear_regression(X, y) plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*ByOrO54g7efCNgPr.png" /></figure><p><strong>CONCLUSION:</strong></p><p>With this, we reach towards the end of the library and its capabilities. We really hope that this article and the underdog library mlxtend makes your analysis easier. Stay tuned for further helpful and exciting blogs in the field of Data Science. Till then, happy analysis!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af073ebd0c51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-community-srm/mlxtend-af073ebd0c51">Mlxtend</a> was originally published in <a href="https://medium.com/data-science-community-srm">DataX Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>