<?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 Patrick Fuller on Medium]]></title>
        <description><![CDATA[Stories by Patrick Fuller on Medium]]></description>
        <link>https://medium.com/@patrickbfuller?source=rss-16b01fdb4ccb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oBuomC9dlDrLcFc3fEutxw.jpeg</url>
            <title>Stories by Patrick Fuller on Medium</title>
            <link>https://medium.com/@patrickbfuller?source=rss-16b01fdb4ccb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:51:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrickbfuller/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Simple Flask App]]></title>
            <link>https://medium.com/@patrickbfuller/a-simple-flask-app-edeed75dbee2?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/edeed75dbee2</guid>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 04:03:11 GMT</pubDate>
            <atom:updated>2019-10-11T04:04:11.196Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fun With Flask, Brython, and Jinja</h4><h4>Context</h4><p>This blog follows code used to make a simple app using python, flask and html. The code can be found <a href="https://github.com/Patrickbfuller/simple_flask">here</a>, and my current versions are the following</p><pre>flask --version</pre><pre>Python 3.6.9</pre><pre>Flask 1.1.1</pre><pre>Werkzeug 0.15.5</pre><p>*This project was heavily inspired by Miles Erickson’s work <a href="https://github.com/mileserickson/flask-brython-example">here</a>.</p><h4>Static/, Templates/ And App.py</h4><p>The structure of the this app has three components. The <strong>Static/</strong> directory contains the Brython javascript files, brython.js and brython_stdlib.js. This implementation could run without the stdlib but if you wanted to do fancier stuff you’ll want it.</p><p>The <strong>Templates/</strong> directory houses the HTML, simply named index.html. This file directly contains the brython code. This is where the fun part comes in. You can write python code to tell the browser what to do. Below is a rough outline of how it is included into HTML structure.</p><pre>&lt;body onload=&quot;brython(1)&quot;&gt;<br>&lt;script type=&quot;text/python3&quot;&gt;<br>*write python here*<br>&lt;/script&gt;<br>...(divs and such)<br>&lt;/body&gt;</pre><p>Alternatively the python script can be stored in a separate file and read in as such, &lt;script type=”text/python” src=”test.py”&gt;&lt;/script&gt;.</p><p>The Brython being onloaded also allows the Jinja to be interpereted in the body outside of the &lt;script&gt;&lt;/script&gt; section. Jinja allows python like syntax directly in the HTML like the following:</p><pre>{% for element in var_from_server %}<br>    {% if element &gt; 2 %}<br>      &lt;div&gt;{{element}}&lt;/div&gt;<br>    {% endif %}<br>{% endfor %}</pre><p>In this case var_from_server is a test_dummy list of integers that gets sent to the client browser from the server in the app.py file.</p><p>The <strong>app.py</strong> file contains all python. It imports the Flask module and uses @ decorators to tell flask how to find its functionality.</p><h4>The the app.py code is run on the server while Brython code runs client-side in the browser.</h4><p>The app.py (on the server side) does a few things:</p><ol><li>Tells flask where to find the brython files and any other code that would be kept in the static directory.</li><li>Tells flask where to find the html file and maybe passes other data to the browser.</li><li>Receives (‘GET’) data from client browser.</li><li>Defines what the server does with the data.</li><li>Sends (‘POST’) data to the client browser.</li></ol><p>The brython in the HTML (on the client side):</p><ol><li>What action triggers the data getting sent to the server.</li><li>Where on the server to send the data.</li><li>What to do with the new data that gets send back from the server.</li></ol><p>To get it fired it up let flask know where to find the app.py file. In this case, export FLASK_APP=app.py. Then the command flask run will launch the app. It will tell you where to find your app (circled below) and if you follow it in your browser you find it. If you open the Javascript console monitor you will be able to see where the Brython gets run. It may come in handy for debugging and can be toggled with Command + Option + J (Mac) or Control + Shift + J (Windows, Linux, Chrome OS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0VHvYc5CgG7E9I1ZPsWTQ.png" /></figure><p>Below is a side by side visualization of these two Brython and app.py components. The print statements are included to demonstrate what runs where and how one might debug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdpweOCjhNmZJSYad5Cqeg.png" /><figcaption>Note the print statements to see which code is runs where.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRqCT9Ie-1HndXT9HSssPg.png" /></figure><p>To be clear adding 1 to a number is something that could be done just in browser. This is a simple example to illustrate what runs on the server and what runs in the browser, and hopefully inspire you to clone the repo and try it out and build your own creations!</p><p>To conclude, I do not claim to be an authority on these matters but to give some context here are a few explanations.</p><h4>Flask</h4><p>As per <a href="https://pymbook.readthedocs.io/en/latest/flask.html">https://pymbook.readthedocs.io/en/latest/flask.html</a>:</p><blockquote>“Flask is a web framework. This means flask provides you with tools, libraries and technologies that allow you to build a web application.”</blockquote><p>Official documentation here: <a href="http://flask.palletsprojects.com/en/1.1.x/">http://flask.palletsprojects.com/en/1.1.x/</a></p><h4>Werkzeug</h4><p>From the <a href="https://www.palletsprojects.com/p/werkzeug/">documentation</a>,</p><blockquote>“Werkzeug is a comprehensive <a href="https://wsgi.readthedocs.io/en/latest/">WSGI</a> web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries.</blockquote><blockquote><a href="https://palletsprojects.com/p/flask">Flask</a> wraps Werkzeug, using it to handle the details of WSGI while providing more structure and patterns for defining powerful applications.”</blockquote><h4>Brython</h4><p>In <a href="https://www.i-programmer.info/news/98-languages/5840-brython-python-in-the-browser.html">Brython — Python In The Browser</a>, Alex Armstrong writes</p><blockquote>“Brython is a Python to JavaScript compiler, but it does the whole job in the browser and so makes Python appear to be a client scripting language.”</blockquote><p>Documentation here: <a href="http://brython.info/">http://brython.info/</a></p><h4>Jinja</h4><p>From the <a href="https://jinja.palletsprojects.com/en/2.10.x/">documentation</a>,</p><blockquote>“Jinja is a modern and designer-friendly templating language for Python, modelled after Django’s templates.”</blockquote><p>I certainly find it friendly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edeed75dbee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine ‘Listening’ — Revisited]]></title>
            <link>https://medium.com/@patrickbfuller/machine-listening-revisited-845a26ed46d3?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/845a26ed46d3</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 05:58:43 GMT</pubDate>
            <atom:updated>2019-10-24T22:04:18.216Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine ‘Listening’ — Revisited</h3><h4>Adding Classes To Multi-class Classification of Music Genres</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcIIDZzdsGuGTApzrAwwjw.jpeg" /></figure><h4>CONTEXT</h4><p>This blog covers a continuation of an experiment in classifying music genres with machine learning. The earlier experiment covered machine learning for classifying 6 different genres. This blog covers machine learning for 10 genres.</p><p>The code for the 6 genre experiment can be found <a href="https://github.com/Patrickbfuller/classify_genre/blob/master/archive/genres.ipynb">here</a>.</p><p>The code for the 10 genre experiment can be found <a href="https://github.com/Patrickbfuller/classify_genre/blob/master/extra_genres.ipynb">here</a>.</p><h4>BUSINESS UNDERSTANDING</h4><p>A longer explanation can be found in an earlier blog covering the 6 genre experiment.</p><p>Previous blog <a href="https://medium.com/datadriveninvestor/machine-listening-a4312a129780">here</a>.</p><p>The potential for machine learning classification is to automatically sort new music, produced by an artist that is a departure from their typical repertoire. For example Folk artist produces an Electronic song on an album with Folk music.</p><p>Further potential exists in the ability to find songs exist on the border between two genres. A machine learning model that recognizes the portion of each genre present can find genre mixtures, e.g Jazzy Rock in new and old music.</p><h4>DATA UNDERSTANDING</h4><p><strong>Collection- </strong>The previous experiment covered 6 genres: Country, Hip Hop, Electronic, Jazz, Classical and Metal. As mentioned in the other blog, the code is designed to be repeatable with different genres if you would like to experiment. For this expansion, 4 genres are added: Bluegrass, Blues, Folk and Classic Rock.</p><p>As a summary, genres.collect_genres_features() implements the following libraries: BeautifulSoup(bs4), YoutubeDL and Librosa. Given a playlist on youtube, it examines each audio file and extracts sonic features.</p><h4>Visualization</h4><p>There are 20 features and now 10 classes. There are a great many different combinations that could be visualized. Instead a broad overview approach was taken. Bear in mind it is messy, but with the intent of finding a feature with similar distributions across all genres. Such a feature may have little predictive power and could potentially be dropped to prevent overfitting.</p><p>For example two features are shown. One demonstrates distinct distributions between genres that will likely give the feature strong predictive power, and one demonstrates distributions which are very similar for each genre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ZtQybOgLQWAODatzH6UrpA.png" /><figcaption>Many genres distributed uniquely.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*fFllR6RUmuEXwPiRcuOLgg.png" /><figcaption>Each genre is distributed similarly.</figcaption></figure><h4>DATA PREPARATION</h4><p>Train Test Split- A 64/16/20 train/test/validation split is performed. The split is performed stratified with respect to to the target class to preserve the a representative distribution of each class in each set. Stratify is a helpful parameter in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">sklearn.model_selection.train_test_split()</a>. The distributions are depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*bt6Kbe2XoJUYaijXKnYTLQ.png" /><figcaption>Rows in Train (Blue), Test (Green) and Validation (Red).</figcaption></figure><p>Two models that performed best in the previous experiment are tested, Support Vector Classifier and Gradient Boosted Trees. For Support Vector models the data is normalized and transformed using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PowerTransformer.html">sklearn.preprocessing.PowerTransformer()</a>. For the Gradient Boosted Tree model principal component analysis is applied.</p><p>Also experimented is a pipeline that drops two features whose distributions were very similar across genres (mfcc9 and mfcc11). The drop is pipelined using sklearn_pandas.DataFrameMapper()</p><pre>mapper = DataFrameMapper(<br> features=[<br> (col, None) for col in X_train.columns if col not in [‘mfcc9’, ‘mfcc11’]<br> ],<br> df_out=True</pre><p>It is then conveniently applied to the beginning of the already existing pipeline as follows:</p><pre>svc.steps.insert(0, (&#39;mapper&#39;, mapper))</pre><h4>MODELING</h4><p>The Support Vector Classifier again outperformed the Gradient Boosted Trees in log loss and Jaccard similarity. Dropping mfcc’s 9 &amp; 11 did not improve performance and the step was removed from the pipeline as follows:</p><pre>svc.steps.remove((&#39;mapper&#39;, mapper))</pre><p><strong>Grid Search- </strong>The following parameters are searched for the model with log loss as the score.</p><pre>params = {<br>    &#39;model__C&#39;: [8,9,10,11,12],<br>    &#39;model__gamma&#39;: [0.25, 2, &#39;auto&#39;, &#39;scale&#39;],<br>    &#39;model__tol&#39;: [0.01, 0.001, 0.0001],<br>    &#39;model__decision_function_shape&#39;: [&#39;ovo&#39;, &#39;ovr&#39;]<br>}</pre><p>The results are as follows:</p><pre>svc_grid.best_params_<br>&gt;&gt;&gt;<br>{&#39;model__C&#39;: 8,<br> &#39;model__decision_function_shape&#39;: &#39;ovr&#39;,<br> &#39;model__gamma&#39;: 0.25,<br> &#39;model__tol&#39;: 0.0001}</pre><h4>EVALUATION</h4><p>The final model performed as follows on the validation data:</p><ul><li>Log Loss: 0.476</li><li>Jaccard Score: 0.749 (<em>average</em>)<br> -Country: 0.656<br> -Jazz: 0.854<br> -Hip_Hop: 0.680<br> -Classical: 0.824<br> -Metal: 0.733<br> -Electronic: 0.673<br> -Bluegrass: 0.842<br> -Blues: 0.727<br> -Folk: 0.767<br> -Classic_Rock: 0.737</li><li>Accuracy: 0.854</li></ul><p>Below is a confusion matrix of the validation set. Also below are confusion matrices modified to calculate recall and precision for each genre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*RTU69XC8CtmwIZjRsvUfDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*xSrLEXwrY35SiLJI1lClaw.png" /><figcaption>The identity cells show the recall for each genre.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*UTG6TpjNq8psbWhpraTtAQ.png" /><figcaption>The identity cells show the precision for each genre.</figcaption></figure><h4>DEPLOYMENT</h4><p>A demonstration of this classifier can be found at <a href="http://www.whatsthatgenre.com/">http://www.whatsthatgenre.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=845a26ed46d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATA UNDERSTANDING— EDA Cont’d]]></title>
            <link>https://medium.com/@patrickbfuller/data-understanding-eda-contd-c9ddd3d8616d?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ddd3d8616d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[crisp-dm]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 05:33:01 GMT</pubDate>
            <atom:updated>2019-10-22T00:34:54.838Z</atom:updated>
            <content:encoded><![CDATA[<p>LOOK AT THE DATA!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*GoesnRUWNMK6OUx67fgyyQ.jpeg" /><figcaption>LOOK AT THE DATA</figcaption></figure><h4>CONTEXT</h4><p>I am writing this with as a continuation of a previous blog, <a href="https://medium.com/@patrickbfuller/data-understanding-eda-first-looks-5da1154c97ca">First Looks in EDA</a>. This blog takes a look at some visualization techniques when performing exploratory data analysis. a task performed in the second phase of CRISP-DM, <em>Data Understanding</em>. It follows python code run in a Jupyter Notebook and is written in the context of linear regression and preparing data for a machine learning model. It follows these practices mainly with pandas DataFrames.</p><h4>LINEAR REGRESSION</h4><p>Linear Regression is a method used for assessing mathematical relationships and making predictions on new data using a machine learning model. It has some fundamental assumptions that include:</p><ul><li>A linear relationship between predictors and target</li><li>Normally distributed data</li><li>Little to no Multi-collinearity</li><li>No Auto-correlation</li><li>Homoscedastic residuals</li></ul><p>When modeling data that is <em>not</em> <em>quite</em> normally distributed, transformations can be applied to create a version of the data that is more normally distributed to help the model process it. Ultimately those transformations are applied in a pipeline as part of DATA PREPARATION, a later phase of CRISP-DM, but it can be helpful to visualize the transformations before hand in EDA. We want to know which distributions look normal, which don’t and what transformations are helpful.</p><h4>LOOK AT THE DATA</h4><p>When modeling, there’s one column that will always be included, the target. I am a fan of Seaborn’s distplot method. Also good are Seaborn’s kde plot and good old fashioned matplotlib.pyplot.hist(). I have heard good things about plotly as well.</p><pre>import seaborn as sns<br>sns.distplot(df_viz[&#39;price&#39;], color=&#39;teal&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*TYC0CD545q4XeLv3cdI98Q.png" /><figcaption>Very skewed distribution of prices.</figcaption></figure><p>Well that is just not even close. We’re looking for an even bell curve. Maybe taking the square root or log of the price will help.</p><pre>sns.distplot(df_viz[&#39;price&#39;]**0.5, color=&#39;mediumblue&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*qvm9esMKZuZT9s4yQ0_k-Q.png" /><figcaption>Less skewed than original but still far from ideal.</figcaption></figure><pre>sns.distplot(np.log(df_viz[&#39;price&#39;]), color=&#39;green&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*zA2UocTfyJx_Ou25r2nNjQ.png" /><figcaption>Not perfect but greatly improved.</figcaption></figure><p>The log of the price seems to be distributed far more normally. It will make an appropriate transformation for feeding the model. Next up, looking at the rest of the columns that may offer predictive power. This is a somewhat ugly, broad sweep, but makes for an effective first look at the unseen data.</p><pre>df_viz.drop([&#39;id&#39;, &#39;price&#39;, &#39;log_price&#39;], axis=1).hist(<br>    figsize=(15,15),<br>    color=&#39;seagreen&#39;,<br>    bins=30<br>)<br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P13byiFhiCbyS0WjDKssxw.png" /><figcaption>A somewhat shotgun approach to looking at many columns.</figcaption></figure><p>Theres a lot of information there but here are a few main takeaways:</p><ul><li>There are no pretty bell curves. Gonna have to perform some transformations</li><li>Some are clearly not a numerical, but categorical feature and as such won’t need to be transformed.</li><li><strong>yr_renovated</strong> has 0’s. A LOT OF 0’s. This is non-null missing data.</li><li>There’s actually a category missing from this; <strong>date</strong>.</li></ul><p>We’ll make a decision regarding missing data, as well as which features we want to transform, but first we haven’t <em>seen</em> all the data. Pandas datetime will not work for a histogram from a pandas.DataFrame object(2D structure) e.g.</p><pre>df_viz[[&#39;date&#39;]]</pre><p>but will work if you pass it as a pandas.Series object e.g.</p><pre>df_viz[&#39;date&#39;] or df_viz.date</pre><p>Then you can simply use the pandas .hist() method for a quick and dirty look.</p><pre>df_viz.date.hist();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*rrMGSA2M2QSJvuScxMiMuA.png" /><figcaption>Blocky but gives you a rough sense.</figcaption></figure><p>A cleaner look at the distributions of sales dates can be achieved using a groupby statement.</p><pre>monthly_counts = df_viz.date.groupby(<br>    [df_viz.date.dt.year, df_viz.date.dt.month]<br>).count()<br>monthly_counts.plot(kind=&#39;bar&#39;,figsize=(12,5));<br>     # This line inspired by the helpful folks at <a href="https://stackoverflow.com/questions/27365467/can-pandas-plot-a-histogram-of-dates">https://stackoverflow.com/questions/27365467/can-pandas-plot-a-histogram-of-dates</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*Z5T9AH3OhTeXo_LRWLB6YA.png" /><figcaption>Preferable in almost every way.</figcaption></figure><p>Date is ultimately having a categorical effect on the price of a home, and therefore does not need to have a normal distribution but it is always good to look at your data. As a role model of mine says, with out looking at your data, you’re flying blind.</p><p>Next up the features that are numerical in nature need to be transformed. Two quick and effective transformations are log and power transformations. Power transformation is a little cryptic and harder to explain the effect of features, but can sometimes be more helpful than log in transforming distributions. After subsetting to just the numerical categories, the code below produces a nice side by side comparison of the benefits of log and power transformation.</p><pre>from sklearn.preprocessing import power_transform, scale<br>plt.figure(figsize=(18,35))<br>n = 1<br>i = len(df)<br>for col in numeric:<br>    s = df_viz[[col]].dropna() + 0.0001<br>    s1 = scale(np.log(s))<br>    s2 = power_transform(s, method=&#39;box-cox&#39;)<br>    plt.subplot(i,2,n)<br>    sns.distplot(s1, color=&#39;cornflowerblue&#39;, axlabel=&#39;log_&#39;+col)<br>    plt.subplot(i,2,n+1)<br>    sns.distplot(s2, color=&#39;mediumseagreen&#39;, axlabel=&#39;pwr_&#39;+col)<br>    n += 2<br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIVQi0zUJy-KYVxLyE0Yfg.png" /></figure><p>This further influences our decision of what to include as a numeric feature as opposed to maybe binning a feature (such as <strong>sqft_basement</strong>). As well as highlighting which transformation will be more successful for particular features, e.g. <strong>sqft_lot15 </strong>responds best to power transformation where as <strong>sqft_living15</strong> responds best to log transformation. With this smaller list of transformed features, next up is how they correlate with the target.</p><p>This can be examined non-visually with the below code to get a rough idea of what to expect.</p><pre>df_tfm.corr().log_price.sort_values(ascending<strong>=False</strong>)</pre><pre>&gt;&gt;&gt;</pre><pre>log_price            1.000000<br>grade                0.703720<br>log_sqft_living      0.674802<br>log_sqft_living15    0.607154<br>pwr_sqft_above       0.576573<br>log_bathrooms        0.520278<br>log_bedrooms         0.342850<br>pwr_sqft_lot         0.126461<br>pwr_sqft_lot15       0.113175<br>pwr_yr_built         0.104614<br>Name: log_price, dtype: float64</pre><p>But it’s much more helpful to have a full picture. Also nice is to have color play a roll. Using the values, visual pop can be added to the color of the features that are more correlated with the target with the code below.</p><pre>n = 1<br>plt.figure(figsize=(15,15))<br>for col in df_tfm.drop(&#39;log_price&#39;, axis=1):<br>    plt.subplot(3,3,n)<br>    n+=1<br>    corr = df_tfm.corr().log_price[col]<br>    color = np.array([0,0.8,0.5 ** corr]) * corr<br>    sns.scatterplot(<br>        x=df_tfm[col],<br>        y=df_tfm[&#39;log_price&#39;],<br>        color=color,<br>        alpha=0.2,<br>        label=f&#39;Corr: {round(corr,3)}&#39;<br>    )<br>    plt.legend(prop={&#39;size&#39;:14})<br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkYD6hTbc8kzqE_Q8p81ig.png" /><figcaption>Brighter colors correspond to higher correlation.</figcaption></figure><p>This visual ultimately gives the most clear picture of the interaction between our numerical feature candidates and the target.</p><p>As a last example on this blog, a look at the association between month and price can be examined using code like the following.</p><pre>df_monthly = df_viz.groupby(<br>    [df_viz.date.dt.year, df_viz.date.dt.month]<br>)<br>monthly_avgs = df_monthly.log_price.mean()<br>monthly_avgs</pre><pre>&gt;&gt;&gt;</pre><pre>date  date<br>2014  5       13.061631<br>      6       13.078965<br>      7       13.059795<br>      8       13.044535<br>      9       13.035465<br>      10      13.038953<br>      11      13.011753<br>      12      13.018059<br>2015  1       13.008518<br>      2       12.994354<br>      3       13.051455<br>      4       13.096912<br>      5       13.075735<br>Name: log_price, dtype: float64</pre><p>And the following for visualization:</p><pre>plt.figure(figsize=(15,8))<br>sns.scatterplot(<br>    x=&#39;date&#39;,<br>    y=&#39;log_price&#39;,<br>    data=df_viz,<br>    alpha=0.1,<br>    color=&#39;teal&#39;<br>)</pre><pre>sns.lineplot(<br>    x=pd.date_range(&#39;2014-05-15&#39;, &#39;2015-05-15&#39;, periods=13),<br>    y=monthly_avgs.values,<br>    color=&#39;white&#39;,<br>    marker=&#39;o&#39;,<br>    markerfacecolor=&#39;gold&#39;,<br>    markersize=12<br>    )</pre><pre>plt.title(label=&#39;Prices Over Time&#39;,fontdict={&#39;size&#39;:20})<br>plt.xlim(&#39;04-25-14&#39;,&#39;06-01-15&#39;)<br>plt.vlines(<br>    x=pd.date_range(&#39;2014-06&#39;, &#39;2015-05&#39;, periods=12),<br>    ymin=11,<br>    ymax=16,<br>    linestyles=&#39;dotted&#39;,<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*5R42FblcGj4sibvqg6YAqg.png" /><figcaption>The distribution and average price does not change much month to month.</figcaption></figure><h4>SOURCES</h4><ul><li><a href="https://www.statisticssolutions.com/assumptions-of-linear-regression/">https://www.statisticssolutions.com/assumptions-of-linear-regression/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ddd3d8616d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine ‘Listening’]]></title>
            <link>https://medium.datadriveninvestor.com/machine-listening-a4312a129780?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4312a129780</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 01:32:06 GMT</pubDate>
            <atom:updated>2019-09-25T09:06:28.499Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine Learning For Music Genre Classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*_y7Mrqpk_xgkb57uijPrQQ.jpeg" /></figure><h4>BUSINESS UNDERSTANDING</h4><p>Music is a part of most people’s lives, whether in the context of workouts, cocktails, night clubs, or TV and movies. But only certain types of music work in certain situations. I like to think of this as ‘Genre Fit’ or ‘Appropriateness’. Music isn’t just good or bad; It’s good or bad <em>for a situation</em>. The Game of Thrones intro is great, but it probably wouldn’t mix very well with a SitCom or a cocktail party. On a narrower spectrum, for one person’s wedding reception Country music might be great and Classical would be uncomfortable. For a different person’s wedding reception the opposite might be true. Luckily we often have Genre labels for music. What about new music? Likely artists will self report the genre. But what if a Folk artist produces a Jazz song? Or what we want to find the Folk songs that are also Jazz, but some of them are labeled as Folk and some of them are labeled as Jazz? Or for another genres example, what if we wanted to find new Country music that is no way Hip Hop? If we can predict the likelihood that a song falls into certain genres we can answer these questions.</p><h4>DATA UNDERSTANDING</h4><p><strong><em>Collection- </em></strong>For this experiment, I collected about 600 songs worth of data, with about 100 from 6 different genres. But I wanted the experiment to be quickly repeatable with different mixes and numbers of genres of music. So If you’d like to re-run this experiment with different genres, you can just replace the playlist urls with other playlists and genre labels. The repo can be found <a href="https://github.com/Patrickbfuller/classify_genre">here</a>.</p><p><a href="https://www.datadriveninvestor.com/2019/03/03/editors-pick-5-machine-learning-books/">DDI Editor&#39;s Pick: 5 Machine Learning Books That Turn You from Novice to Expert | Data Driven Investor</a></p><p>For each genre a playlist on youtube is selected, such as a ‘Top 100 country’, effectively pre-labeling my data. The urls to each song are collected using <strong>BeautifulSoup</strong>. Then for each song, the audio file is retrieved using the <strong>youtube_dl</strong> library. The audio file is then loaded as 1d <strong>numpy</strong> array, using the <strong>librosa </strong>audio library. If the song is longer than 4 minutes only the first 4 minutes are loaded. The song’s audio is then chopped into 10-second pieces for a more granular examination of the sounds present. Librosa is then used to extract features such as tempo, spectral centroid, spectral rolloff, zero crossing rate and mel frequency cepstral coefficients. These terms are very jargon-ey but in essence, they represent parts of the <em>timbre </em>of a sound. They are then averaged over their 10-second intervals to create 1 data point per feature. The features are then stored in a <strong>json </strong>with the genre label and one row for each 10-second chunk in the song. The audio file is then erased before moving on to the next song. The same process is repeated for each song of each genre.</p><p><strong><em>Exploratory Data Analysis</em>-</strong><em> </em>Not all 600 songs got loaded. These are the results of the collection.</p><pre>df.groupby(&#39;genre&#39;).song.count()</pre><pre>genre<br>classical     2320<br>country       2389<br>electronic    2371<br>hip_hop       2345<br>jazz          2397<br>metal         2399<br>Name: song, dtype: int64</pre><pre>df.groupby(&#39;genre&#39;).song.nunique()</pre><pre>genre<br>classical      97<br>country       100<br>electronic     99<br>hip_hop        98<br>jazz          100<br>metal         100<br>Name: song, dtype: int64</pre><p>There are way too many combinations of genres and features to display them all here but if you’d like to see them all you explore the <a href="https://github.com/Patrickbfuller/classify_genre/blob/master/genres.ipynb">notebook</a>. Below are a few combinations of genres and features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZoOysJ6lXnonyvwmhbVmQ.png" /><figcaption>Country and Hip Hop are rather similar.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS0_Wb0fnsPb4fd_goI0Mw.png" /><figcaption>Classical is more distinguishable from Hip Hop</figcaption></figure><h4>DATA PREPARATION</h4><p>For Logistic Regression and Support Vector Models the data needs to be scaled. The transformers tested are StandardScaler and PowerTransformer from <strong>Scikit Learn</strong>. PowerTransformer is nice in that it normalizes skewed distributions as well as scaling to the standard deviation and moving the mean to zero. It currently defaults to the Yeo-Johnson transform.</p><p>The principal component analysis is also tested and these preparations are applied to a pipeline object.</p><h4>MODELING</h4><p>The following models are tested:</p><ul><li>Logistic Regression</li><li>Support Vector Machine</li><li>Random Forest</li><li>Gradient Boosted Trees</li><li>Sequential Network (Deep Learning)</li></ul><p>The models were evaluated on log loss and Jaccard Similarity. Log loss is a measurement the penalizes wrong classifications based on how confidently the data point was mislabeled. In other words, it makes sure the model isn’t just getting by with lucking into narrowly decided classifications and is classifying with more confidence.</p><p>Jaccard similarity evaluates the overlap between the two regions. It is similar to accuracy in that it measures successes, but its denominator is true positives and false positives. So it will penalize a model that was really accurate at predicting jazz but was only accurate for jazz because it classified almost everything as jazz.</p><p>Ultimately, on the test set, the support vector model predicted with the lowest log loss(0.39) and best Jaccard similarity(0.77). Gradient boosted trees came in second with a slightly lower Jaccard similarity(0.73) but a much worse log loss(0.50). However support vectors do not scale well and with more data, other models may perform better, especially if sufficient data could be acquired to train a deep learning model.</p><h4>EVALUATION</h4><p>On the holdout set, the support vector performed nearly identically. Below are confusion matrices with total numbers, and with the percentage of true labels(accuracy per genre) respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*If3sWRT9e-5Og50plQpAvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*lt2EnA4iy-HvsnMbwgrv5A.png" /></figure><h4>DEPLOYMENT</h4><p>This model is not currently deployed, but the code is available if you would like to clone the repo and import the method, <em>genre.classify</em> from genre.py.</p><h4>FUTURE</h4><p>More experiments with more genres and different mixes could provide more insights as well as iterative improvements. Tuning deep learning could improve performance.</p><p>Experiments on classifying with a Convolutional Neural Network trained on spectrogram images are reported to perform very well and make a great next step.</p><p>Unsupervised clustering on the sonic features and/or spectrograms may provide interesting insights as to ‘How many distinct genres are there <em>really</em>?</p><p>A fun idea may be a model that predicts the probability of rap being ‘West Coast’, ‘East Coast’ or ‘South’.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4312a129780" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/machine-listening-a4312a129780">Machine ‘Listening’</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATA UNDERSTANDING — EDA First Looks]]></title>
            <link>https://medium.com/@patrickbfuller/data-understanding-eda-first-looks-5da1154c97ca?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5da1154c97ca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[crisp-dm]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 02:10:39 GMT</pubDate>
            <atom:updated>2019-09-13T02:10:39.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>DATA UNDERSTANDING — EDA First Looks</h3><h3>A Fundamental Phase of CRISP-DM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNtZJymRXj6ba1tssEV3Zg.jpeg" /><figcaption><a href="https://wallpaper-mania.com/background/space-wallpapers/stars-wallpaper-hd/">Space Wallpapers</a></figcaption></figure><h4>CONTEXT:</h4><p>This article takes a look at some tools for first looks into exploratory data analysis, a task performed in the second phase of CRISP-DM, <em>Data Understanding</em>. It follows python code run in a Jupyter Notebook. It is written in the context of linear regression and preparing data for a machine learning model. It follows these practices mainly with pandas DataFrames.</p><h4>CRISP-DM:</h4><p>It stands for Cross Industry Standard Process for Data Mining and to say that it is important is an understatement. It’s the set of golden rules. I like to think of it as a blend of best-practices for <em>science</em>, <em>business</em>, and <em>data</em>, and I confidently believe if you follow CRISP-DM closely and often and you will be happier for it. It has 6 fundamental phases.</p><ol><li>BUSINESS UNDERSTANDING</li><li>DATA UNDERSTANDING</li><li>DATA PREPARATION</li><li>MODELING</li><li>EVALUATION</li><li>DEPLOYMENT</li></ol><p>The 4th phase, <strong>Modeling</strong>, is the often the most exciting and magical part of the process, but in order for in order for the model to perform it needs to be fed data that is cleaned and prepared. That is handled in the 3rd phase, <strong>Data Preparation</strong>. We often need to make a pipeline that and will change some of the datatypes and perform a mathematic operation as a brief example. And we also need to get remove or repair missing data! But how do we know what parts of the data set need to be changed? PHASE TWO OF COURSE!</p><p>DATA UNDERSTANDING</p><p>This is where you get to know your data. The following principles are some go to checks but if you feel there is a component of Data Understanding that is absent please leave a comment on this article.</p><ul><li>Amount- Number of rows/columns</li><li>Data Types- Integers/Floats/Strings/Booleans/DateTime</li><li>Data Concept- Numerical(Continuous or Discrete)or Categorical value</li><li>Missing Data- Drop or Fill</li><li>Distribution- Range and Skew</li><li>Correlation- Target and Collinearity</li><li>Visualization- Generally Helpful Aid, Histograms and Scatterplots</li></ul><p>In pandas, my first cursory overlook includes the following methods:</p><ul><li><em>.head()</em></li><li><em>.info()</em></li><li>.isna().sum()</li><li><em>.describe()</em></li></ul><h4>df.head()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upVlXnN9sMwGsW3gwjTudw.png" /><figcaption>Just a crop of the first 4 of 21 columns.</figcaption></figure><p>This method gives a quick glimpse into the dataset. You can get a very quick intuition for what sort of values are present. It’s not the most information in one place, but it gives a nice context for the following concepts.</p><h4>df.info()</h4><pre>df.info()<br>&gt;&gt;&gt;</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 21597 entries, 0 to 21596<br>Data columns (total 21 columns):<br>id               21597 non-null int64<br>date             21597 non-null object<br>price            21597 non-null float64<br>bedrooms         21597 non-null int64<br>bathrooms        21597 non-null float64<br>sqft_living      21597 non-null int64<br>sqft_lot         21597 non-null int64<br>floors           21597 non-null float64<br>waterfront       19221 non-null float64<br>view             21534 non-null float64<br>condition        21597 non-null int64<br>grade            21597 non-null int64<br>sqft_above       21597 non-null int64<br>sqft_basement    21597 non-null object<br>yr_built         21597 non-null int64<br>yr_renovated     17755 non-null float64<br>zipcode          21597 non-null int64<br>lat              21597 non-null float64<br>long             21597 non-null float64<br>sqft_living15    21597 non-null int64<br>sqft_lot15       21597 non-null int64<br>dtypes: float64(8), int64(11), object(2)<br>memory usage: 3.5+ MB</pre><p>This method can seem a little tiresome and cluttered but it can offer some vital starting information. Things to take note of:</p><ul><li><strong>Total Number of Columns-</strong> 21. This info is in <em>.head()</em> but it can be helpful to see a cleaner vertical list of column names.</li><li><strong>Total Number of Entries-</strong> 21597. The <strong>waterfront</strong>, <strong>view</strong>, <strong>yr_renovated</strong> columns have less entries. This is a sign that there is missing data. Null/NaN values are present.</li><li><strong>DataTypes-</strong> There is a mix of integer, float and object(string) types present. It’s too early to know for sure but it seems likely that <strong>sqft_basement</strong> is a numerical concept and will need to be coerced to a int/float.</li><li>*Object types in conceptually numeric columns can be a sign of a non-numeric character/value being entered and a computer coercing the entire column to a string to be able to digest all the entries present.</li><li><strong>Date/Time Data-</strong> The <strong>date</strong> and <strong>yr_built</strong> and <strong>yr_renovated</strong> columns are likely a concept of time. It always depends on the business case and model use but there is a chance these columns will be the most helpful if coerced to a DateTime object.</li></ul><h4>.isna().sum()</h4><pre>df.isna().sum()<br>&gt;&gt;&gt;</pre><pre>id                  0<br>date                0<br>price               0<br>bedrooms            0<br>bathrooms           0<br>sqft_living         0<br>sqft_lot            0<br>floors              0<br>waterfront       2376<br>view               63<br>condition           0<br>grade               0<br>sqft_above          0<br>sqft_basement       0<br>yr_built            0<br>yr_renovated     3842<br>zipcode             0<br>lat                 0<br>long                0<br>sqft_living15       0<br>sqft_lot15          0<br>dtype: int64</pre><p>This one may be my favorite. Maybe it’s just saying ‘izz-naw’. This method returns the total number of missing rows in each column. Its not a great deal of new information that wasn’t in <em>.info()</em> but it’s really quick and easy to read. It can also be simply modified to deduce percent of missing data like the following:</p><pre>round(df.isna().sum() <strong>/</strong> len(df), 4) <strong>*</strong> 100<br>&gt;&gt;&gt;</pre><pre>id                0.00<br>date              0.00<br>price             0.00<br>bedrooms          0.00<br>bathrooms         0.00<br>sqft_living       0.00<br>sqft_lot          0.00<br>floors            0.00<br>waterfront       11.00<br>view              0.29<br>condition         0.00<br>grade             0.00<br>sqft_above        0.00<br>sqft_basement     0.00<br>yr_built          0.00<br>yr_renovated     17.79<br>zipcode           0.00<br>lat               0.00<br>long              0.00<br>sqft_living15     0.00<br>sqft_lot15        0.00<br>dtype: float64</pre><h4>NON-NULL MISSING DATA</h4><p>This does not necessarily catch all of the missing data in the dataset. Sometimes there is non-valid data entered as something like an empty string, (‘ ’), or an irrelevant number, (-999). So always be on the look out and never be surprised to find more missing data.</p><h4>.describe()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BY1ARdkkAP4_RvrYmSu2dg.png" /></figure><p>This method returns statistical information for the numeric columns. Be careful: if the column was a numeric concept but the datatype is a string then it will be omitted from this result.</p><p>Ultimately visualizing the distributions with histograms will provide a clearer glimpse of the data but this can be a great quick first look. For example, the minimum of the <strong>yr_renovated</strong> column is 0. Missing Data Alert🚨.</p><p>This is just a brief introduction into Data Understanding. Stay tuned for more snapshots of CRISP-DM.</p><p>References / Sources:</p><ul><li><a href="https://www.datasciencecentral.com/profiles/blogs/crisp-dm-a-standard-methodology-to-ensure-a-good-outcome">https://www.datasciencecentral.com/profiles/blogs/crisp-dm-a-standard-methodology-to-ensure-a-good-outcome</a></li><li><a href="https://wallpaper-mania.com/background/space-wallpapers/stars-wallpaper-hd/">https://wallpaper-mania.com/background/space-wallpapers/stars-wallpaper-hd/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da1154c97ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Catch Me If You GAN!]]></title>
            <link>https://medium.com/@patrickbfuller/catch-me-if-you-gan-7c7750a32bdd?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c7750a32bdd</guid>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-art]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 19:29:39 GMT</pubDate>
            <atom:updated>2019-06-11T19:29:39.129Z</atom:updated>
            <content:encoded><![CDATA[<h4>A BRIEF overview of Goodfellow et al. -On Generative Adversarial Networks</h4><p>I recently discovered an academic <a href="https://arxiv.org/abs/1406.2661">paper</a> from the Université de Montréal written in 2014 concerning generative adversarial networks, or <em>GANs</em>. The first name given credit in the paper is Ian Longfellow, and as far as I can tell he is the inventor of Generative Adversarial Networks. In a <a href="https://www.technologyreview.com/s/610253/the-ganfather-the-man-whos-given-machines-the-gift-of-imagination/">Technology Review</a>, Martin Giles refers to him as the ‘GANfather’.</p><p>The paper begins with a background on deep learning. Deep learning is a subset of machine learning that commonly involves multi-layer perceptrons. These are a form of artificial neural networks, <em>ANNs</em>, whose structure(algorithm) was inspired by the connection of neurons in the brain. Goodfellow references recent strides made in image detection, specifically implementations of ‘drop out’ and ‘back prop’ algorithms’. These adjust the way information is passed from neuron to neuron. Convolutional neural networks, <em>CNNs, </em>utilize a modified algorithm that is excellent for detection of multiple features in images using that to tell two types of images from one another. So models were getting really good at taking in an image and spitting out information about that image, but there was not a lot of success in models taking information and spitting out an image.</p><p>What the paper proposes is an ‘adversarial net’. This is comprised of two different deep learning ANNs, a generative model, and a discriminitory model that work against each other in a ‘<a href="https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/">minimax’ game</a>. The job of the generative model, G, is to capture the distribution of a dataset. It learns what the data looks like and uses that learned knowledge to generate something that looks similar; in a sense, how to <em>impersonate</em> it. The job of the discriminator, D, is also to learn the true distribution, and then look at what G generates and determine how much it looks like the real data; in a sense how to <em>appraise</em> the authenticity of the output of G.</p><ul><li>The aim of G in the minimax game is to maximize the probability of D making a mistake, where D outputs a probability of generated data being real. G wants to fool D into saying the output of G looks like the true distribution.</li><li>The aim of D in the minimax game is maximize accuracy of classifying G as coming from G and not from the true distribution. D wants to know when it is fed input from G and when it it is fed real data.</li></ul><p>I always think of the end of the movie, ‘Catch Me If You Can’. Frank Abagnale Jr. has been successfully forging checks, but is eventually caught by the FBI. Abagnale becomes a consultant to help analyze even higher quality forgeries crafted by another con-person. With Abagnale’s help the FBI becomes even better at detecting fake checks. Giles analogizes an picture forger and an art detective who repeatedly try to outwit one another.</p><p>While it is a little gloomy to compare a GAN to a con-artist, it is in someways realistic. This brilliant algorithm is not without potential for abuse. Such technology might be used all manor of imitations. Giles cites the potential to influence politics and stock prices with fake news. There is danger that comes with realistic fakes.</p><p>On a more positive note, however, there are some beneficial success attributed to GANs. In a <a href="https://www.sciencedaily.com/releases/2019/05/190516145206.htm">Science Daily</a>, Mustafa Mustafa, a machine learning engineer, refers to GANs as the ‘Holy Grail’ to studying dark matter. It is even signed with some of the algorithm! There is also a strong potential in <a href="https://www.forbes.com/sites/forbestechcouncil/2019/05/21/gans-and-deepfakes-could-revolutionize-the-fashion-industry/#430e335c3d17">fashion</a> for versatile artificial modeling using GANs. In October of 2018, Christies auction house, sold its first AI-produced art, <a href="https://en.wikipedia.org/wiki/Edmond_de_Belamy">Edmond de Belamy</a> (~$432,000.00).</p><p>To get just a little mathy, part of the algorithm aims to minimize log(1-D(G(z))) where z is like raw materials used by G to craft something that looks like it came from the true distribution.</p><p>The network should converge on a solution when them D(G(z)) is 0.5; it cannot determine the difference between the real data, and what is G generates. It is a temperamental algorithm though and the Goodfellow et al discuss a couple of practical issues.</p><p>The first issue is that allowing D to ‘learn to completion’ is computationally expensive and will overfit on finite datasets. Overfitting is a risk that machine learning models run when they look to closely at specific examples and fail to capture the general trend; they can’t see the forest for the trees. As a result overfitting decreases model performance. The computational cost and risk can be reduced by alternating between k steps of optimizing D, and 1 step of optimizing G. Functionally we don’t want D to learn to fast so we set a limit on the number of rounds it gets to play and force it to take a break after playing its limit.</p><p>The second issue if that when G starts out, it may not learn enough fast enough to fool D. In this scenario, there will be a high contrast between the out put of G and the true distribution, and D will reject G’s output too confidently and the factor that the GAN minimizes, log(1-D(G(z))) can ‘saturate’. This risk can be reduced by instead training the model to maximize log(D(G(z))). This would provide a stronger gradient early in the learning process and produce the same fixed point result.</p><p>References below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGn189Cdf4O74IWxs0ZWfg.png" /><figcaption>‘Edmond de Belamy’ by Obvious</figcaption></figure><p>References:</p><p><a href="https://www.technologyreview.com/s/610253/the-ganfather-the-man-whos-given-machines-the-gift-of-imagination/">The GANfather: The man who&#39;s given machines the gift of imagination</a></p><p>DOE/Lawrence Berkeley National Laboratory. “Training a neural network to study dark matter.” ScienceDaily. <a href="http://www.sciencedaily.com/releases/2019/05/190516145206.htm">www.sciencedaily.com/releases/2019/05/190516145206.htm</a> (accessed June 10, 2019).</p><ul><li><a href="https://en.wikipedia.org/wiki/Generative_adversarial_network">Generative adversarial network - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Edmond_de_Belamy">Edmond de Belamy - Wikipedia</a></li><li><a href="https://www.nytimes.com/2018/10/25/arts/design/ai-art-sold-christies.html">AI Art at Christie&#39;s Sells for $432,500 (Published 2018)</a></li><li><a href="https://www.forbes.com/sites/forbestechcouncil/2019/05/21/gans-and-deepfakes-could-revolutionize-the-fashion-industry/#430e335c3d17">GANs And Deepfakes Could Revolutionize The Fashion Industry</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c7750a32bdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Librosa: A Python Audio Libary]]></title>
            <link>https://medium.com/@patrickbfuller/librosa-a-python-audio-libary-60014eeaccfb?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/60014eeaccfb</guid>
            <category><![CDATA[librosa]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pitch]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Tue, 28 May 2019 22:57:09 GMT</pubDate>
            <atom:updated>2019-05-28T22:57:09.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>by: David Kaspar, Alexander Bailey, Patrick Fuller</h4><p>This is by no means the complete guide to Librosa, but may hopefully be a helpful place for getting started.</p><h4>Installing Librosa:</h4><p>I am using anaconda and had no trouble installing Librosa the following code as per the instructions from Librosa’s <a href="https://github.com/librosa/librosa">documentation</a>.</p><pre>conda install -c conda-forge librosa</pre><h4>Loading in a song:</h4><p>Librosa’s load function will read in the path to an audio file, and return a tuple with two items. The first item is an ‘audio time series’(type: array) corresponding to audio track. The second item in the tuple is the sampling rate that was used to process the audio. Eg:</p><pre>import librosa<br>data, sr = librosa.load(&#39;/Users/patrickfuller/Downloads/Led Zeppelin - Stairway To Heaven.mp3&#39;)</pre><pre>print(data.shape)<br>&gt;&gt;&gt;(21188736,)</pre><pre>print(sr)<br>&gt;&gt;&gt;44100</pre><p>The resulting array plotted might look like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*cPviJP1Wyw6-Cbjnrxyjtg.png" /><figcaption>Scaled amplitude plotted over ~10 million samples.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*-Ggl665a9q3oeToGG8-3KA.png" /><figcaption>Segment of above over fewer samples.</figcaption></figure><p>The default sampling rate used by Librosa is 22050, but you can pass in almost any sampling rate you like. Some common sampling rates can be found <a href="https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Sampling_rate">here</a>. Beware: resampling may add a non-negligible amount of run time for the load function(depending on your task). I found the run time for loading Stairway, a 8 min song to be about 16 seconds with default settings.</p><pre>start = time.clock()</pre><pre>test_array_default, _ = librosa.load(&#39;/Users/patrickfuller/Downloads/Led Zeppelin - Stairway To Heaven.mp3&#39;)</pre><pre>print(time.clock()-start)</pre><pre>&gt;&gt;&gt; <strong>15.907617</strong></pre><p>If you want to change the sample rate for your resulting audio time series, to 11000 for example, you can set the sample rate parameter in librosa.load() as:</p><pre># New Sample Rate<br>start = time.clock()</pre><pre>test_array_default, _ = librosa.load(&#39;/Users/patrickfuller/Downloads/Led Zeppelin - Stairway To Heaven.mp3&#39;, <strong>sr=11000</strong>)</pre><pre>print(time.clock()-start)</pre><pre>&gt;&gt;&gt; <strong>14.952034</strong></pre><p>If you need to reduce load time, you can pass in an optional parameter to the load function, ‘res_type’, short for <strong>resample type</strong>(default is ’kaiser_best’). Options are ‘scipy’ and ‘kaiser_fast’.</p><pre>start = time.clock()</pre><pre>test_array_default, _ = librosa.load(&#39;/Users/patrickfuller/Downloads/Led Zeppelin - Stairway To Heaven.mp3&#39;, <strong>res_type=&#39;kaiser_fast&#39;</strong>)</pre><pre>print(time.clock()-start)</pre><pre>&gt;&gt;&gt; <strong>4.631903</strong></pre><p>When using the default sample rate, the ‘kaiser_fast’ noticeably reduced the load time (~16 down to under 5), but the ‘scipy’ actually added time (<strong>85 seconds</strong>!!). When passing in sample rate as 11000, the ‘scipy’ it took about 67 second and ‘kaiser_best’ still came in fastest at about 4.85 sec.</p><p>The kaiser methods are code from the ‘resampy’ <a href="https://resampy.readthedocs.io/en/latest/example.html">module</a>, where as ‘scipy’ uses code from the ‘scipy’ <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html#scipy.signal.resample">module</a>. The ‘kaiser_best’ touts to be a higher quality. I cannot as of yet, back that claim scientifically.</p><p>There is however another parameter for sample rate, that can potentially improve both load time, and quality. If you pass sample rate as <strong>None</strong>, instead of resampling the audio, it will use the native sampling rate. This method resulted in a run time of about 1.4 seconds and had a noticeably higher quality playback. The track I was testing this with was stored with a sample rate of 44100 and that information is encoded into the file. You can right click on a file in finder to <em>get info</em>&gt;<em>more info</em> from finder, or get <em>song info</em>&gt;<em>file info</em> from iTunes to find this. If using windows, I believe right clicking in explorer and selecting properties might provide this information.</p><p>This native sampling functionally keeps the original sonic features in the output array instead of mashing features together. The size of the array gets smaller with a smaller sample rate. The longer array (more detailed audio) can add to processing time later on in workflow. For example computing a <em>mel spectrogram</em> the largest array took almost 4 seconds versus about 1.6 for the resampled smaller array. This additional time is much smaller than the margin(15s to 1.4) from load time, but if your running multiple operations it may add up. If you’re running 100 operations on the array the size of the array the may run up a bigger tab than the load time and you may want to resample to a smaller array.</p><h4>Mel Spectrogram:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*fnYGQAxZCwU6LURt4KjJaw.png" /><figcaption>Wikipedia graph: mel vs hz</figcaption></figure><p>What is a mel spectrogram? Well first let’s start with the mel. A mel is a number that corresponds to a pitch, similar to how a frequency describes a pitch. If we consider a note, A4 for example, its frequency is 440 hz. If we move up an octave to A5 its frequency doubles to 880 hz, and doubles again to 1760 at A6. So thats a jump of 440 between the A4 and A5 and 880 between A5 and A6, but the problem is that the human ear doesn’t hear that way. The difference between two notes feels the same whether we jump from C to D or from F to G. But the logarithmic relationship gives different hz values for these different intervals. The term mel comes from the word ‘melodic’ and the mel scale is intended to regularize the intervals between notes. Unfortunately there does not seem to be one uniform mel scale. The code used by Librosa is a bit cryptic can be found <a href="https://github.com/librosa/librosa/blob/master/librosa/filters.py">here</a>. In principle the mel is used to display pitch in a more regularized distribution.</p><p>Librosa includes a function to exctract the power spectrogram (amplitude squared) for each mel over time as well as a function for easy display of the resulting mel spectrogram. This display function is not automatically imported with librosa and must be imported on its own as such:</p><pre>spec = librosa.feature.melspectrogram(y=data, sr=sr)</pre><pre>import librosa.display<br>librosa.display.specshow(spec,y_axis=&#39;mel&#39;, x_axis=&#39;s&#39;, sr=sr)<br>plt.colorbar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*tRuUqwr0W6t9Kcdn3W7uiA.png" /></figure><p>Well thats not a lot of information. The Librosa documentation includes a tutorial that covers this very issue. Librosa has a function to convert the amplitude squared to decibels.</p><pre>db_spec = librosa.power_to_db(spec, ref=np.max,)<br>librosa.display.specshow(db_spec,y_axis=&#39;mel&#39;, x_axis=&#39;s&#39;, sr=sr)<br>plt.colorbar();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*XbIoJXPfGdfymeWsDT0Hqw.png" /><figcaption>Pitch intensities over time.</figcaption></figure><h4>Harmonic Percussive Separation:</h4><p>Librosa can also separate the initial audio series into harmonic and percussive components.</p><pre>data_h, data_p = librosa.effects.hpss(data)</pre><pre>spec_h = librosa.feature.melspectrogram(data_h, sr=sr)<br>spec_p = librosa.feature.melspectrogram(data_p, sr=sr)<br>db_spec_h = librosa.power_to_db(spec_h,ref=np.max)<br>db_spec_p = librosa.power_to_db(spec_p,ref=np.max)</pre><p>And when plotted we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*1NonkTqEEcFWkryKnPINBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*OJiPcdon11SpSSiXIepLgQ.png" /></figure><p>Around 140 seconds into the song the intensities for both harmonic and percussive low frequencies increase. For the harmonic this is likely the bass guitar, and for percussive this would be the kick drum. Now that the percussive features are separated out we can extract which pitches are present as notes from the harmonic features.</p><pre>chroma = librosa.feature.chroma_cqt(y=data_h, sr=sr)</pre><pre>plt.figure(figsize=(18,5))<br>librosa.display.specshow(chroma, sr=sr, x_axis=&#39;time&#39;, y_axis=&#39;chroma&#39;, vmin=0, vmax=1)</pre><pre>plt.title(&#39;Chromagram&#39;)<br>plt.colorbar()</pre><pre>plt.figure(figsize=(20,8))<br>plt.title(&#39;Stairway To Heaven: Chroma Spectrogram&#39;)<br>librosa.display.specshow(chroma, sr=sr, x_axis=&#39;s&#39;, y_axis=&#39;chroma&#39;, );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CUJZqriP_uYM0OGPm1ToA.png" /></figure><p>It looks like this song has a lot of A. It’s seems likely that this is the key of the song(any guitar players out there?). It’s a bit too much information in one graph though. Let’s take a look at just the first thirty seconds.</p><pre>first_thirty_seconds = librosa.time_to_samples(30, sr=sr)<br>intro = data[:first_thirty_seconds]</pre><pre>intro_harm = librosa.effects.harmonic(intro)<br>intro_chroma = librosa.feature.chroma_cqt(intro_harm, sr=sr)</pre><pre>plt.figure(figsize=(20,8))<br>plt.title(&#39;Stairway To Heaven: Chroma Spectrogram&#39;)<br>librosa.display.specshow(intro_chroma, sr=sr, x_axis=&#39;s&#39;, y_axis=&#39;chroma&#39;, )<br>plt.colorbar();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnVCRmWiwzLhfmKWxRt0UA.png" /></figure><h4>How fast is this song?</h4><p>Last but not least, Librosa’s beat.tempo function will estimate the tempo of the audio sample in beats per minute.</p><pre>print(librosa.beat.tempo(data, sr=sr))<br>&gt;&gt;&gt;[139.67483108]</pre><p>This is just an estimation, as this is a long song with multiple different parts with tempo up and down but it is potentially interesting for comparing songs.</p><p>These are only some of the many operations that Librosa can perform but hopefully they will provide a jumping off point to explore the rest of them and/or other musical analyses as well!</p><p>References:</p><ul><li><a href="https://librosa.github.io/librosa/index.html">https://librosa.github.io/librosa/index.html</a></li><li><a href="https://github.com/librosa/librosa">https://github.com/librosa/librosa</a></li><li><a href="https://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20demo.ipynb">https://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20demo.ipynb</a></li><li><a href="https://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20audio%20effects%20and%20playback.ipynb">https://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20audio%20effects%20and%20playback.ipynb</a></li><li><a href="https://en.wikipedia.org/wiki/Mel_scale">https://en.wikipedia.org/wiki/Mel_scale</a></li><li><a href="https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Sampling_rate">https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Sampling_rate</a></li><li><a href="https://resampy.readthedocs.io/en/latest/example.html">https://resampy.readthedocs.io/en/latest/example.html</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html#scipy.signal.resample">https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html#scipy.signal.resample</a></li><li><a href="https://groups.google.com/forum/#!topic/librosa/TIke2HVJHdc">https://groups.google.com/forum/#!topic/librosa/TIke2HVJHdc</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60014eeaccfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NumPy Art- A Tutorial in Scatter-Fun]]></title>
            <link>https://medium.com/@patrickbfuller/numpy-art-a-tutorial-in-scatter-fun-634f79628435?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/634f79628435</guid>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Mon, 20 May 2019 18:09:15 GMT</pubDate>
            <atom:updated>2019-05-20T18:09:15.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXJAD4hKPkAgrIZVudn47g.png" /><figcaption>A little bit of random, a little bit of order.</figcaption></figure><p>I was working on an assignment recently and arrived at an exponential distribution. One segment of the exercise was to graph part of the corresponding parabola bit by bit. It ended up looking something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*YloSP6CGX-334weyjmeWJw.png" /><figcaption>The true nature of the distribution.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*TxxtWDywDnf00XqahRahsg.png" /><figcaption>The segmented chunks drawn one by one.</figcaption></figure><p>This was a nice little lightbulb moment for me. Nothing truly groundbreaking mind you. It was something akin to, “OOooh, look at the colors!”.</p><p>So far I have found it more common to plot a collection of points as two corresponding lists/arrays of x values and y values. It might like something like this for example:</p><pre>x = np.linspace(-4,4,5)<br>y = x**2<br>plt.scatter(x, y)</pre><p>This results in one color for all the points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*qnuE2KjDXtfBCCJl5Dr6sA.png" /><figcaption>Less colorful, less pop.</figcaption></figure><p>The principle for graphing the different colors on the same graph is to call pyplot(as plt) multiple times.</p><pre>for x in range(-2,3):<br>    plt.scatter(x, x**2)</pre><p>Each time x is reassigned in the for loop, pyplot is creating a new scatter plot with a different color. I can only presume this architecture is designed to allow to functions to appear distinct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*-gb8MBmd4x5Bav7b_P6UVw.png" /><figcaption>Different colors to help distinguish between functions.</figcaption></figure><p>I had recently also discovered passing the size of the scatter markers as a changing variable and my next experiment resulted in something more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*jdAXrhmtJAtUWQ500qzR7g.png" /><figcaption>Colors with changing size for extra pop.</figcaption></figure><p>At this point I began to wonder what about adjusting more features in a graph with multiple different colors.</p><p>To take a step back, lets break down a few simple parameters of my new favorite function, <strong>matplotlib.pyplot.scatter</strong>.</p><ol><li><strong>Size</strong>- This adjusts the size of the markers. If you wanted to adjust the size of the graph, in an earlier line use plt.figure(figsize=(<em>width</em>, <em>height</em>)).</li><li><strong>Color</strong>- This adjusts the color of a given scatterplot’s markers. This parameter could take a number of different value types. It could take a string of one color by name, or a list of colors(with the same length as the distribution plotted). The color parameter will also accept RGB, RGBA and HEX colors.</li><li><strong>Alpha</strong>- This parameter adjusts the opacity of the markers plotted. This is very handy when analyzing distributions, and many of the points over lap. It allows us to see a ‘cloud-like’ representation of the data with regions with less data appearing lighter.</li><li><strong>Marker</strong>- This parameter adjusts the shape or style of the marker plotted. Common choices are circles, triangles, or diamonds, but there are quite a number of others the can be found <a href="https://matplotlib.org/api/markers_api.html#module-matplotlib.markers">here</a>. A recent new favorite might be the ability to pass in any text you like by passing marker = “$text$”.</li></ol><ul><li>There are many other amazing parameters of the scatterplot and can be found at Matplotlib’s documentation, <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html">matplotlib.pyplot.scatter</a>.</li></ul><p>I initially began experimenting with hex colors. A hex color is just six numbers (single digit integers)preceded with a ‘#’. An example might look like ‘#000000’ or ‘#052884’. Also sometimes they can include letters and sometimes they can be three long instead of six. I have generally seen it passed a string in python. I initially landed on the code below as a way to randomize color:</p><pre>hexlist = [str(np.random.randint(0,10)) for i in range(6)]<br>color = &#39;#&#39;+&#39;&#39;.join(hexlist)</pre><p>Ultimately I found my self randomizing color using an RGB/RGBA architechture more often than hex. RGB uses an array of three values ranging from 0 to 1. Each value corresponds to an intensity in the hues, red, green, and blue accordingly. An optional fourth value corresponds to the alpha value(opacity like above). I arrived at this code for my RGBA randomizer.</p><pre>rgba = [np.random.random() for _ in range(4)]<br>color = np.array([rgba])</pre><p>Why do we care a bout randomizing color, when calling new scatterplots will change the color for us? Well lets take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*hQhwTMVwbj06_7JwNIsV0A.png" /><figcaption>Using the default colors that scatterplot provides.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*bwRWSr1n89QPtTXrSe7MPA.png" /><figcaption>Adding in randomized color.</figcaption></figure><p>The default colors provided when the scatterplot chooses its own are not bad. Many are pastel, and they really don’t seem to grab the full spectrum compared to full randomization. To be 100% transparent(forgive the pun), the second plot also has opacity randomized with all four values in RGBA. Full opacity would look so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*hQAoqJR3Koaq_Yy817Bq0A.png" /><figcaption>Only three values randomized: RGB</figcaption></figure><pre>xs = np.linspace(-100,100,1000)<br>for x in xs:<br>    rgb = [np.random.random() for _ in range(3)]<br>    color = np.array([rgb])<br>    plt.scatter(x,np.random.normal(),<br>               s = (np.abs(x))/20,<br>               c = color)</pre><p>So far I have only tied size to a variable and randomized color, but both can randomized or assigned to a value in the distribution. The world is our multi-colored oyster. Lastly to randomize markers I found a dictionary online and used np.random.choice to select them as follows:</p><pre>markers = {&#39;.&#39;: &#39;point&#39;, &#39;,&#39;: &#39;pixel&#39;, &#39;o&#39;: &#39;circle&#39;, &#39;v&#39;: &#39;triangle_down&#39;, &#39;^&#39;: &#39;triangle_up&#39;, <br>           &#39;&lt;&#39;: &#39;triangle_left&#39;, &#39;&gt;&#39;: &#39;triangle_right&#39;, &#39;1&#39;: &#39;tri_down&#39;, &#39;2&#39;: &#39;tri_up&#39;, &#39;3&#39;: &#39;tri_left&#39;, <br>           &#39;4&#39;: &#39;tri_right&#39;, &#39;8&#39;: &#39;octagon&#39;, &#39;s&#39;: &#39;square&#39;, &#39;p&#39;: &#39;pentagon&#39;, &#39;*&#39;: &#39;star&#39;, &#39;h&#39;: &#39;hexagon1&#39;, <br>           &#39;H&#39;: &#39;hexagon2&#39;, &#39;+&#39;: &#39;plus&#39;, &#39;x&#39;: &#39;x&#39;, &#39;D&#39;: &#39;diamond&#39;, &#39;d&#39;: &#39;thin_diamond&#39;, &#39;|&#39;: &#39;vline&#39;, <br>           &#39;_&#39;: &#39;hline&#39;, &#39;P&#39;: &#39;plus_filled&#39;, &#39;X&#39;: &#39;x_filled&#39;, 0: &#39;tickleft&#39;, 1: &#39;tickright&#39;, 2: &#39;tickup&#39;, <br>           3: &#39;tickdown&#39;, 4: &#39;caretleft&#39;, 5: &#39;caretright&#39;, 6: &#39;caretup&#39;, 7: &#39;caretdown&#39;, 8: &#39;caretleftbase&#39;,<br>           9: &#39;caretrightbase&#39;, 10: &#39;caretupbase&#39;, 11: &#39;caretdownbase&#39;, &#39;None&#39;: &#39;nothing&#39;, None: &#39;nothing&#39;, <br>           &#39; &#39;: &#39;nothing&#39;, &#39;&#39;: &#39;nothing&#39;}</pre><pre>plt.figure(figsize=(12,12))<br>for _ in range(1000):<br>    a = np.random.randint(0,1000,5)<br>    b = np.random.randint(0,1000,5)<br>    rgba = [np.random.random() for _ in range(4)]<br>    color = np.array([rgba])<br>    marker = np.random.choice(list(markers.keys()))<br>    alpha = np.random.random()**2.5<br>    size = np.random.exponential()**5.3<br>    plt.scatter(a,b, alpha=0.4, marker=marker,<br>               color=color, s=size)</pre><p>Resulting in something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*3WObad2kTLDpIn_Nxr66lg.png" /><figcaption>So many shapes!</figcaption></figure><p>At this point, so many features have been randomized so many times, that each time the code is run, it produces something that will likely never be reproduced in the same way. In this light, the code starts to take on a strange beauty for its ephemerality, aside from its partial resemblance to some modern art.</p><p>Lastly but not least, here is my new favorite adding text for markers:</p><pre>for x in range(5):<br>    plt.scatter(x,x, marker=&quot;$yup$&quot;, s=1000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Qfjx-GXWjM2ei5VixVMOpA.png" /><figcaption>Need I say more? …fine YUP!</figcaption></figure><p>To change the color of the background and remove axes I use:</p><pre>plt.style.use(&#39;dark_background&#39;)<br>plt.axis(&#39;off&#39;)</pre><p>The code for these experiments can be found at my <a href="https://github.com/Patrickbfuller/random_graph">repo</a> and below are some of my favorites.</p><ul><li>DSAF</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSGoHGBxOF8X5vSsu4RdOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hX9wUGsx5F4uAuMA74qxUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zflVM6i6rYUjU3GXx1EfHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqEXqsdKm_WJxxgUx21xFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXJAD4hKPkAgrIZVudn47g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dXNK2c9mkb6OIpTPTobIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alCnHRHpvqDGp1QLJ1XoRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-tQzdyL458emqQTnSatOw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=634f79628435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Line-Plot]]></title>
            <link>https://medium.com/@patrickbfuller/line-plot-7b4068a3a9fc?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b4068a3a9fc</guid>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Thu, 02 May 2019 14:44:11 GMT</pubDate>
            <atom:updated>2019-05-02T14:44:11.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>Visualizations-what are they and what do we use them for?</h4><p>Visualizations are a key part of many walks of life and my quest in learning Data Science is no exception. We’ve got numbers, we’ve got other numbers and we’ve got more numbers. But reading them off in a list rarely does them justice. It often far more helpful and much faster to display them visually. One of the main types of data visualizations is the line-plot.</p><h4>What is a line-plot?</h4><p>According to the wiki,</p><blockquote>“A line chart or line plot or line graph is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields”</blockquote><p>Well okay, that sounds pretty fancy. What does this fancy graph look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fhU845CNFSqfgb6IxpoRuw.jpeg" /><figcaption>**google image search ‘line plot’ … first result</figcaption></figure><p>Hmm. It has ‘markers’ and we could say the points <em>are</em> ‘connected by straight line segments’. But this is more of a histogram functionally, assessing counts of values in one dimension. What about that line-<em>chart </em>in the wiki definition?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*zhXyt_vc04KTPHLCU2Yf8Q.png" /><figcaption>**google image search ‘line chart’ … first result**</figcaption></figure><p>Now that certainly appears more ‘Data Science’-ey, doesn’t it? What’s the difference? This line chart is doing a lot. If we look at just one line(let’s start with the blue one), its depicting 6 values for population of bears from six years. The markers represent the individual data points, and the lines connecting them give the viewer a sense of <em>rate of change</em> between points. So that’s one extra dimension numerically(measures different years on one axis, and different populations on the other). This graph also depicts not one lines worth of data but <strong>three</strong>! Different colored lines portray the population over time for multiple species at once. So it is kind of four graphs in one: a graph of the population trend for each of the three species, as well as a graph comparing those three graphs.</p><p>When is this visualization effective?</p><p>This graph of wildlife population example is a good example of the ‘wheel-house’ for line charts. The lines depicting rate of change make it very easy for the human eye to compare rates of change over time or, <em>trends</em>. These time series analyses are also useful when comparing trends between categories, such as the populations of different species, or social media traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Ir0W1A-eNz9nGPSuAI5uXQ.jpeg" /><figcaption>A comparison of trends</figcaption></figure><h4>Where might line charts fall short?</h4><p>Line chart shows every point and as such is subject to statistical noise. If you were aiming to display an <em>overall</em> rate of change, a single linear regression plot would be easier to understand. The human eye may be distracted by different slopes in a line chart. Also, comparing multiple slopes does not give a clear sense of their combined trend.</p><h4>Where do line charts excel?</h4><p>Line charts are perfect for time series analysis. They are commonly used for anything dollar related. Its literally the first thing I think of when I picture my savings. It is also a great visual example of the stock-prices and they are great tool for analyzing different trends all over the social media world.</p><p>Any change in a feature over time will be ripe for a line chart. Think political approval ratings, price of milk &amp; bread, crime rates, population, greenhouse gas levels, heart rate, revenue historical analysis and so on.</p><h4>Weaknesses with comparison to other graphs:</h4><p>A good visualization is like communicating, and to be effective, it should be clear and concise. The wildlife graph is able to display a lot of information quickly by adding more lines with different colors. This allows it to compare categories. The viewer gets a sense of the relative trends for each species. But while you can compare differences between categorical data by adding other lines with different colors, bar charts are often shorter and more to the point for categorical topics.</p><p>On a similar note, you could technically get a sense of the spread of data with a line chart, but it would probably feel messy, and would not be your best tool. For getting a sense of the distribution of data no graph will ever beat a histogram. Line charts are pretty flexible and can do many nice things, but histograms are sweeter and quicker to the punch.</p><p>How important is speed and readability? Well it depends on the task for the visualization. A graph could be used for a quick dip into EDA or as evidence in a pivotal presentation. If you are exploring collection of data, a simpler less complicated graph will be good to maintain workflow(histograms for exapmle). I haven’t found myself line plotting many variables. Once you start forming hypotheses and using data for evidence however, we can delve into the more complicated line chart and get more bang for our buck. Try making your own line chart to depict something in your world that changes over time. Maybe your trivia team vs your rivals!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b4068a3a9fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Data Science!?]]></title>
            <link>https://medium.com/@patrickbfuller/why-data-science-cd7f1d9bb733?source=rss-16b01fdb4ccb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd7f1d9bb733</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Patrick Fuller]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 23:23:53 GMT</pubDate>
            <atom:updated>2019-04-21T23:26:49.395Z</atom:updated>
            <content:encoded><![CDATA[<p>‘Why?’ is an important question. Sometimes the answer, our <strong><em>reason</em></strong><em> </em>why, is simple in its purest form, but it is often complicated to explain. The answers to ‘Who?’, ‘what?’, ‘where?’, and ‘when?’ are much easier to explain, and while these are less important questions, perhaps they can build a framework for answering the big ‘Why?’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4HDzr4CBqyfXiCrJQAxBqA.gif" /></figure><p><strong><em>WHO </em></strong>I am a musician. I am a yoga teacher. I have a bachelors in biology and minor in chemistry. I love cooking and if I don’t make a list, I will almost certainly forget to do something.</p><p>These are <strong>things</strong> about me but ultimately, more of pointers to who I AM.</p><p>I once asked a trusted friend what she thought I should be doing. She referenced my passion for biology, my long history of songwriting, and my joy in cooking and guiding yoga classes. To paraphrase her, she pointed out that, “Each of these contain unique moving parts and have different systems for connecting one to another. <strong>That’s what you need</strong>.” At the time, I agreed that she was indeed right on the mark(<em>again</em>) but I had not yet had the ‘lightbulb moment’ where I would connect that template to Data Science.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLIjfq5CPyhoMoLIAqxDMw.jpeg" /></figure><p><strong><em>WHAT</em></strong> even <em>is</em> data science? Is it math? Science? Computer programming? It seems to be some strange marriage of these fields and the skills to put the resulting combination to a practical use. I am honestly not yet confident I could pin it down and explain it to an audience, technical or otherwise. I am confident however that this ‘thingy thing’ is <em>fascinating</em>. It’s hard to put down. Addicting in a way. It is also unexpected. It’s not something I ever pictured myself diving into as fully as I have. When initially exploring careers involving programming, my first reaction to data science was a guess that it would be boring. That first take couldn’t have been farther off. Very quickly it became the sort of discipline in which I would get up from my work to find hours have passed in what felt like moments. It is enthralling. I have literally set alarms on my phone to take break to eat and drink.</p><p><strong><em>WHERE</em></strong><em> </em>We live in a world where we generate so much data that humans could never make sense of it on their own. As a result we turn to our computers to help us process it. Technology has permeated our society. It is a big part of the way we live and is magical in a lot of ways. When I asked my older brother for career advice, he shared a hypothesis akin to, “In ten years if you don’t know some coding, you’ll be a dinosaur.” Whether or not that is the case, it sparked an investigation. This led me to a conversation with a fraternity brother of mine who had been coding for 3 or so years. He was moving out of San Fransisco, and when I asked him where he was moving to, he said he wasn’t sure yet. Worried that his job situation might be shaky, I politely inquired about his employment. He responded that he still worked for the same company but could now work from wherever he wanted. This pretty much blew my mind. I mean, I knew that sort of thing technically existed, but seeing it materialize for a close friend is another story. After that I decided I did not know enough about the world where I live. Cue google search: ‘Coding Jobs’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*ZZFtKUx4rvKCNh5QUxDeOQ.gif" /></figure><p><strong><em>WHEN</em></strong> The year is 2019. Skynet hasn’t taken over yet… but tech seems to have become one of the most important industries. The moment is somewhere between not being a Data Scientist and acheiving that goal. I am less than a month into an immersive career change program and pandora’s box has been opened. I could argue it is a renaissance of sorts. Maybe it’s more of a revelation. For now I’ll say that it is exciting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qObABRh1dkCwrXWHN1EhQw.jpeg" /></figure><p>But <strong>WHY??</strong> Why did I decide on Data Science?</p><ul><li>I like learning challenging, technical skills.</li><li>I want to put technical skills to use.</li><li>I want to explore the other ends of the spectrum from teaching yoga and playing music.</li><li>I’d like to have a ‘<em>good</em>’ job.</li><li>I want to be in demand and part of a growing field.</li><li>Subconsciously, I probably crave the ability to organize complex data structures to compensate for not being able to wrangle my messy life. Isn’t it satisfying to pull answers out of the mysterious jumble the world gives us.</li></ul><p>There are a lot of WHY’s, but ultimately I think they’re more of validations. The real why is probably closer to what my friend mentioned:</p><blockquote><strong>A system of unique parts;</strong></blockquote><blockquote><strong>The different ways they interact…</strong></blockquote><p>There are feelers. There are creatives. There are organizers and so on. Personally I’m really not sure into which of these categories I fall most heavily. I can say however, that the more I dive into Data Science, the more it applies to life. It’s really a part of the same way I’ve always seen things, and in practical terms it offers a vocabulary and framework for interpreting the world around us.</p><p>It’s a lens. It’s a decoder. It’s the way the world works, and once you pick up the language, you can’t unsee it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP7uibnCtTJ5uRqtnCdvPQ.jpeg" /></figure><p>DSAF</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd7f1d9bb733" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>