<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ baseball - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ baseball - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 27 Jun 2026 16:35:57 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/baseball/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Echo Buttons take Amazon Alexa Skills to a new level ]]>
                </title>
                <description>
                    <![CDATA[ By Terren Peterson I’m recognized as an Amazon Alexa Champion and have published more than twenty custom skills on the platform. I continue to look for new ways to stretch this technology, create more robust skills, and share with the community. Last... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-echo-buttons-take-amazon-alexa-skills-to-a-new-level-d4c489853b1f/</link>
                <guid isPermaLink="false">66c34d17465d1b2f886ba3e1</guid>
                
                    <category>
                        <![CDATA[ amazon echo ]]>
                    </category>
                
                    <category>
                        <![CDATA[ baseball ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 26 Jul 2018 23:49:51 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*F6CHpSv0t3e2ntNu0iDygw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Terren Peterson</p>
<p>I’m recognized as an Amazon <a target="_blank" href="https://developer.amazon.com/alexa/champions/terren-peterson">Alexa Champion</a> and have published more than twenty custom skills on the platform. I continue to look for new ways to stretch this technology, create more robust skills, and share with the community.</p>
<p>Last <a target="_blank" href="https://developer.amazon.com/blogs/alexa/post/402fd908-f8d7-4a2b-ab5e-4099222ad974/introducing-alexa-gadgets-new-tools-for-developers-to-create-fun-sign-up-to-stay-tuned">September</a>, Amazon released a new product for Alexa called Echo Buttons. These hardware devices expand the capabilities for the millions of customers that already have an Alexa. They’re relatively inexpensive, right now going for <a target="_blank" href="https://www.amazon.com/dp/B072C4KCQH/">$20/2 pack</a>.</p>
<p>In <a target="_blank" href="https://developer.amazon.com/blogs/alexa/post/705a0ac1-940d-4128-b35e-7085274eca6a/gadgets-skill-api-beta-is-now-available-developers-can-build-games-for-echo-buttons">April</a> of this year, Amazon opened up the platform for developers like me to begin incorporating them into custom skills. This is my experience so far programming with them.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CyYLDlEogrNXnrYiXgOAfMnPLr-EHMGF5S87" alt="Image" width="800" height="600" loading="lazy">
<em>Echo Button in inactive state.</em></p>
<h3 id="heading-getting-started-with-echo-buttons">Getting Started with Echo Buttons</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/rD-kqpmupIZML-HuI46qqn97rNmfe2CmT7fx" alt="Image" width="700" height="300" loading="lazy">
<em>Network connectivity of Echo Buttons</em></p>
<p>Buttons are paired with Alexa devices through a bluetooth connection, becoming a physical extension of the speaker. All network traffic from the button to use Amazon services goes through the paired device. Don’t buy buttons if you don’t already have an Alexa, as they don’t do anything on their own.</p>
<p>If you have multiple speakers associated with your account, the button will only work with the device it’s currently paired with. The pairing can be undone with just a few steps on your phone. To unpair a device, just use the Alexa companion app and go into the settings section. Select the button that has already been paired, and it will release it. Then go back through the steps to repair to another device.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/hivuzrSwuf4WcMXDB25tWOKDBXz6qIeQHMiy" alt="Image" width="750" height="1073" loading="lazy">
<em>Screenshot of Alexa App on a Mobile Device</em></p>
<p>This makes buttons an easy add on for Alexa enthusiasts, and makes them flexible for those with multiple devices.</p>
<h3 id="heading-how-buttons-interact-with-custom-skills">How Buttons Interact with Custom Skills</h3>
<p>Alexa is an event driven architecture. Events are created by the sounds going into the speaker that are translated through Cloud based service. Normally these events are initiated after the array of microphones picks up a command from a user. These commands are then translated by the ASR (Automated Speech Recognition) models depending on which custom skill is being used.</p>
<p>With buttons, a new type of event is created that follows a similar pattern. When the button is pressed, an event is created and sent to the skill that runs in the Cloud. When the button is released, a separate event is created. These events are created independently of anything being picked up by the microphones on the Echo Speaker and flow through a Cloud based service called the Game Engine.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xn54u0QFvTYWHG-5EBh2IwBAYKiYXRMUVCAY" alt="Image" width="650" height="334" loading="lazy">
<em>Alexa Event Architecture including Buttons</em></p>
<p>The Lambda function that contains the logic for the custom skill needs to process these events along with the existing voice triggered ones. Translating request objects is facilitated by the Alexa SDK installed in the Lambda function. Examples of how this works are provided in the <a target="_blank" href="https://github.com/alexa/skill-sample-nodejs-buttons-hellobuttons">Alexa repo</a>.</p>
<p>This opens up new possibilities for gameplay, as a user can leverage both their voice and hands to interact with the skill. Engaging more senses broadens the experience, and enables more complex gaming. For example, in the <a target="_blank" href="https://www.amazon.com/Seventh-Inning-Stretch-Baseball-Game/dp/B071FF8WCN">Seventh Inning Stretch skill</a>, a user can play a baseball game listening on their speaker while pressing the button to swing the bat.</p>
<h3 id="heading-how-skills-use-the-gadgets-api">How Skills use the Gadgets API</h3>
<p>Using buttons within a custom skill requires the Gadgets API. Documentation is currently on this <a target="_blank" href="https://developer.amazon.com/docs/gadget-skills/understand-gadgets-skill-api.html">website</a>, and note that it is still in beta. Buttons are just a type of gadget, and provide a glimpse into what’s possible with enabled hardware.</p>
<p>Connectivity between systems is facilitated by interfaces across the internet. The API that buttons need is invoked by adding directive attributes to a standard Alexa response object. This enables the SDK to handle the explicit details for the HTTPS call (i.e. encoding the header, setting the attributes, error handling, etc.)</p>
<p>Here is an example of adding a directive to set the lights on a button at the same time that the Echo speaker reads back an introduction to the user.</p>
<pre><code><span class="hljs-string">"response"</span>: {               <span class="hljs-string">"shouldEndSession"</span>: <span class="hljs-literal">false</span>,               <span class="hljs-string">"outputSpeech"</span>: {                     <span class="hljs-string">"type"</span>: <span class="hljs-string">"SSML"</span>,                     <span class="hljs-string">"ssml"</span>: <span class="hljs-string">"&lt;speak&gt; Welcome back to Seventh Inning Stretch.&lt;break time=\"1s\"/&gt;We found an prior game in progress. Would you like to resume? &lt;/speak&gt;"</span>                 },               <span class="hljs-string">"reprompt"</span>: {                     <span class="hljs-string">"outputSpeech"</span>: {                           <span class="hljs-string">"type"</span>: <span class="hljs-string">"SSML"</span>,                           <span class="hljs-string">"ssml"</span>: <span class="hljs-string">"&lt;speak&gt; Say yes to resume the in-progress game, or no to delete it.  &lt;/speak&gt;"</span>                     }               },               <span class="hljs-string">"directives"</span>: [    {                           <span class="hljs-string">"type"</span>: <span class="hljs-string">"GadgetController.SetLight"</span>,                            <span class="hljs-string">"version"</span>: <span class="hljs-number">1</span>,                           <span class="hljs-string">"targetGadgets"</span>: [],                           <span class="hljs-string">"parameters"</span>: {                      <span class="hljs-string">"animations"</span>: [               {                         <span class="hljs-string">"repeat"</span>: <span class="hljs-number">1</span>,                            <span class="hljs-string">"targetLights"</span>: [<span class="hljs-string">"1"</span>],              <span class="hljs-string">"sequence"</span>: [                          {                    <span class="hljs-string">"durationMs"</span>: <span class="hljs-number">30000</span>,                                                               <span class="hljs-string">"color"</span>: <span class="hljs-string">"FFFF00"</span>,                  <span class="hljs-string">"blend"</span>: <span class="hljs-literal">false</span>                                                     }              ]                      }           ],      <span class="hljs-string">"triggerEvent"</span>: <span class="hljs-string">"buttonDown"</span>,                                <span class="hljs-string">"triggerEventTimeMs"</span>: <span class="hljs-number">0</span>    }}
</code></pre><p>The Game Engine creates events just like the Echo speaker. The same taxonomy is used, and the attributes within the request identifies event details. Below is an example of a request indicating that a button was pressed.</p>
<pre><code>“request”: {   “type”: “GameEngine.InputHandlerEvent”,   “requestId”: “amzn1.echo-api.request.xxx”,   “timestamp”: “<span class="hljs-number">2018</span>–<span class="hljs-number">07</span>–<span class="hljs-number">21</span>T21:<span class="hljs-number">33</span>:<span class="hljs-number">25</span>Z”,   “locale”: “en-US”,   “originatingRequestId”: “amzn1.echo-api.request.xxx”,   “events”: [     {       “name”: “button_down_event”,       “inputEvents”: [ {         “gadgetId”: “amzn1.ask.gadget.xxxx”,         “timestamp”: “<span class="hljs-number">2018</span>–<span class="hljs-number">07</span>–<span class="hljs-number">21</span>T21:<span class="hljs-number">33</span>:<span class="hljs-number">25.374</span>Z”,         “color”: “<span class="hljs-number">000</span>DD6”,         “feature”: “press”,         “action”: “down”       } ]     }   ] }
</code></pre><h3 id="heading-save-battery-life-through-roll-call">Save Battery Life through Roll Call</h3>
<p>Echo Buttons are battery powered, making energy management important. When a custom skill requires a button, it must initiate a connection and wake the button. This is done through a process called ‘roll call’ within the custom skill.</p>
<p>To initiate a roll call in a custom skill, add a directive to the response object providing the parameters to perform the task. In parallel, audio instructions need to be included in the response object. These will encourage a user to do something with the buttons. For example, ask the user to press each button to get started.</p>
<p>For specifics on what a directive looks like, here is the roll call directive I use for my Seventh Inning Stretch skill. It’s a series of attributes in a large JSON object. This sets the timeout parameter for when the buttons can go back to sleep if not used (the 300,000 value is in milliseconds — this translates to five minutes), and looks for just the button down event.</p>
<pre><code><span class="hljs-string">"directives"</span>: [  {     “type”: “GameEngine.StartInputHandler”,     “timeout”: <span class="hljs-number">300000</span>,     “recognizers”: {       “button_down_recognizer”: {         “type”: “match”,         “fuzzy”: <span class="hljs-literal">false</span>,         “anchor”: “end”,         “pattern”: [{ “action”: “down” }]       }    },     “events”: {       “button_down_event”: {         “meets”: [“button_down_recognizer”],         “reports”: “matches”,         “shouldEndInputHandler”: <span class="hljs-literal">false</span>       },       “timeout”: {         “meets”: [“timed out”],         “reports”: “history”,         “shouldEndInputHandler”: <span class="hljs-literal">true</span>       }     }  }]
</code></pre><p>The buttons handle the timer for when to turn off. This minimizes the risk of battery drain when a user ends their session. Skills that use buttons should also make a request to the shut off the device if the skill is exited.</p>
<h3 id="heading-translating-game-engine-events">Translating Game Engine Events</h3>
<p>The Game Engine can create events just like the speaker after it is awake. The request uses the same taxonomy, and the attributes identify details of the event. Here is an example of a request indicating that a button was pressed.</p>
<pre><code>“request”: {   “type”: “GameEngine.InputHandlerEvent”,   “requestId”: “amzn1.echo-api.request.xxx”,   “timestamp”: “<span class="hljs-number">2018</span>–<span class="hljs-number">07</span>–<span class="hljs-number">21</span>T21:<span class="hljs-number">33</span>:<span class="hljs-number">25</span>Z”,   “locale”: “en-US”,   “originatingRequestId”: “amzn1.echo-api.request.xxx”,   “events”: [     {       “name”: “button_down_event”,       “inputEvents”: [ {         “gadgetId”: “amzn1.ask.gadget.xxxx”,         “timestamp”: “<span class="hljs-number">2018</span>–<span class="hljs-number">07</span>–<span class="hljs-number">21</span>T21:<span class="hljs-number">33</span>:<span class="hljs-number">25.374</span>Z”,         “color”: “<span class="hljs-number">000</span>DD6”,         “feature”: “press”,         “action”: “down”       } ]     }   ] }
</code></pre><p>The logic within the Lambda function for the skill will need to respond to these events, and process functionality accordingly.</p>
<h3 id="heading-buttons-can-change-color">Buttons Can Change Color</h3>
<p>Inside the buttons are a series of LED’s that can be turned off and on. They are bright and the color is very rich.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9gmdYm6OjjrrCzjeM0DLTLJ-RDtTdnB3gfKd" alt="Image" width="800" height="600" loading="lazy"></p>
<p>The buttons can also change colors by altering how the different LED’s are illuminated.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/fr7rACZlz0hBY5apboKduTEjVd7cK8tlXGDz" alt="Image" width="800" height="600" loading="lazy"></p>
<p>Color changing of the buttons is also done within directives in a response object. If you start your skill using the <a target="_blank" href="https://github.com/alexa/skill-sample-nodejs-buttons-hellobuttons">repo for buttons</a>, there are helper functions that make this easy to integrate into your skill.</p>
<h3 id="heading-closing">Closing</h3>
<p>If you’re interested in trying out a game that uses them, please test out my baseball simulation game on Alexa. It’s called “Seventh Inning Stretch” and is an attempt to recreate the fun of old handheld games from the 80’s. It’s a good example of what’s possible using these new accessories.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ACXMJEoX78nZezIBRNITH7S5eSIsL0Jka5z6" alt="Image" width="750" height="1077" loading="lazy">
<em>Example of Alexa Skill that uses Buttons</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How you can use data to discover the secrets of baseball ]]>
                </title>
                <description>
                    <![CDATA[ By ?? Anton de Regt Data can tell lots of stories, and finding the hidden secrets is like finding a needle in a haystack. After finishing my first data analysis course on Udacity, it was time for a real-world project. In this project, I’m going to ex... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/discovering-the-secrets-of-baseball-with-data-56f793852de0/</link>
                <guid isPermaLink="false">66c3493c9972b7c5c7624e34</guid>
                
                    <category>
                        <![CDATA[ baseball ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Feb 2018 22:55:23 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*t6bdAIXvBropF4AMwTP9Jg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By ?? Anton de Regt</p>
<p>Data can tell lots of stories, and finding the hidden secrets is like finding a needle in a haystack.</p>
<p>After finishing my first data analysis course on <a target="_blank" href="https://classroom.udacity.com/courses/ud170">Udacity</a>, it was time for a real-world project.</p>
<p>In this project, I’m going to explore baseball data. To be more specific: batting data for every player that played between 1871 and 2016. You can download the entire dataset <a target="_blank" href="http://www.seanlahman.com/baseball-archive/statistics/">here</a>.</p>
<p>My process:</p>
<ol>
<li>Have a first look at the data</li>
<li>Come up with a question</li>
<li>Wrangle the data</li>
<li>Explore the data</li>
<li>Draw conclusions/predictions</li>
<li>Communicate my findings</li>
</ol>
<p>My goal is to find the secrets of baseball in the data and share it with you, so that you can learn something and improve your game.</p>
<p><a target="_blank" href="https://github.com/antonderegt/data-baseball/blob/master/Baseball%20Project.ipynb">antonderegt/data-baseball</a><br><a target="_blank" href="https://github.com/antonderegt/data-baseball/blob/master/Baseball%20Project.ipynb">data-baseball — A Final project of Udacitygithub.com</a></p>
<h3 id="heading-first-look-at-the-data">First look at the data</h3>
<p>The first step is to import a dataset. For the first look, I am going to display the first five entries to get an idea of what I’m dealing with.</p>
<pre><code><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> pltimport numpy <span class="hljs-keyword">as</span> npimport pandas <span class="hljs-keyword">as</span> pdimport seaborn <span class="hljs-keyword">as</span> sns%matplotlib inline
</code></pre><pre><code># Reading the batting datafilename = <span class="hljs-string">'Batting.csv'</span>batting_df = pd.read_csv(filename)
</code></pre><pre><code># Printing the first five entriesbatting_df.head()
</code></pre><pre><code># Getting some metrics on the home runs, number <span class="hljs-keyword">of</span> games, runs batted <span class="hljs-keyword">in</span> and the number <span class="hljs-keyword">of</span> strikeoutsbatting_df[[<span class="hljs-string">'HR'</span>,<span class="hljs-string">'G'</span>, <span class="hljs-string">'RBI'</span>, <span class="hljs-string">'SO'</span>]].describe()
</code></pre><p>Looking at the table above, it seems batters hit an average of 2.8 home runs in a season with an average of 51 games.</p>
<pre><code>batting_df_groupedby_year = batting_df.groupby([<span class="hljs-string">'yearID'</span>]).sum()homeruns_per_year = batting_df_groupedby_year[[<span class="hljs-string">'HR'</span>]]
</code></pre><pre><code># Plotting the heatmap <span class="hljs-keyword">in</span> reverse order to make it easier to see the increasesns.heatmap(homeruns_per_year.iloc[::<span class="hljs-number">-1</span>])
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*a-xusvHac4NFo_4FVWzYew.png" alt="Image" width="388" height="252" loading="lazy">
<em>Plotting the heatmap</em></p>
<p>Above you can see the number of home runs increase as the years pass. On the left y-axis you can see the year, and on the right y-axis you can see the number of home runs.</p>
<h3 id="heading-questions">Questions</h3>
<p>Before the data will reveal its secrets, I have to ask it a few questions. Here are some examples of questions I can ask the data:</p>
<ol>
<li>Which teams have the most effective batters?</li>
<li>Is there a correlation between Strikeouts and Home Runs?</li>
<li>Who is the best stealer in history (Caught Stealing vs. Stolen Bases)?</li>
<li>Which region produces the best batters (need to merge with another table for that)?</li>
<li>What is the relationship between different performance metrics? Do any have a strong negative or positive relationship?</li>
<li>What are the characteristics of baseball players with the highest salaries?</li>
</ol>
<p>The question I am going to focus on is: which metrics correlate and which metrics do not?</p>
<h3 id="heading-wrangling">Wrangling</h3>
<pre><code># Displaying the batting data <span class="hljs-keyword">for</span> the last ten yearsbatting_last_ten_years = batting_df.groupby([<span class="hljs-string">'yearID'</span>], as_index=False).sum().sort_values(by=<span class="hljs-string">'yearID'</span>, ascending=False).head(<span class="hljs-number">10</span>)batting_last_ten_years
</code></pre><p>The dataset I am using is already very clean. I don’t have to do a lot of wrangling to get to the data I need. Above you can see batting data from the last 10 years.</p>
<h3 id="heading-exploring">Exploring</h3>
<p>In the next code block, I will calculate the correlations between Home runs and all the other metrics. This way we can see which metrics contribute to home runs and which metrics are bad for scoring home runs. For example, I expect batters who play more games to score more home runs. I also expect batters with a high RBI to score the most home runs.</p>
<p>A correlation of 1 between two values is a perfect positive correlation. This means that when one of the two values increases, the other increases as well.</p>
<p>A correlation of -1 is a negative correlation. This means that when one value increases the other decreases.</p>
<p>As the value of a correlation goes to 0, the correlation is very small or non-existent. I will call a positive correlation ++, + or +- depending on the strength of the correlation. No correlation will be 0, and negative correlations will range from -+, — , or — — being a strong negative correlation.</p>
<pre><code>def standardize(data):    <span class="hljs-keyword">return</span> (data - data.mean()) / data.std(ddof=<span class="hljs-number">0</span>)
</code></pre><pre><code>def pearsons_r(x, y):    <span class="hljs-keyword">return</span> (standardize(x) * standardize(y)).mean()
</code></pre><pre><code># It doesn<span class="hljs-string">'t make sense to calculate the correlation between these values and home runsleave_out = ['</span>playerID<span class="hljs-string">', '</span>yearID<span class="hljs-string">', '</span>teamID<span class="hljs-string">', '</span>lgID<span class="hljs-string">', '</span>HR<span class="hljs-string">']</span>
</code></pre><pre><code># Meaning <span class="hljs-keyword">of</span> the column names <span class="hljs-keyword">in</span> the datadictionary = {<span class="hljs-string">'playerID'</span>:<span class="hljs-string">'Player'</span>, <span class="hljs-string">'yearID'</span>:<span class="hljs-string">'Year'</span>, <span class="hljs-string">'teamID'</span>:<span class="hljs-string">'Team'</span>, <span class="hljs-string">'lgID'</span>:<span class="hljs-string">'League'</span>, <span class="hljs-string">'HR'</span>:<span class="hljs-string">'Home Runs'</span>,<span class="hljs-string">'stint'</span>:<span class="hljs-string">'Stints'</span>, <span class="hljs-string">'G'</span>:<span class="hljs-string">'Games'</span>, <span class="hljs-string">'AB'</span>: <span class="hljs-string">'At Bats'</span>, <span class="hljs-string">'R'</span>: <span class="hljs-string">'Runs'</span>, <span class="hljs-string">'H'</span>:<span class="hljs-string">'Hits'</span>, <span class="hljs-string">'2B'</span>:<span class="hljs-string">'Doubles'</span>, <span class="hljs-string">'3B'</span>:<span class="hljs-string">'Triples'</span>, <span class="hljs-string">'RBI'</span>:<span class="hljs-string">'Runs Batted In'</span>, <span class="hljs-string">'SB'</span>:<span class="hljs-string">'Stolen Bases'</span>, <span class="hljs-string">'CS'</span>:<span class="hljs-string">'Caught Stealing'</span>, <span class="hljs-string">'BB'</span>:<span class="hljs-string">'Base on Balls'</span>, <span class="hljs-string">'SO'</span>:<span class="hljs-string">'Strikeouts'</span>, <span class="hljs-string">'IBB'</span>:<span class="hljs-string">'Intentional Walks'</span>, <span class="hljs-string">'HBP'</span>:<span class="hljs-string">'Hit by pitch'</span>, <span class="hljs-string">'SH'</span>:<span class="hljs-string">'Sacrifice hits'</span>, <span class="hljs-string">'SF'</span>:<span class="hljs-string">'Sacrifice flies'</span>, <span class="hljs-string">'GIDP'</span>:<span class="hljs-string">'Grounded into double plays'</span>}
</code></pre><pre><code>strong_positive_correlation = []strong_negative_correlation = []
</code></pre><pre><code>def correlations_for_hr(df):    columns = list(df)    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> columns:        <span class="hljs-keyword">if</span> x not <span class="hljs-keyword">in</span> leave_out:            name_of_metric = dictionary[x]            r = pearsons_r(df[<span class="hljs-string">'HR'</span>], df[x])                        # Calculating the strenth <span class="hljs-keyword">of</span> the correlation            correlation = <span class="hljs-string">''</span>            <span class="hljs-keyword">if</span> r &gt; <span class="hljs-number">0.7</span>:                correlation = <span class="hljs-string">'++'</span>                strong_positive_correlation.append(name_of_metric)            elif r &gt; <span class="hljs-number">0.5</span>:                correlation = <span class="hljs-string">'+ '</span>            elif r &gt; <span class="hljs-number">0.3</span>:                correlation = <span class="hljs-string">'+-'</span>            elif r &gt;= <span class="hljs-number">-0.3</span>:                correlation = <span class="hljs-string">'O '</span>            elif r &gt; <span class="hljs-number">-0.5</span>:                correlation = <span class="hljs-string">'-+'</span>            elif r &gt; <span class="hljs-number">-0.7</span>:                correlation = <span class="hljs-string">'- '</span>            elif r &gt; <span class="hljs-number">-1</span>:                correlation = <span class="hljs-string">'--'</span>                strong_negative_correlation.append(name_of_metric)                            print(<span class="hljs-string">'{} Correlation between Home runs and {}:{}'</span>.format(correlation, name_of_metric, <span class="hljs-string">"%.3f"</span>%r))            print(<span class="hljs-string">'-----------------------------------------'</span>)            print(<span class="hljs-string">'Correlations:'</span>)print(<span class="hljs-string">'-----------------------------------------------------'</span>)print(correlations_for_hr(batting_df))print(<span class="hljs-string">'\n'</span>)
</code></pre><pre><code>print(<span class="hljs-string">'Positive correlations: {}'</span>.format(strong_positive_correlation))print(<span class="hljs-string">'\n'</span>)
</code></pre><pre><code>print(<span class="hljs-string">'Negative correlations: {}'</span>.format(strong_negative_correlation))
</code></pre><p>Output:</p>
<pre><code>Correlations:--------------------------------------------------------------------O  Correlation between Home runs and Stints: <span class="hljs-number">-0.065</span>--------------------------------------------------------------------+  Correlation between Home runs and Games: <span class="hljs-number">0.668</span>--------------------------------------------------------------------+  Correlation between Home runs and At Bats: <span class="hljs-number">0.695</span>--------------------------------------------------------------------++ Correlation between Home runs and Runs: <span class="hljs-number">0.729</span>--------------------------------------------------------------------++ Correlation between Home runs and Hits: <span class="hljs-number">0.703</span>--------------------------------------------------------------------++ Correlation between Home runs and Doubles: <span class="hljs-number">0.725</span>--------------------------------------------------------------------+- Correlation between Home runs and Triples: <span class="hljs-number">0.348</span>--------------------------------------------------------------------++ Correlation between Home runs and Runs Batted In: <span class="hljs-number">0.837</span>--------------------------------------------------------------------O  Correlation between Home runs and Stolen Bases: <span class="hljs-number">0.265</span>--------------------------------------------------------------------+- Correlation between Home runs and Caught Stealing: <span class="hljs-number">0.409</span>--------------------------------------------------------------------++ Correlation between Home runs and Base on Balls: <span class="hljs-number">0.731</span>--------------------------------------------------------------------++ Correlation between Home runs and Strikeouts: <span class="hljs-number">0.822</span>--------------------------------------------------------------------++ Correlation between Home runs and Intentional Walks: <span class="hljs-number">0.753</span>--------------------------------------------------------------------+- Correlation between Home runs and Hit by pitch: <span class="hljs-number">0.497</span>--------------------------------------------------------------------O  Correlation between Home runs and Sacrifice hits: <span class="hljs-number">0.064</span>--------------------------------------------------------------------++ Correlation between Home runs and Sacrifice flies: <span class="hljs-number">0.792</span>--------------------------------------------------------------------++ Correlation between Home runs and Grounded into double plays: <span class="hljs-number">0.767</span>--------------------------------------------------------------------
</code></pre><pre><code>Positive correlations: [<span class="hljs-string">'Runs'</span>, <span class="hljs-string">'Hits'</span>, <span class="hljs-string">'Doubles'</span>, <span class="hljs-string">'Runs Batted In'</span>, <span class="hljs-string">'Base on Balls'</span>, <span class="hljs-string">'Strikeouts'</span>, <span class="hljs-string">'Intentional Walks'</span>, <span class="hljs-string">'Sacrifice flies'</span>, <span class="hljs-string">'Grounded into double plays'</span>]
</code></pre><pre><code>Negative correlations: []
</code></pre><h3 id="heading-reviewing-first-expectations">Reviewing first expectations</h3>
<p>Remember my expectations? I expected the number of games and the RBI score to have a positive correlation with home runs. According to my calculations above, the number of games has a positive correlation with a Pearson’s R of .668. So players who played more games in a season have a higher number of home runs. This sounds very logical, since batters who play more games have more chances of scoring a home run.</p>
<p>My other expectation was that a high RBI would mean a high number of home runs. The correlation between home runs and RBI is big with .837! This again is quite logical, because home runs are able to reward the player with the most RBI points.</p>
<p>Another interesting fact is that there are no negative correlations. So, there is no metric that decreases when the number of home runs increases.</p>
<pre><code># HOME RUNS vs. RUNS BATTED INsns.lmplot(size=<span class="hljs-number">10</span>, data=batting_df[[<span class="hljs-string">'HR'</span>, <span class="hljs-string">'RBI'</span>]], x=<span class="hljs-string">'HR'</span>, y=<span class="hljs-string">'RBI'</span>, x_estimator=np.mean)
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*OgrJ3wEmh75BYlyu71Pn4A.png" alt="Image" width="712" height="712" loading="lazy">
<em>HOME RUNS vs. RUNS BATTED IN</em></p>
<p>The chart above shows how home runs correlate to RBI. You can see the number of home runs of the x-axis and the number of RBI points on the y-axis.</p>
<pre><code># HOME RUNS vs. STRIKEOUTSsns.lmplot(size=<span class="hljs-number">10</span>, data=batting_df[[<span class="hljs-string">'HR'</span>, <span class="hljs-string">'SO'</span>]], x=<span class="hljs-string">'HR'</span>, y=<span class="hljs-string">'SO'</span>, x_estimator=np.mean)
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*imXXUHBOTge6FRDyCyYPpw.png" alt="Image" width="712" height="712" loading="lazy">
<em>HOME RUNS vs. STRIKEOUTS</em></p>
<p>The plot above returns an interesting correlation. It’s the correlation between home runs and strikeouts. The Pearson’s R correlation is .822, being almost as high as the correlation between home runs and RBI.</p>
<p>This correlation was more interesting to me because RBI’s are a direct result of home runs. Strikeouts, on the other hand, have a direct correlation to losing your chance at a home run. How on earth would strikeouts result in more home runs?</p>
<h3 id="heading-how-are-home-runs-and-strikeouts-related">How are home runs and strikeouts related</h3>
<p>To solve this mystery, I started thinking… Maybe the batters who take more risk are more likely to score a home run. Because they swing even on balls that seem hard to hit. So, if taking more risks gives you more home runs, I took a look at risky metrics. Risky metrics are metrics that involve risk-taking, like stealing bases. Let’s have a look at the correlation.</p>
<pre><code># HOME RUNS vs. CAUGHT STEALINGsns.lmplot(size=<span class="hljs-number">10</span>, data=batting_df[[<span class="hljs-string">'HR'</span>, <span class="hljs-string">'CS'</span>]], x=<span class="hljs-string">'HR'</span>, y=<span class="hljs-string">'CS'</span>, x_estimator=np.mean)
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*F6UO9ZsBNxHxcsM9mGs9Xg.png" alt="Image" width="712" height="712" loading="lazy">
<em>HOME RUNS vs. CAUGHT STEALING</em></p>
<p>Above you can see the correlation (.409) between home runs (x-axis) and the number of times a runner gets caught stealing (y-axis). There is a vague correlation, but it’s not enough to make a conclusion. Maybe the risk takers have gotten very good at stealing bases and don’t get caught stealing? Let’s look at stolen bases.</p>
<pre><code># HOME RUNS vs. STOLEN BASESsns.lmplot(size=<span class="hljs-number">10</span>, data=batting_df[[<span class="hljs-string">'HR'</span>, <span class="hljs-string">'SB'</span>]], x=<span class="hljs-string">'HR'</span>, y=<span class="hljs-string">'SB'</span>, x_estimator=np.mean)
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*6MsW8r0ef2wXT-sz_2Eicw.png" alt="Image" width="712" height="712" loading="lazy">
<em>HOME RUNS vs. STOLEN BASES</em></p>
<p>Above you can see the correlation of .265 between home runs (x-axis) and stolen bases (y-axis). This correlation is non-existent. So, taking risks has nothing to do with scoring a home run.</p>
<p>The data alone is not going to reveal the secret of scoring a home run. I need to learn more about baseball to solve this mystery. My next plan of attack was watching YouTube videos to see how high scoring batters behave.</p>
<p>As it turns out, scoring a home run has more to do with fine calculations than taking risks. I saw batters waiting for the right pitch. They’d rather get a strike, hoping the next throw will serve them batter, eh better. An added benefit is that the pitcher tires faster as he has to throw more balls.</p>
<h3 id="heading-conclusionspredictions">Conclusions/Predictions</h3>
<p>To batters trying to improve their home run stats, I have a few suggestions. Step one in getting more home runs is: play more games, no excuses — play! Step two: get some strikeouts. It sounds counter-intuitive, but it increases your number of home runs. The way this works: it blows out the pitcher and gives the batter more time to wait for the best pitch to hit that GRAND SLAM.</p>
<p>For more about the correlation between home runs and strikeouts, read <a target="_blank" href="https://www.mlb.com/news/anthony-castrovince-increasing-strikeout-totals-acceptable-if-a-batter-produces-offensively/c-47432098">this article</a>.</p>
<p>Or this one about <a target="_blank" href="http://www.stack.com/a/pitcher-fatigue">risks of a tired pitcher</a></p>
<p>For more check out <a target="_blank" href="http://ditisanton.com">ditisAnton.com</a> and <a target="_blank" href="https://goo.gl/mBggzD">SIGN UP</a> for my weekly newsletter.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
