<?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 Jeremy Elmani on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Elmani on Medium]]></description>
        <link>https://medium.com/@jeremyelmani?source=rss-7eaa435e9ef0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WArSkWbAqYcRxmROzNw6Hg@2x.jpeg</url>
            <title>Stories by Jeremy Elmani on Medium</title>
            <link>https://medium.com/@jeremyelmani?source=rss-7eaa435e9ef0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:19:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeremyelmani/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[What is Reinforcement Learning?]]></title>
            <link>https://medium.com/@jeremyelmani/what-is-reinforcement-learning-53921386f8a7?source=rss-7eaa435e9ef0------2</link>
            <guid isPermaLink="false">https://medium.com/p/53921386f8a7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-driving-cars]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Jeremy Elmani]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 18:05:47 GMT</pubDate>
            <atom:updated>2026-01-11T18:05:47.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever seen one of those Waymo cars driving down the street with no driver? Have you heard of the AI that can beat the best chess players and the best Go players? You might be wondering how an AI can accomplish these tasks. The answer is Reinforcement Learning.</p><p>The goal of a reinforcement learning algorithm is to create a policy that can determine the optimal action in any given state. Let’s define these terms for what they mean in an RL context.</p><h3>State, Action and Policy</h3><p>A state in this context consists of all relevant factors in determining an action at that current moment in the environment. In a chess game, this would be the position of all pieces on the boards. For an autonomously driving helicopter, this might be its current position (x, y, z coordinates), the different angles of the helicopter, its current velocity, etc.</p><p>An action is how we get from one state to the next. In a chess game, this is moving a piece. In a self driving car, this would be pressing on the gas or the brake or steering the wheel. The policy is how we get from state to action. The learning algorithm creates a policy that can take a state (in practice a vector of numbers that represents the variables in the current environment we talked about earlier, like the positions of all the chess pieces) and outputs the optimal action.</p><p>Now you might be asking, how does a RL algorithm quantify what is an optimal action? How does it know what a good move in chess is?</p><h3>Rewards and Returns</h3><p>Every state will have a reward attached to it in the form of a number. Let’s use the Mars rover as an example. The goal of the Mars Rover is to find interesting samples from Mars. An optimal action is one that results in the Mars rover finding an extremely interesting sample. Any state (in this case position on mars) that results in an extremely interesting sample would have a very high reward, say 100. Another location that has an interesting reward (but not that interesting) might still yield a reward but not as high, say 40.</p><p>This brings us to the concept of the return. Let’s say we have two policies. One gets the mars rover to the 100 reward in 3 state changes and the other gets the mars rover to the 100 reward in 6 state changes. Is one of the policies better? Shouldn’t we be able to quantify the difference between these two policies? How do we maximize the amount of reward in the least amount of state changes?</p><p>The answer is utilizing the discount factor. We choose a value for the discount factor that is less than 1, and for each state change we multiply the reward by the discount factor taken to the power of the number of steps. We also call the discount factor gamma (𝜸)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puBIMiMcfr4jbtpgz-fMHg.jpeg" /></figure><p>Now that we have the needed vocabulary and concepts, how do we represent this mathematically? And how do we make determinations of what the optimal action is in any given state?</p><h3>State Action Value Function</h3><p>The state action value function, also called the Q function, is a function of the current state and any possible action from that state. It returns the value of the reward if you start in that state, take the given action, and then behave optimally after that. The idea is to be able to evaluate any possible action at that state.</p><p>The state action value function is represented mathematically as <em>Q(s, a)</em> where s is the state and the action is a. The Bellman equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*RkMGfVnTCqRO_Aw1MsEYgg.png" /><figcaption>Bellman Equation</figcaption></figure><p>Let’s break this down: s’ represents the next state that is a result from taking the original action a and a’ is the next action you take once you’re in s’. This states that Q(s, a) (the return of any action from a state) is equal to the current reward <strong><em>R </em></strong>plus the maximum possible return value of Q(s’, a’) multiplied by the discount factor gamma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SefU0Du9foAJL9l6tFpoxw.png" /></figure><p>How do we actually determine what the Q function is? Now that we have this foundation, we can learn the algorithm for how we can use neural networks to to learn the state action value function.</p><h3>Deep Reinforcement Learning (Deep Q Network)</h3><p>In a deep Q network we use a neural network for our Q function. The algorithm for a deep q network is as follows:</p><ul><li>We initialize 2 neural networks each with random weights to start with. One is the neural network we continuously learn on called the Policy Network, the other is our target network which we use to perform inference when performing gradient descent (explained more later)</li><li>We perform random actions (it’s actually more sophisticated than this, look up the epsilon-greedy policy if interested) in the environment many times and store the relevant info (starting state vector, action performed, resulting state vector and reward) in what we call the replay buffer.</li><li>Each set of info in the replay buffer becomes a training example for our neural network. Once we have enough examples in the replay buffer, we use the bellman equation to train our neural network. Our X input into the neural network is each state and our associated y target is the calculated return composed of: the immediate reward in the given state plus the optimal return from the next state(which we calculate from our target neural network) multiplied by the discount factor</li><li>As our learning network gets better, we intermittently update the weights of our target network so we have an updated target network that can benefit from the training. We separate out the two networks this way so during training, our target y isn’t constantly changing. This would make gradient descent not work as well</li></ul><p>Eventually, given enough training data, we have a neural network that can take in a state and any possible action and return the value of the Q function for that state and action. From there, for our mars rover or AI chess player to perform optimally, we simply pick the highest value returned from our neural network out of all the possible actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvPjlKAfGNJiCtgKVbpIBw.png" /><figcaption>Deep Q Network</figcaption></figure><h3>Conclusion</h3><p>What you just learned is the underlying logic behind a Waymo navigating a busy intersection or an AI beating a gradmaster in chess. Reinforcement learning the bridge between deep learning and AI actually performing actions in the real world. In a couple years when a robot is making you pancakes, you can think back to this post to understand how it works.</p><p>If you enjoyed this article, <a href="https://x.com/jerlearnsml">follow me on twitter</a> for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53921386f8a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Neural Network? A Beginner-Friendly Guide (with Code You Can Understand)]]></title>
            <link>https://medium.com/@jeremyelmani/what-is-a-neural-network-a-beginner-friendly-guide-with-code-you-can-understand-5d796143aabe?source=rss-7eaa435e9ef0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d796143aabe</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jeremy Elmani]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 23:01:48 GMT</pubDate>
            <atom:updated>2025-11-14T23:01:48.802Z</atom:updated>
            <content:encoded><![CDATA[<p>They’re changing the world and taking our jobs. But what actually are neural networks? You might be scared to ask at this point. I’ll explain what they are both as a high level overview and a lower level, technical explanation. I’ll also show you a small, simple, <a href="https://github.com/jelmani/jeremys-neural-network">stripped down neural network</a> I wrote that helped me solidify these concepts.</p><h3>The Concept of a Neural Network</h3><p>The idea of a neural network comes from (as you might have guessed) neurons in the brain. Billions of neurons in the brain are connected to each other in vast, complex networks. This complexity is how we are able to form thoughts and have different personalities. Neurons communicate with each other via electrical signals that get passed from one neuron to another. There are 3 parts to a neuron: the cell body, the dendrites and the axons. The dendrites receive signals from other neurons and the axons transmit signals to other neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*vQy5aZlq5Af0T5fx_p-XBQ.png" /><figcaption><a href="https://qbi.uq.edu.au/brain/brain-anatomy/what-neuron">https://qbi.uq.edu.au/brain/brain-anatomy/what-neuron</a></figcaption></figure><p>This is where the inspiration for the neural network algorithm comes from in machine learning. In machine learning, neural networks are formed out of many interconnected nodes called neurons or units. This interconnected structure inspired from neuroscience allows neural networks to learn complex patterns in order to accomplish complex tasks like image classification or text generation.</p><h3>Neural Networks as a Machine Learning Algorithm</h3><p>Imagine you want a machine learning algorithm to detect if an image contains a car. While this is an easy task for a human, this is quite a complicated task for a computer. Imagine if you had to break down this task in a computer program. How would you break up the tasks? Maybe you would say something like look for an image that has 4 circles on the bottom, with square like shapes for the doors and windows with circles for the headlights. Pretty cumbersome right? This is the cool thing about neural networks: given a task like this (and enough training data) a neural network will learn how to decompose a task like this into manageable chunks that are each handled by neurons that are organized into layers.</p><p>But what is a neuron in this context? As fancy as the term neural network sounds, at its core a neural network is just a big math equation. Specifically sequences of matrix/vector multiplications. Each neuron in the network is its own simpler mathematical function, such as a <a href="https://medium.com/@jeremyelmani/predicting-ride-time-of-citibike-riders-from-distance-rode-an-intro-to-linear-regression-and-da8557202070">linear regression</a> or a <a href="https://medium.com/@jeremyelmani/nba-win-loss-predictor-with-64-accuracy-how-to-write-your-own-logistic-regression-model-b476bb747712">logistic regression</a>. Each neuron can take an input x and compute an output y. The neuron’s output is modified by its parameters. Parameters are the adjustable numbers the network learns to tune its predictions. Each layer in a neural network contains a certain amount of neurons (the amount is decided beforehand usually fairly arbitrarily). The neural network takes in an input (say an image in this example). Each neuron in the first layer takes the input and computes an output and all the outputs from each neuron in the layer is passed along to the next layer. Note that neural networks can only work with numbers. Anything else (images, text, sound) must be converted into numerical form first.</p><p>To recap, a neural network is composed of multiple layers. Each of the layers are composed of multiple neurons. Each neuron is a little mathematical function that takes in an input X and computes an output y. The neural network is initially given an input, say an image for example. The image is converted into numbers based on the rgb values of each pixel in the image. These numbers are given to each of the neurons in the first layer, some math is performed, the outputs of all these mathematical functions are fed forward from layer to layer until the last layer that outputs our desired value, in this case a probability of the image having a car.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*bSA1ISAxYeyRtnsL0BWRVw.png" /><figcaption><a href="https://www.ibm.com/think/topics/neural-networks">https://www.ibm.com/think/topics/neural-networks</a></figcaption></figure><p>So we have this image that may or may not contain a car. We feed the image into the neural network and each layer and each neuron learns (on its own through training) its own individual task. The first layer in the network might first be concerned in detecting curves in the image. Each neuron in that layer might be responsible for determining if a certain section (say a 4x4 pixel area of the image) contains a curve.</p><p>The next layer takes that information and might determine where in the image contains circles. Each neuron might take on a larger segment of the image and determine if there was a circle in that segment. It goes on like this through the layers until the output layer, the last layer, uses the information from the previous layers to determine if there is a car in the image.</p><p>This is the power of neural networks. They are able to learn what features they need in order to complete any given task. This is it for the high level overview, I’ll dig a little deeper into the details now.</p><h3>Forward Propagation and Activation Functions</h3><p>In order to make a prediction (or an inference) we use forward propagation in a neural network. This is the process of taking an input, processing it through all the hidden layers, and coming out the other side as our prediction. Each layer in a neural network can have a different activation function. An activation function is what determines if the neurons in this layer will be a logistic regression, a linear regression, or something else.</p><p>If z is the product of our input and our parameters, then we put z through our activation function to get the final output of the neuron. Examples of activation functions are a linear function (this simply returns z so it is really the absence of an activation function), sigmoid (for logistic regression), softmax (for multi class classification), or ReLU. ReLU is just max(0, z). The ReLU activation function normalizes all negative values of z to zero, introducing non-linearity into the model. This non-linearity is critical because it allows the neural network to learn and compose complex relationships between inputs and outputs rather than being limited to a purely linear mapping. The standard convention is to use ReLU for our hidden layers and choose an activation function for our output layer based on the nature of our desired output (sigmoid for a binary classification problem, softmax for multiclass, linear for predicting a number, etc).</p><p>For our image of the car, imagine it is a 20x20 pixel image that we have unraveled into a 400 element vector. This vector represents our input vector with 400 features (each pixel). Note that this represents a single training example for the purposes of this explanation. Let’s say our neural network is composed of 2 hidden layers. The first has 25 units, the second 15 units. Since we have a binary classification problem (presence of a car in the image) our output layer will have a single unit with a sigmoid activation function. If this was a multi-class classification problem (eg what brand of car is present with some finite number of possibilities) then our output layer would have a neuron for each possible category of the classification. In other words, say we were classifying the car into 6 possible brands, we would have 6 neurons in the output layer each of which would output the probability that the car is one of the 6 possible brands.</p><p>So let’s say we have an image and we would like our trained neural network to detect the presence of a car. We represent the image as a 400 element vector of numbers. We feed our input into our first layer that has 25 neurons. Each of our 25 neurons will have a parameter vector w that will be of length 400 (since the input is 400) and a scalar b for the bias (<em>y = wx +b</em>). This means that our first layer’s parameters is a matrix w of shape (400, 25) and a vector b of shape (25,). We can say that in general that for any given layer, the parameter W’s shape will be (size of input, size of output). We are feeding 400 feature vector into the layer and the layer has 25 neurons so the output will be 25 numbers, therefore (400, 25). The parameter b will generally b a vector of shape (size of output). Remember the size of the output is equal to the amount of neurons in the layer, since each neuron outputs one number.</p><p>We perform our matrix multiplication and add our bias (<em>wx + b</em>) and run the product through our activation function (ReLU in most cases) and produce a vector of length 25. This becomes the input for our next layer. Our parameter matrix W will be of shape (25, 15) and our vector bias <em>b</em> will be of shape (15,). Same as before we perform our matrix multiplication and add the bias and run it through the activation function and pass it along to our final layer. Our final output layer only has one neuron so our parameter vector w will be of shape (15,) and we will have scalar <em>b</em>. We compute z and, again since this is binary classification, run z through the sigmoid to finally get our probability of the presence of a car. In our neural network from scratch, we can see that this forward prop process can be coded quite simply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*ipGPst9V9wxHnkDyvY0qgw.png" /></figure><p>Where the output method computes <em>wx + b</em> and runs it through the activation function.</p><p>This is it for forward propagation! You now understand how a neural network performs inference. But how do we train a neural network?</p><h3>Backpropagation</h3><p>As you might recall, machine learning algorithms can use gradient descent for learning by updating their parameters by the derivative of the cost function. The derivative is like a map that can tell us how off our parameters and which direction to update them. This concept holds true in neural networks. The difference is that in neural networks we have multiple layers of parameters that are separated from the output and therefore the cost function. How would we compute the gradient of the parameters in the first layer in a 10 layer neural network? How can we do that efficiently? The answer is back propagation.</p><p>Back propagation is the process by which the error of the output of the entire neural network is passed along to all of its layers and all of its parameters. If forward propagation is sending signals forward to make a prediction, think of backpropagation of sending error backwards in order to learn. This is how it’s done in practice.</p><p>First we compute the gradient of our cost function with respect to the activation from our output layer. In other words, how wrong is the output of our neural network and how should we modify the output in order to reduce our wrongness? We take the gradient and pass it to our last layer (remember we’re going backwards). The last layer takes the gradient and (using the chain rule in calculus) uses it to compute the derivatives of its own parameters with respect to the cost function and the derivatives of its input from the previous layer to the cost function. Put another way, the layer figures out how off its own parameters are and updates accordingly and then it figures out how wrong the input from the previous layer is and then passes it up the network to the previous layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFntqCqy1WEM9FdTKYtRlQ.jpeg" /><figcaption>Forward prop passing along activations in purple, back prop passing back derivatives in blue</figcaption></figure><p>The previous layer does the exact same thing. It takes the gradient of its output with respect to the cost function and uses that to update its own parameters and compute the gradient of its input (the output from the previous layer).</p><p>To put it broadly, the gradient is passed backwards from layer to layer. Each layer is given the gradient of its output, uses that to compute and update its parameters, and then computes the gradient of its input (the previous layer’s output) and hands it off to the previous layer. This way each layer in the network is able to update its parameters efficiently. Doing it this way also allows us to save a massive amount of compute time, as we can simply pass along the gradient of the layer’s output and use the chain rule instead of having to compute all of the parameters in the network individually.</p><p>You can get a peak at my implementation here so you can see it in code. The fit function of the network calls the backward function on each layer. The backward function takes in the derivative of its activation and returns the derivative of the activation of the layer before. It also internally updates its own parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*TdFCnWkh8kcSLg9g09o9gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*PXqmTTiGsftxMZzfZcYWDg.png" /></figure><h3>Wrapping up</h3><p>Congratulations! You now know what a neural network is! So the next time you’re asking ChatGPT for life advice, remember you’re getting advice from a big ol’ matrix multiplication.</p><p>Check out my simple neural network I wrote from scratch <a href="https://github.com/jelmani/jeremys-neural-network">here on github</a> and <a href="https://x.com/jerlearnsml">follow me on twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d796143aabe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NBA Win-Loss Predictor with 64% Accuracy: How to Write Your Own Logistic Regression Model]]></title>
            <link>https://medium.com/@jeremyelmani/nba-win-loss-predictor-with-64-accuracy-how-to-write-your-own-logistic-regression-model-b476bb747712?source=rss-7eaa435e9ef0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b476bb747712</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[nba]]></category>
            <dc:creator><![CDATA[Jeremy Elmani]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 00:15:08 GMT</pubDate>
            <atom:updated>2025-10-23T00:15:08.030Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve finished the first course in Andrew Ng’s Machine Learning Specialization! The last course was on Logistic Regression. For my capstone project, I went back to the NBA. This time I used logistic regression and the fantastic <a href="https://github.com/swar/nba_api/">NBA API</a> to predict the winner of an NBA game. I was able to achieve ~64% accuracy in my testing! <a href="https://github.com/jelmani/nba-game-predictor">You can check out the project here.</a></p><h3>Logistic Regression</h3><p>Logistic regression is quite similar to linear regression but with some key differences. In Linear regression, our goal was to find a function that can predict a number based on some features. In graphical terms, we wanted to create a line that maps to our data so we can use it to predict new values based on our features. In logistic regression, our goal is to predict the probability of a binary outcome. So instead of mapping a line to continuous values we map our input values to a curve that separates our data points into two categories. Put another way, in linear regression we optimize for a line that minimizes the distance between our data points and the line. In logistic regression, we optimize for a line/curve that best separates our data into two categories. Our line in logistic regression maps our feature inputs to a probability between 0 and 1. The way we are able to do this mathematically is the sigmoid function.</p><h4>Sigmoid</h4><p>Remember, our original function for a line is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*bAgRHvDnHqtfqhEB0DPDcw.png" /></figure><p>Where w is our parameter (vector or scalar) and b is our bias. Since we are still creating a line (or a curve in the case of polynomials) we still use this same function. Except in logistic regression we need the output to be between 0 and 1 so its in the form of a probability. This is where the sigmoid comes in. The sigmoid function is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*VP5aM0j9xFDMhtJxBt54bQ.png" /></figure><p>Where z is the output of our original function of a line. Graphically, it is an s shaped curve that levels out so that no matter the input the output is between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*2fLT2OdGIRvqbf1a1UBvew.png" /><figcaption>Credit: wikipedia</figcaption></figure><p>We then choose a decision boundary (usually 0.5) so that if the output our function is greater than 0.5 than we consider it a prediction of 1 (true/yes/positive) and if its lower than 0.5 its a prediction of 0 (false/no/negative)</p><p>Say we’re trying to predict whether or not a tumor is cancerous based on images from a medical scan. If the output of our model is 0.7 for a given image, that means our model is 70% sure the tumor is cancerous. If our decision boundary is 0.5, then we would consider this a prediction of a cancerous tumor.</p><h4>Cost function and Gradient Descent in Logistic Regression</h4><p>Just as before, we use the cost function to figure out how off our model is, and we use the cost function’s derivative to update our parameters in gradient descent. In Linear Regression, we used the mean squared error for our cost function. That made sense for linear regression since we’re trying to get a line that maps to our data as close as possible. For logistic regression since we have binary output, we need a more appropriate cost function. The logistic loss function for a single training example looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*XpoY6fuwkXISaKTO35STsQ.png" /></figure><p>Where y is the actual value (1 or 0) and y hat is our predicted probability. This loss function for logistic regression is perfect since if our y actual value is 1, the loss function approaches 0 as our predicted probability approaches 1 and when our y actual value is 0 the loss function approaches 0 as our predicted probability approaches 0. This makes perfect sense right? This basically gives us a higher loss when our model is incorrect and a lower loss when our model is correct, exactly what we want out of the loss function. The cost function for our model given m training examples is the average loss across all training examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*r9uDfbYUhNaFHeakCAT8Xw.png" /></figure><p>The cost function here is negative because logs of probabilities are negative, and we want a <em>positive number</em> to minimize. The next step as we remember from linear regression is to take the derivative of the cost function to update our parameters in gradient descent. The good news is the derivative of the logistic cost function will look quite familiar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*IVkyuKlIFlyI_PzFD_AYrA.png" /></figure><p>The derivative of the logistic cost function works out to be exactly the same as in linear regression! The only difference is that our model output (f of w,b) is our model output for logistic regression which is our function of a line filtered through the sigmoid. The rest of the steps are the same as in linear regression. We update our parameters with the derivative until we reach a local minimum of the cost function. Now to the implementation!</p><h3>Getting out of Jupyter Notebook</h3><p>For this project I wanted to start getting comfortable getting out of jupyter notebook and creating my model in python files with proper classes and project organization. I used Jupyter Notebook to initially wrangle the data, engineer features, create my model, etc and then converted everything to python classes. You can <a href="https://github.com/jelmani/nba-game-predictor">check out the project on github</a> but I’ll go through some of parts here.</p><h3>Calling the NBA API and Preprocessing</h3><p>The first step is my data ingestor class. This is where I call the NBA API and do some simple pre processing. I filter out the WNBA, G league, etc based on team ids. I convert the dates from strings to datetime objects. I get rid of things like summer league and preseason because it would add irrelevant noise to the data since these games aren’t taken as seriously. The class is set up to take in start/end dates of games for future proofing but for now, we just get all games the NBA API will send (the limit is about 30,000 which is about 5 years worth of games). After the preprocessing I return a dataframe that is sent to the feature extractor to do the real work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*kp5_YRKQVvY6kcj-VTqGgA.png" /></figure><h3>Feature Engineering</h3><p>This was the most difficult part of the project. For this current iteration, all the features are different season to date stats. Things like possessions, offensive rating, defensive rating, plus/minus. The NBA API returns a traditional box score for each game so getting my season to date stats required some manipulation of Pandas dataframes.</p><p>Ultimately, I wanted a dataframe where each row is a game and each column is a feature, the rolling season to date averages from the previous games. The problem is that we need a joined game dataframe to calculate our initial stats (eg offensive rating and defensive rating for each game since some of them depend on the opponent). Then we need an unjoined (2 row per game) dataframe to calculate the rolling averages (so we can easily just group by team and sort by date since there is a row for each team). Then we need to join them back for our final feature dataframe. This was a great way to improve my Pandas skills to say the least!</p><p>The feature extractor class handles all this and returns either a training set, a test set, or a feature set for predicting the outcome for one game based on a given home and away team. It hands this over to the modeling class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC2hbNNMtocu-25PeOexfw.png" /></figure><h3>Modeler</h3><p>This class was my implementation of logistic regression. I compute the cost, gradient, and gradient descent manually. I have public methods for fitting the data, predicting, and testing the model. This was also my first time implementing a regularized model. Regularization is a technique to reduce over fitting. The idea is that you add a limiter to the parameters w in the cost function, so that when calculating the gradient, we don’t allow the parameters to get too large and sway the model too much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*ftL860Nyp0SEYOCnDp8HrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*HLIr7nJwHmnb4dMjReWIWg.png" /></figure><h3>Putting it all together and results</h3><p>After training my model hits around 64% accuracy which isn’t a bad start and I’ll take it as a win. For reference, the most accurate models I’ve seen hover around 68–70% so not too far off. I hope to get there in the future after some fine tuning. Finally in the game predictor file I call all my classes and predict the outcome of a game based on the user input. I encourage you to try it out. <a href="https://github.com/jelmani/nba-game-predictor">Check it out on github</a> and try it yourself! <a href="https://x.com/jerlearnsml">Hit me up on twitter</a> if you use it to make some money (but I don’t condone gambling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*VCesvAWMaJ80PV6GS_avuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WbUcAgZyw-b74v6Iih0zQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b476bb747712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Noisy Data: Vectorization and Feature Engineering the NBA with Multiple Linear…]]></title>
            <link>https://medium.com/@jeremyelmani/dealing-with-noisy-data-vectorization-and-feature-engineering-the-nba-with-multiple-linear-358d2fb9254b?source=rss-7eaa435e9ef0------2</link>
            <guid isPermaLink="false">https://medium.com/p/358d2fb9254b</guid>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jeremy Elmani]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 21:21:57 GMT</pubDate>
            <atom:updated>2025-10-02T21:21:57.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dealing with Noisy Data: Vectorization and Feature Engineering the NBA with Multiple Linear Regression</h3><p>As a part of my effort to create a capstone project for every section of Andrew Ng’s amazing Machine Learning Specialization course, my second project was a Linear Regression with multiple input variables and dealt with the NBA. I wanted to be able to predict how many points a player will score in any one given game based on some chosen statistics from previous games. Even though my result wasn’t quite what I wanted (yet), I learned a lot along the way. You can check out the project <a href="https://github.com/jelmani/nba-predictor">here</a>.</p><h3>Data Wrangling</h3><p>First step was to gather my data. I used <a href="https://www.basketball-reference.com/">https://www.basketball-reference.com/</a> and took a look at the data to try and come up with some good features. I settled on a mix of rolling averages of the previous 5 games (things like last 5 games points average, minutes played average, field goals attempted etc), days rest, last game minutes played, and some statistics from the opposing team (pace, defensive rating, etc).</p><p>I wanted to create a generic function that can simply take the relevant CSVs from basketball reference and return my feature set DataFrame and my target output for my training data. This way when i go on to the validation and test phases its simple to just drop in the data into the function and get it back in the form I need.</p><p>You can check out the <a href="https://github.com/jelmani/nba-predictor">project on GitHub</a> to see all the steps but I’ll go through one of the interesting things I learned here:</p><p>A big chunk of the features were rolling averages of various stats. I originally computed these with a for loop where I would iterate over the DataFrame and compute the rolling average of each of the statistics manually. After doing some research however, I found a much cleaner more vector friendly way to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*loE9kopS0H_soUhQvqHhyQ.png" /></figure><p>The rolling function from Pandas makes it super simple to compute a rolling average in one line. I take the relevant column of the DataFrame, shift it forward by 1 so as not to include the given game at that position in the average and call rolling with 5 as the window and minimum period. This gives us a rolling average of the relevant statistics in one line, cool!</p><h3>Multiple Linear Regression with Vectorization</h3><p>One of the purposes of doing this project was to practice implementing a linear regression model with multiple feature input variables. The cool thing is, thanks to vectorization, the process is not much different than implementing a univariate (single variable) linear regression model.</p><p>Recall from the last post that our linear regression model is simply the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*bAgRHvDnHqtfqhEB0DPDcw.png" /></figure><p>Where x is our feature variable, w is our parameter associated with that variable and b is our bias. Before we only had one feature variable, so the math was quite simple. Now with multiple features the math becomes a little more complicated since each feature variable has an associated parameter with it (n represents the number of different features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*tQoH242hyvslJTUB0p6sGA.png" /></figure><p>So our code must get a lot more complicated right? Fortunately not! Our code doesn’t have to change much because of the idea of vectorization. Vectorization is the concept of putting our features variables into NumPy arrays and performing operations on them as a whole in order to save computational speed, efficiency and code clarity. We can use the dot product between our feature matrix (m number of rows of training examples and n features) and our parameter vector (n number of features so n parameters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*0351aXyY8c_yaf0jRhF53g.png" /></figure><p>Pretty similar to our single feature linear regression right? Now you might be asking yourself, what is the dot product? The dot product (as opposed to element-wise multiplication which simply multiplies the corresponding elements in each matrix) does exactly what we need in this case. It takes our parameter vector and broadcasts it across all the training examples of our feature matrix. So we end up with a vector where each element is the result of w1x1 + w2x2… for each of the training examples and then we simply add b to our vector (b is also broadcasted across the vector and the value is added to each element. <a href="https://www.youtube.com/watch?v=ZUeSxQ67wD8">Here’s a good video on this topic if you want more details</a>.</p><p>Similarly, we can apply this concept to our feature scaling. We can apply z-score normalization to our whole feature matrix with this simple function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*tR-rfYuqp758nNoUDdv_eQ.png" /></figure><p>Where the axis parameter set to zero (which represents the rows) tells numpy to collapse the rows and get our mean/std column wise. Meaning get the average and the standard deviation for each of our features.</p><p>The rest of the project (computing the cost and gradient descent, etc) was not very different from our previous one thanks to vectorization. Now lets see how good our model is by using data from the 2024 season to test our model. I take the 2024 data and put it in our cost function, convert it into units relative to our data and then compare that to the standard deviation of the target output data.</p><h3>Results</h3><p>Comparing it to the standard deviation of the target output data gives us an idea of if our model is learning anything. Since the standard deviation is the measure of how much the data is spread out around the mean, it gives us a baseline benchmark based on if we just guessed how much points the player will score from the mean. Lets see how we did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gPgRGUmsnlZ7Bwwm2Rciw.png" /></figure><p>Oof not great. Our cost was slightly higher than the standard deviation. This means our model is not performing well. This could be due to many reasons such as choice of features (including possibly introducing polynomial features), our data not being clean (e.g. using whole season data for opposing teams for each game when really it should be season to date data to avoid data leakage), an unrealistic problem statement, needing a more sophisticated algorithm and more.</p><p>Sometime in the future I’ll come back to this project and work on fine tuning it to get accurate results. When I learn more advanced algorithms I can come back and apply them to this project and see if they make a difference.</p><p>Even though I didn’t achieve the results I wanted; this project taught me a lot about feature engineering, vectorization, writing modular generic code multiple linear regression. The next topic for me to learn is classification with logistic regression!</p><p>Remember to <a href="https://x.com/jerlearnsml">follow me on twitter/x</a> for more updates and observations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358d2fb9254b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting ride time of CitiBike riders from distance rode: An intro to Linear Regression and…]]></title>
            <link>https://medium.com/@jeremyelmani/predicting-ride-time-of-citibike-riders-from-distance-rode-an-intro-to-linear-regression-and-da8557202070?source=rss-7eaa435e9ef0------2</link>
            <guid isPermaLink="false">https://medium.com/p/da8557202070</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Jeremy Elmani]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 22:18:02 GMT</pubDate>
            <atom:updated>2025-09-17T22:18:02.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting ride time of CitiBike riders from distance rode: An intro to Linear Regression and Gradient Descent</h3><p>I’ve started my journey on learning Machine Learning and have started with Andrew Ng’s Machine Learning Specialization. I’ll be sharing what I learn here along with some capstone projects of my own creation for each of the modules.</p><p>For my first project, I wanted to use data from CitiBike to predict how long a ride in NYC with an electric bike would take given the distance traveled in meters. I implemented the linear regression model and the gradient descent manually. I’ll walk through linear regression and gradient descent here and use this project as an example. Check out the full project <a href="https://github.com/jelmani/CitiBike-ML/tree/main">here on GitHub</a></p><h3>Data Wrangling</h3><p>The first step was setting up our data to be useful before we make our model. The raw data from CitiBike required some conversions. Things like subtracting the start/end times of each ride to figure out the total seconds for each trip, using the Haversine formula to figure out the distance in meters from the latitude and longitude of the start and end points. I also eliminated some outliers based on the speed of the ride to eliminate noise from the data (eg. rides that lasted a long time but didn’t travel anywhere which are most likely issues with docking the bike or other technical issues). Eventually we had our scatter plot of our training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGz6z-KTbZLXfMTFMjiMYw.png" /><figcaption>Plotting our cleaned up CitiBike data</figcaption></figure><h3>Linear Regression</h3><p>The idea of any supervised machine learning model is to take your training set (the dataset you’re using to train your model) complete with your features and your target values and put it into a learning algorithm in order to come up with a function that can take an input and accurately predict the outcome. The idea is to come up with a line that can neatly map across our data and give us a function that allow us to predict new values.</p><p>First some math notation:</p><p><em>x</em> — refers to our input variables/features. In our CitiBike project, our single feature variable is distance between the two stations in meters</p><p><em>y</em> — refers to our output or target variable. In our CitiBike project, this would be the time in seconds that a given ride would take given our input variable x (distance between the two stations)</p><p><em>m</em> — refers to the total number of training examples. This would be the number of rides from the CitiBike data used to train our model</p><p>In linear regression, the goal is to come up with a function that can predict the desired target value from the given feature inputs. In math terms:</p><p><em>f(x) = wx + b</em></p><p>Which you might recognize as the line function. Here, x represents the feature inputs, w represents the weight attached to that feature input. Think of it as how important that particular feature input is to the model’s outcome. b is the bias, which can be thought of as like a base starting value to the model’s output. w and b are the parameters of our Linear Regression Model. This is our model. You can see it in code here for our CitiBike project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*7wcFSSFAUCreY-ZweaYuuw.png" /></figure><p>The goal is to find values of w and b that can reliably predict the desired target value from the given feature input x. Or in another way, find values of w and b that minimizes how wrong our machine learning model is.</p><h3>Cost Function</h3><p>This brings us to the cost function. The goal of the cost function is to find values of w and b that minimize the distance (error) between y (the predicted value) and y (the target value). We need a way to measure how good our machine learning model is right? What the cost function does is give your machine learning model a single number that represents how “off” it is from the target values. This function is represented in mathematical terms like: J(w, b). Where J represents the cost function in terms of the parameters for w, b For Linear Regression, we use the Mean Squared Error which looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*0p4gwEYmH_9V-UX9kwJlVA.png" /><figcaption>Cost Function for Linear Regression</figcaption></figure><p>This looks quite complicated if you’re new to math notation but it is actually quite intuitive. This guy: ∑ simply means the sum of the function that follows it for each value i between 1 and m. Remember m represents the number of training examples. So what this cost function is saying is for each training example (this would be for our CitiBike project, a single pair of distance in meters and length of trip in seconds) take the output of our function given that particular training example minus the actual target value for that example. We then square that value which accomplishes two things: gets rid of negative values and magnifies the effect of larger outliers. For each training example, we take this value and sum them up and divide by 2m.</p><p>This is basically taking the average of the squared error (sound familiar?) except for the extra 2. The reason for that will be explained later but know that it’s just for convenience. Back to our CitiBike project, you can see how I computed the cost here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*anuFGzkB2R43sWdi4dLYjg.png" /><figcaption>MSE Cost function implemented in Python</figcaption></figure><p>Not too bad right? If we want to figure out how off our model is, this is pretty intuitive. It is just the average amount the model is off by.</p><p>Now remember the goal is to get values of our parameters so that the cost function returns as low a number as possible. But how do we take this info and actually improve the accuracy of our model?</p><h3>Gradient Descent</h3><p>Gradient descent is how we go from cost function -&gt; more accurate model. We use gradient descent to figure out the optimal values of our parameters that gets us the lowest value of the cost function as possible. Here’s how it works:</p><p>So we have our cost function right? If we give our cost function any given parameters (in our case here (w and b) it’ll give us the error. Let’s graph our cost function and let’s forget about our parameter b for a second so we can graph it in a 2D space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*8jP0WFpN8g7r7t32WL8DRQ.png" /><figcaption>Graphing an example Cost Function</figcaption></figure><p>We want to get into that valley right? That’s where our model is most accurate. Remember in practice it will almost never be as simple as shown here, you can have thousands of parameters in your model and you won’t be able to simply look at a graph like this and choose where the cost is at a minimum, this is just for educational purposes.</p><p>So let’s say we start out with a random value of w. How do we know which direction to go so we’re going towards that valley? And by how much we should go? Fortunately there’s a concept from calculus that can answer these questions: the derivative.</p><p>I won’t pretend to be an expert on calculus here, but I can give a simple explanation for what the derivative is. For any given function you can figure out the derivative of that function which tells you the slope of the tangent line for any point along your original function. Or in other words, at any given point in the original function you can use the derivative to figure out the direction (is the output of the function increasing or decreasing) and by how much (a slope that is very high means the value is increasing rapidly at that point, a low slope means its more stable).</p><p>To explain the concept further here is an example. Say we have a car driving down the highway. We graph how long he’s been driving in hours to distance traveled in miles. The derivative of that function would represent the speed of the car. Since the derivative is a measure of how fast that function is changing, the derivative of the distance function would tell us the speed.</p><p>For our machine learning models we use something called the partial derivative. The partial derivative is just the derivative of a function with multiple variables, where you focus on one variable at a time while treating all the others as constants. This is how we update each of our parameters, we take the partial derivative for each parameter.</p><p>I won’t go into exactly how to calculate the derivative here but there’s <a href="https://mml-book.com/">plenty</a> of <a href="https://youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr&amp;si=NPINcnz0lm8KwDx1">resources</a> online for that. Just know that the derivative of our cost function with respect to w is here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*T1cY2OV2dxcS8VcpBDo-6Q.png" /><figcaption>Derivative of Cost Function with respect to w</figcaption></figure><p>This is where that extra 2 comes in from before. To take the derivative, we move the exponent into a coefficient. This lets us cancel out the 2 which leaves or derivative nice and clean. Again I won’t be going into it here but its a good idea to brush up on some Calculus to get a good conceptual understanding for what’s going on here.</p><p>This is perfect right? If we have a cost function, we can simply take the derivative of that cost function and use that information to update our parameters. We also use something called a learning rate which is just a constant we multiply by the derivative. This is useful in tweaking our model. We start with any value of w and b (I used zero) and from there figure out the derivative of the cost function given those values of our parameters, based on the derivative we update our parameters and repeat until the derivative gets close to zero. Remember, our derivative being very small means the rate of change of our cost function has slowed down and we are approaching a local minimum. Here you can see how I did it for the CitiBike project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*nvE7HzCKKUi-_LIOCgt0hw.png" /><figcaption>Python functions for computing the derivative and gradient descent</figcaption></figure><p>We give the functions our training data, our starting values of w and b, our constant alpha and our iterations and the gradient descent function will (eventually) return our optimized values of w and b. We also have to scale our feature variables meaning we translate the values into values that are smaller to work with between say -3 and 3. If we don’t do this we run into issues running our gradient descent where it zig-zags or take a long time to converge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bazh9YRWiWtR0UL3pHFumA.png" /><figcaption>Running gradient descent in Python</figcaption></figure><p>The value of alpha and how many iterations you need is something you have to experiment with and tweak. But ultimately we have our values of w and b! I also computed the cost (adjusted to be relative to our feature inputs) to be about 3 minutes. Not too bad. Lets see how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3LFnUB04un72c2vG8c2qQ.png" /><figcaption>Visualization of our linear regression model</figcaption></figure><p>Pretty nice fit! With this you have now learned the basics of linear regression, cost functions, and gradient descent.</p><p>With this project, I got hands-on experience building a linear regression model from scratch, cleaning real-world data, and using gradient descent to optimize it. It was cool to see how the math actually plays out in code and how a simple model can make pretty solid predictions. Next, I’ll start exploring multiple features to see how adding more data points can make these predictions even stronger.</p><p><a href="https://x.com/jerlearnsml">Follow me on X</a> (twitter was a better name) to see more content like this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da8557202070" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>