<?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 Lucas Moncada on Medium]]></title>
        <description><![CDATA[Stories by Lucas Moncada on Medium]]></description>
        <link>https://medium.com/@lucas.moncada08?source=rss-2c1365993887------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6Rle_EO4HRrrwGHXW6F7yg.png</url>
            <title>Stories by Lucas Moncada on Medium</title>
            <link>https://medium.com/@lucas.moncada08?source=rss-2c1365993887------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:45:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucas.moncada08/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[How I Implemented Redis in Python]]></title>
            <link>https://medium.com/@lucas.moncada08/how-i-implemented-redis-in-python-4cf39e66e77a?source=rss-2c1365993887------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf39e66e77a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[project-based-learning]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Lucas Moncada]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 20:43:55 GMT</pubDate>
            <atom:updated>2022-08-11T21:00:39.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Why and How I Built a Toy-Redis from Scratch in Python</p><figure><img alt="Python and Redis" src="https://cdn-images-1.medium.com/max/1024/1*MrRmze9JrEG2pr5tYlOzFg.png" /></figure><h3>Contents</h3><ul><li>Why I built a Redis-CLI from scratch</li><li>Design and Implementation</li></ul><h3>Why Build a Mini-Redis CLI</h3><p>Redis at its core is a data structure store used in applications as a key-value database; typically, used as a cache to store recently used data. Apart from this, Redis supports many different data structures such as sorted sets, streams, and spatial data. In fact, Redis in its current form can be used as the primary database in some applications.</p><p>Wow, that sounds amazing, but why would you ever attempt to take on such a project? First of all, I am not interested in trying to fully implement all, or even close to all, of the Redis features. I am interested in developing some of the core functionalities of Redis. Specifically, the protocol clients use to interact with Redis servers, how data is parsed and stored, and the process of expiring keys.</p><p>“Ahhh,” you might say, “so why are you just making a worse version of Redis?” Well, the project isn’t for the purpose of building something that will be used by many millions of users. That is actually the inverse of what I am going for. Redis was used by many millions of users, so I am building parts of it. To make the point clear, I am building Redis because it is an established, popular technology that I could learn from. This comes with the added benefit of deeply grasping the Redis fundamentals for future use of the tool.</p><p>To linger on what I learned a bit longer, this project taught me how to:</p><ul><li>Properly use sockets and threads</li><li>Design and use of a great serialization protocol (RESP)</li><li>Object-oriented design</li><li>Parsing byte strings</li><li>Testing a Python application using Unittest</li></ul><p>If you are a junior engineer or student, this approach of building things from scratch is one I highly recommend. I will likely make a post about this soon.</p><h3>Design and Implementation</h3><h4>High-Level Design</h4><p>To implement a Redis-CLI that runs locally, we need to create a client-server architecture that allows for communication between each other. For this, we can use socket programming to share raw packets of info. Specifically, we can use Python’s socket[1] library.</p><p>Additionally, we need to be able to handle many different clients connecting to the server without creating a large bottleneck during server computations. To fix this problem we will use the Thread[2] library in Python and will implement a connection buffer class to read data in batches.</p><p>Finally, the client and the server must be able to communicate using the Redis serialization protocol specification (RESP)[3]. Moreover, the server and client should be able to extensively decode RESP communication, while the client should also be able to encode user input into RESP communication.</p><h4>Implementation</h4><p>Before we get to the feature implementations, let’s decide on some tests to run so that we have goals to aim for as we develop our code (a.k.a. Test Driven Development). We can write these tests using the Python Unittest[4] library.</p><p>We might start off by writing some unit tests for the RESP communication and implement that functionality. Subsequently, we can move on to making some end-to-end tests combining the RESP functionality with the client and server before implementing the features to meet these tests.</p><p><strong>RESP Communication</strong></p><p>For testing the RESP encoder, we can create some sample messages that the encoder might encounter, including some edge cases. Below includes some tests I used:</p><pre># format: (input, expected)<br>data = (<br>  (&quot;PING&quot;, b&quot;+PING\r\n&quot;),<br>  (&quot;ping&quot;, b&quot;+ping\r\n&quot;),<br>  (&quot;test12345&quot;, b&quot;+test12345\r\n&quot;),</pre><pre>  (&quot;Echo Hello&quot;, b&quot;*2\r\n$4\r\nEcho\r\n$5\r\nHello\r\n&quot;),<br>  (&quot;get name&quot;, b&quot;*2\r\n$3\r\nget\r\n$4\r\nname\r\n&quot;),<br>  (&quot;set friend john&quot;, b&quot;*3\r\n$3\r\nset\r\n$6\r\nfriend\r\n$4\r\njohn\r\n&quot;),</pre><pre>  (&quot; incorrect&quot;, b&quot;+Invalid\r\n&quot;),<br>  (&quot;&quot;, b&quot;+Invalid\r\n&quot;)<br>)</pre><p>From here we can simply create a function to iterate through the tests and assert that the expected outcome is equivalent to the function’s output.</p><pre>re = RESPEncoder() # not yet implemented</pre><pre>def test_encode(self):<br>  for test, expected in self.data:<br>    actual = self.re.encode(test) # fxn not yet implemented<br>    self.assertEqual(expected, actual)</pre><p>For testing the RESP Decoder, we can just reverse the input and expected values and replace the edge cases with decode-specific examples.</p><p>The RESP Encoder implementation is quite simple. We need a general encoding function in order to parse through the user-inputted commands. The commands should always be passed in with spaces between each input:</p><p>set friend john ex 5</p><p>To encode this in valid RESP, we will create an array of strings to send to the server. Note that an array is denoted by the * character and the strings can be denoted by a$ character.</p><p>*5\r\n$3\r\nset\r\n$6\r\nfriend\r\n$4\r\njohn\r\n$2\r\nex\r\n$1\r\n5\r\n</p><p>We can take care of this functionality with the following RESP Encoder class.</p><pre># Encoding functionality from regular text to RESP format<br>class RESPEncoder:<br>  <br>  def encode(self, text: str) -&gt; bytes:<br>    text_split = text.split(&#39; &#39;)<br>    <br>    if len(text_split) == 0 or text_split[0] == &quot;&quot;:<br>      return b&quot;+Invalid\r\n&quot;</pre><pre>    if len(text_split) == 1:<br>      return f&quot;+{text}\r\n&quot;.encode()</pre><pre>    # if the input had multiple seperate words (commands)<br>    encoded_str = f&quot;*{len(text_split)}\r\n&quot;<br>    for txt in text_split:<br>      encoded_str += self.encode_bulk_string(txt)<br>    <br>    return encoded_str.encode()</pre><pre>  def encode_bulk_string(self, text: str) -&gt; str:<br>    return f&quot;${len(text)}\r\n{text}\r\n&quot;</pre><p>The RESP Decoder takes a bit more design since it will also be used in the server that many clients may be communicating with at one time. Thus, it is valuable to implement a buffer system in order to receive data in batches to decrease a potential server bottleneck.</p><p>In the below code chunk, a class is defined to handle the buffer system using two useful methods. The read method takes in a buffer size parameter and reads data equal to that size. This will be used to read the data type byte (the first character) included in each RESP string. The read_until_delimeter works exactly as it sounds, reading until the passed parameter delimeter is reached. This will be useful due to the ubiquitous \r\n splits in each string.</p><pre>class ConnectionBuffer:<br>  def __init__(self, connection):<br>    self.connection = connection<br>    self.buffer = b&quot;&quot;</pre><pre>  def read(self, buff_size):<br>    # if req buff size has not already been read in<br>    if len(self.buffer) &lt; buff_size:<br>      data = self.connection.recv(1024)<br>      <br>      if not data:<br>        return None</pre><pre>      self.buffer += data</pre><pre>    data, self.buffer = self.buffer[:buff_size], self.buffer[buff_size:]</pre><pre>    return data</pre><pre>  def read_until_delimeter(self, delimeter):<br>    # if buffer does not have delim, more data must be read<br>    while delimeter not in self.buffer:<br>      data = self.connection.recv(1024)<br>      <br>      if not data:<br>        return None</pre><pre>      self.buffer += data</pre><pre>    data_before_delim, delim, self.buffer = self.buffer.partition(delimeter)</pre><pre>    return data_before_delim</pre><p>To utilize this class we can define another class, RESPDecoder that will function as the master class. Notably, the decode method will take the first look at the received RESP string and decide whether it should be processed as a simple string, bulk string, or array.</p><pre>class RESPDecoder:<br>  def __init__(self, connection):<br>    self.connection = ConnectionBuffer(connection)</pre><pre>  def decode(self):<br>    &quot;&quot;&quot;Main function used to evaluate what type of data is recieved&quot;&quot;&quot;</pre><pre>    data_type_byte = self.connection.read(1)<br>    if data_type_byte is None:<br>      return</pre><pre>    if data_type_byte == b&quot;+&quot;:<br>      return self.decode_simple_string()<br>    elif data_type_byte == b&quot;$&quot;:<br>      return self.decode_bulk_string()<br>    elif data_type_byte == b&quot;*&quot;:<br>      return self.decode_array()<br>    else:<br>      raise Exception(f&quot;Unknown data type byte: {data_type_byte}&quot;)</pre><p>In the individual decode_... methods, we can implement the specific logic required. Below is the array decoding functionality that includes a recursive-like call to the abovedecode method for each array element.</p><pre>def decode_array(self):<br>  result = []<br>  array_length = int(self.connection.read_until_delimeter(b&quot;\r\n&quot;))</pre><pre>  for _ in range(array_length):<br>    result.append(self.decode())</pre><pre>  return result</pre><p>Using this methodology, we now pass all the RESP communication tests we wrote before. Furthermore, we have defined the protocol by which our server and clients will communicate.</p><p><strong>Client and Server</strong></p><p>To write the tests for running the client and server in an end-to-end test, we can define a few categories to approach testing in a more granular style. I chose the categories:</p><ol><li>Testing simple commands</li><li>Invalid commands</li><li>Expiry-related commands</li></ol><p>Expiring keys is something that has not yet been discussed in this article, and entails having items in the data store that will only persist for a predefined set of time. For instance, see the below commands.</p><pre>&gt;  SET name lucas-moncada EX 2 # set name key to persist for 2 seconds<br>&lt; OK</pre><pre>&gt;  GET name<br>&lt;  lucas-moncada # name key still in data store</pre><pre># wait 2+ seconds</pre><pre>&gt;  GET name<br>&lt;  -1 # name key no longer in data store</pre><p>The implementation of this will be examined shortly. For now, let us continue with the test making of the app. The three categories of tests aforementioned can be defined in the following way.</p><pre># test data for client input encoding<br>simple_commands_data = (<br>  (&quot;PING&quot;, &quot;PONG&quot;),<br>  (&quot;ping&quot;, &quot;PONG&quot;),<br>  (&quot;Echo Hello&quot;, &quot;Hello&quot;),<br>  (&quot;set friend john&quot;, &quot;OK&quot;),<br>  (&quot;get friend&quot;, &quot;john&quot;),<br>)</pre><pre># test invalid commands<br>invalid_commands = (<br>  (&quot;set friend&quot;, &quot;-ERR invalid number of args&quot;),<br>  (&quot;get friend john&quot;, &quot;-ERR invalid number of args&quot;),<br>  ...<br>  (&quot;name friend&quot;, &quot;-ERR unknown command&quot;),<br>  (&quot;getset name friend&quot;, &quot;-ERR unknown command&quot;),<br>)</pre><pre># testing functionality that relies on expiring items<br># format: (command, timeout_after, response)<br>expire_test_data = (<br>  (&quot;set hello world 2000&quot;, 0, &quot;OK&quot;),<br>  (&quot;get hello&quot;, 3, &quot;world&quot;),<br>  (&quot;get hello&quot;, 0, &quot;-1&quot;),<br>  ...<br>  (&quot;set hello world px 1000&quot;, 0, &quot;OK&quot;),<br>  (&quot;expire hello px 5000&quot;, 2, &quot;1&quot;),<br>  (&quot;get hello&quot;, 4, &quot;world&quot;),<br>  (&quot;get hello&quot;, 0, &quot;-1&quot;),<br>)</pre><p>Running the tests can follow a similar approach as the RESP testing, iterating through the test elements and checking if the method returns the expected value. Additionally, for the expiry-related tests, we will use the Python Time[5] library to timeout while we wait to evaluate if the key really does expire.</p><pre># testing commands that use expiration functionality<br>def test_expire_commands(self):<br>  for test, sleep_time, expected in self.expire_test_data:<br>    actual = run_client(test)<br>    self.assertEqual(expected, actual)<br>    sleep(sleep_time)</pre><p>Great! We have our tests written, now we can implement this functionality with these targets in mind.</p><p>To get started we can implement the client to connect to the server, then loop indefinitely while pausing for inputs until the user inputs the exit command. Below is my implementation, including a test condition for running tests and some input validation.</p><pre>def run_client(test: str=None):<br>  print(&quot;&lt;  Client Started&quot;)<br>  re_encode = RESPEncoder()</pre><pre>  with socket.socket() as s:<br>    s.connect((&quot;localhost&quot;, 6379))<br>    print(&quot;&lt;  Connected to Server\n&quot;)</pre><pre>    data = None<br>    test_flag = False # to check if the test has been run<br>    <br>    # run until exit is input</pre><pre>    while True:<br>      # if tests are provided, use them, else get user input<br>      if test is not None:<br>        if test_flag:<br>          break<br>        inp = test<br>        test_flag = True</pre><pre>      else:<br>        inp = input(&quot;&gt;  &quot;) # client waits for user input<br>        <br>        if inp == &quot;exit&quot;:<br>          print(&quot;&lt;  Exiting&quot;)<br>          break</pre><pre>        if len(inp) == 0 or len(inp) &gt;= 500:<br>          print(f&#39;Invalid length: {len(inp)}. Length range: (0, 500)&#39;)<br>          continue</pre><pre>        enc_inp = re_encode.encode(inp)<br>        s.sendall(enc_inp) # send encoded input back to server</pre><pre>        # wait until data received – first decode is custom decode and second is from bytes to string<br>        data = RESPDecoder(s).decode().decode(&quot;utf-8&quot;)<br>        print(f&#39;&lt;  {data}\n&#39;)</pre><pre>        return data</pre><p>Once again, the server implementation is a bit more complex. Let’s start with the initialization. We must first create a server using the socket create_server command. Afterward, we will create the data store using a simple dictionary in Python and start the ActiveKeyExpire functionality (which we will get to soon). Finally, there should be a while loop to wait for new client requests and handle these new clients by creating a new thread for each client.</p><pre>def main():<br>  logging.basicConfig(level = logging.INFO)<br>  logging.info(&quot;Starting Server&quot;)<br>  server_socket = create_server((&quot;localhost&quot;, 6379), reuse_port=True)<br>  logging.info(&quot;Server Started&quot;)</pre><pre>  store = {} # storage of all the keys</pre><pre>  ActiveKeyExpire(store).run_timer() # not yet implemented</pre><pre>  while True:<br>    client_connection, _ = server_socket.accept() # wait for client<br>    logging.info(&quot;Client Connected&quot;)<br>    <br>    server = Server() # not yet implemented<br>    Thread(target=Server.handle_connection, args=(server, client_connection, store,)).start() # open a thread for each client connection</pre><p>Awesome! Now to implement the Server class to handle individual threads of the server, we can create a while loop to continue pausing for client connection requests. Once a client connection request is received the server will use the RESP decoding functionality to figure out which command to run.</p><pre>class Server:</pre><pre>  def handle_connection(self, client_connection, store):<br>    &quot;&quot;&quot;<br>    Main function used for handling all the connections. Includes while loop to handle all client inputs.&quot;&quot;&quot;</pre><pre>    self.store = store<br>    self.client_connection = client_connection</pre><pre>    while True:<br>      try:<br>        decoded = RESPDecoder(client_connection).decode() # run essential fxn to decode RESP to readable byte strings</pre><pre>        if decoded is None:<br>          break</pre><pre>        if isinstance(decoded, bytes): # just one input<br>          command = decoded.lower()<br>          args = None<br>        else:<br>          command = decoded[0].lower()<br>          args = decoded[1:]</pre><pre>        if command == b&quot;ping&quot;:<br>          client_connection.send(b&quot;+PONG\r\n&quot;)<br>        <br>        elif command == b&quot;echo&quot;:<br>          client_connection.send(<br>            f&quot;${len(args[0])}\r\n{args[0].decode(&#39;utf-8&#39;)}\r\n&quot;.encode()<br>          )</pre><pre>        elif not args:<br>          client_connection.send(b&quot;+-ERR invalid number of args\r\n&quot;)</pre><pre>        elif command == b&quot;set&quot;:<br>          self.handle_set_command(args)</pre><pre>        elif command == b&quot;get&quot;:<br>          self.handle_get_command(args)</pre><pre>        elif command == b&quot;expire&quot;:<br>          self.handle_expire_command(args)</pre><pre>        else:<br>          client_connection.send(b&quot;+-ERR unknown command\r\n&quot;)</pre><pre>      except ConnectionError:<br>        break</pre><p>Using this modular approach allows for understanding the code implementation at a higher level. Above we can see that we move through the possible commands, entering the command-specific methods when necessary.</p><p>I will take a closer look at my implementation of the handle_set_command and the handle_get_command. The handle_expire_command method is similar to the handle_set_command and can be found in the source code linked at the end of the article.</p><p>Nonetheless, below is the handle_set_command options:</p><ol><li>Set a key that will persist forever (until expire)</li><li>Set a key to expire in milliseconds</li><li>Set a key to expire with milliseconds or seconds</li></ol><pre>&gt;  SET language python-3.8 # Option 1<br>&gt;  SET ide vs-studio-code 2000 # Option 2<br>&gt;  SET device mac-2020 EX 5 # Option 3 </pre><p>We can handle this with the args parameter passed into the handler function which contains the arguments as a list that the user inputted along with the set command. Notably, when setting a key with an expiry we use the time() method to get the current time and add the input expiry time to get the threshold of when that key will no longer be valid.</p><pre>def handle_set_command(self, args):<br>  if len(args) &lt; 2 or len(args) &gt; 4:<br>    self.client_connection.send(b&quot;+-ERR invalid number of args\r\n&quot;)<br>    return</pre><pre>  if len(args) == 2: # no expiry<br>    self.store[args[0]] = (args[1], -1)</pre><pre>  elif len(args) == 3: # expiry with no units<br>    self.store[args[0]] = (args[1], time()+(int(args[2])/1000))</pre><pre>  else: # expiry with units<br>    if args[2].lower() == b&quot;px&quot;:<br>      self.store[args[0]] = (args[1], time()+(int(args[3])/1000))<br>    elif args[2].lower() == b&quot;ex&quot;:<br>      self.store[args[0]] = (args[1], time()+int(args[3]))<br>    else:<br>      self.client_connection.send(b&quot;+-ERR invalid unit\r\n&quot;)<br>      return</pre><pre>  self.client_connection.send(b&quot;+OK\r\n&quot;)</pre><p>The get command has a few potential conditional flows as well.</p><ol><li>The requested key is <strong>not</strong> in the data store</li><li>The requested key is in the data store and is valid</li><li>The requested key is in the data store but is <strong>not</strong> valid</li></ol><p>By valid, I simply mean that the key expiry time is chronologically after the current time. This logic is implemented below.</p><pre>def handle_get_command(self, args):<br>  if len(args) != 1:<br>    self.client_connection.send(b&quot;+-ERR invalid number of args\r\n&quot;)<br>    return</pre><pre>  if args[0] not in self.store:<br>    self.client_connection.send(b&quot;+-1\r\n&quot;)</pre><pre>  elif self.store[args[0]][1] != -1 and self.store[args[0]][1] &lt; time():<br>    self.store.pop(args[0])<br>    self.client_connection.send(b&quot;+-1\r\n&quot;)<br>  <br>  else:<br>    value = self.store[args[0]][0] self.client_connection.send(<br>      f&quot;${len(value)}\r\n{value.decode(&#39;utf-8&#39;)}\r\n&quot;.encode()<br>    )</pre><p>We have almost completely walked through the code implementation. However, if you had been paying attention to this get functionality, you may be thinking that if we set many keys, with expiration times, and never access them, we can potentially have a very large amount of expired keys taking up space in the data store. This is happening because we only discover a key is expired when we try to access it. To mitigate this problem, we can implement the ActiveKeyExpire class.</p><p>The design for this class is simple and seems so obvious once you discover it, but in my opinion, is a great idea for dealing with this problem. We can create a thread that runs every 10 seconds that takes a sample of up to 20 keys in the data store and tests if these are valid. If any of these keys are invalid, we simply remove them from the data store. After sampling these 20 keys, if 25% or more of the sampled keys were expired, we call the function again to sample another 20 keys. See the below class for a scalable procedure of active key expiration.</p><pre>class ActiveKeyExpire:<br>  &quot;&quot;&quot;Use thread timer to actively search for expired keys&quot;&quot;&quot;<br>  def __init__(self, store):<br>    self.store = store</pre><pre>  # timer used for active expiring of stored keys<br>  def run_timer(self):<br>    Timer(10.0, self.run_timer).start()<br>    self.active_key_expire()</pre><pre>  def active_key_expire(self):<br>    sample_size = min(len(self.store), 20)    <br>    expired = 0 # keeping track of number of expired keys</pre><pre>    for key in list(self.store.keys())[:sample_size]:<br>      # double check key in store, account for no expiry, check if expired<br>      if key in self.store and self.store[key][1] &gt; 0 and self.store[key][1] &lt; time():<br>        self.store.pop(key, None)<br>        expired += 1</pre><pre>    # if 25% of keys were expired, run the active key expire again<br>    if expired &gt; sample_size*0.25:<br>      self.active_key_expire()</pre><p>That’s it! We can run the end-to-end tests and find that they passed with flying colors.</p><p>The above was a walkthrough of my implementation developing some core Redis features from scratch in Python. Feel free to take inspiration from my code and add to it! Feedback would also be greatly appreciated, this code is by no means flawless and I would love to hear what you think.</p><p>Thanks so much for reading! Have a great rest of your day.</p><h4>Github Link</h4><p><a href="https://github.com/lucasmoncada08/toy-redis">GitHub - lucasmoncada08/toy-redis: Toy Version of Redis to Deeply Understand the Technology</a></p><h4>References</h4><p>[1] <a href="https://docs.python.org/3/library/socket.html">https://docs.python.org/3/library/socket.html</a></p><p>[2] <a href="https://docs.python.org/3/library/threading.html">https://docs.python.org/3/library/threading.html</a></p><p>[3] <a href="https://redis.io/docs/reference/protocol-spec/">https://redis.io/docs/reference/protocol-spec/</a></p><p>[4] <a href="https://docs.python.org/3/library/unittest.html">https://docs.python.org/3/library/unittest.html</a></p><p>[5] <a href="https://docs.python.org/3/library/time.html">https://docs.python.org/3/library/time.html</a></p><p>If you liked this article, check out some of my other articles by clicking on my profile. Also, check out my website below where I elaborate more on my experience, projects, and skills.</p><p><a href="https://lucasmoncada.netlify.app/">Lucas Moncada Portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf39e66e77a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression in Python]]></title>
            <link>https://medium.com/@lucas.moncada08/linear-regression-in-python-f94f9b72c282?source=rss-2c1365993887------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94f9b72c282</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lucas Moncada]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 06:15:41 GMT</pubDate>
            <atom:updated>2021-12-14T06:15:41.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Breaking Down the “Hello World” of Machine Learning</p><p>Linear regressions are often one of the first things an aspiring data scientist/machine learning engineer learns at the beginning of their journey. Thus, I thought I would write an article to an imaginary version of myself learning about linear regression for the first time. First I break down the basics of what linear regressions are, and how they might be used practically. After this, I show a more low-level implementation in code of a linear regression model to facilitate diving into the specifics. Here we go!</p><h3>What is a Linear Regression?</h3><p>A linear regression is a model that attempts to learn the relationship between one or more features (aka inputs) and a numerical continuous target variable. Furthermore, the goal of a linear regression model is to predict this continuous target variable when given some input. Let’s look at a straightforward example, using an employee&#39;s years of experience to predict their salary.</p><h4>Linear Regression Intuition</h4><p>Forget about linear regressions for a second and consider how an individual’s relevant experience might be related to salary in the workplace. A good guess would be to predict that as experience increases, salary increases as well. Maybe it looks something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*_9M13NXlib6ptkCpMiOG4A.png" /></figure><p>This is interesting, but the obvious next question is by how much? Well, that is actually a big part of the point behind linear regression, we want to find out by how much salary increases as experiences. Let us call this “how much” number <strong>W</strong>. The mathematically inclined will likely be led to imagine some equation alike below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*pzGvHZXGX0u3AjRz" /></figure><p>This is an interesting idea. So as a crude example, if one’s salary increased by $10,000 per year of experience you obtained as a Data Scientist, you might imagine an equation like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*VhzaClcJojRc4VjK" /></figure><p>Moreover, you could expect a relationship like the below graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*PlbWz2eD7Cs8WpYOnD8U9Q.png" /></figure><p>Cool, that looks good, right?… Right? Well, if you more closely at the x-axis you might realize something peculiar, this is only for experienced data scientists. What does this same relationship look like for the new grad data scientists?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Oj1rDhFAoQcUs2MQGZ0sJg.png" /></figure><p>Now the problem is visible. Our current formula does not account for an employee’s base salary! This is certainly not the relationship a reasonable employer could use. So how might we account for that? Again, those of you who have taken high-school-level functions may have a kneejerk reaction: “add a bias.” What does this mean? Well quite simply, we can add a fixed amount of “Salary” before calculating the Experience multiplied by <strong>W</strong>. We will call this fixed/base amount of salary <strong>B</strong>. Mathematically, we can write this as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*AdVwjoC2KBZkwFSh" /></figure><p>Now as an example of this formula in action, let’s assume a base salary as $80,000 and change <strong>W</strong> from +$10,000/year to +$5,000/year of experience. Hence, the mathematical representation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*zMaiSAZKMP_A5zLo" /></figure><p>This results in the following graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*gUnYgo0tF4VFqv9E6l9ZRQ.png" /></figure><p>Great! Now that we have defined this heuristic, we now have to figure out what a linear regression is right? On the contrary, this intuition that we have ended upon is known as a <strong>Simple Linear Regression</strong>. We can generalize our formula by replacing Experience by <strong>X</strong>, resembling some form of input, and substituting in <strong>y</strong> instead of Salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*iV3-oeE18CTUysA4" /></figure><p>Great, now take a second to infer how one might write this equation if we were using just a TV Screen’s Area to try and predict the price of that TV.</p><p>We could write that formula something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*IqCUNXSYC8PAycWA" /></figure><h3>Using a Linear Regression Model</h3><p>Now that we have an intuition on what a linear regression model is, how can we use it. Here I will be showing how to use linear regression to predict the salary when given an employee&#39;s experience. I will be using a more extensive dataset this time to better represent a more applicable example. First I will show the implementation using Python’s excellent machine learning library, Scikit-learn (aka sklearn); then later in this article, I will dive into what is actually going on under the hood.</p><p>Our main steps to using this linear regression model, while employing some general machine learning techniques, will be:</p><ol><li><em>Get the data and split it into a training set and test set</em></li><li><em>Initialize our Linear Regression Model</em></li><li><em>Fit our Linear Regression Model on the data</em></li><li><em>Use our Linear Regression Model to predict unseen data</em></li></ol><h4>1. Getting the Data and Splitting it</h4><p>First, we should get our data and take a quick look at it.</p><pre># Import the relevant libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>dataset = pd.read_csv(&#39;Salary_Data.csv&#39;) # get the dataset</pre><pre>YearsExperience = dataset[&#39;YearsExperience&#39;]<br>Salary = dataset[&#39;Salary&#39;]</pre><p>Visualizing the data in a scatter plot we get a similar-looking graph as above, except instead of a linear regression line, we are just showing the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*mFLZ6xBfX9DrFpjKYpB_YA.png" /></figure><p>Now let us split our data into a training set and test set. If you are unfamiliar with this idea, do not worry, it will make more sense later. For now, just realize that we are saving some portion of the experience and salary data pairs in a test set, to use in a later step. We will be working with the training set in the next couple of steps.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>Experience_train, Experience_test, Salary_train, Salary_test = train_test_split(YearsExperience, Salary, test_size=0.2,<br>random_state = 123) # Taking 20% of the data into the test set</pre><p>Now we have a training set comprised of Experience_train and Salary_train. After preparing our data, we can get to the linear regression modelling.</p><h4>2. Initializing a Linear Regression Model</h4><p>What does it mean to initialize a model? Well, this step consists of telling Python (and sklearn) what specifics our model will entail when we create it. Simple linear regression models do not have many specifics to alter, but one example is not including the bias variable that served as our base salary in the prior example. Here, we will create a default linear regression model; however, I implore you to check out the sklearn documentation for their linear regression implementation¹.</p><p>Here is the Python code for initializing a linear regression.</p><pre>from sklearn.linear_model import LinearRegression</pre><pre>linear_regression = LinearRegression()</pre><p>That’s it for initializing the model. Very easy with sklearn, right?!</p><h4>3. Fitting the Linear Regression on the Data</h4><p>This is a critical step of a linear regression model and of all supervised machine learning models (data with labels). Let’s quickly recall our formula for linear regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*iV3-oeE18CTUysA4" /></figure><p>Here we will allow the model to learn from the data, aka the experience and salary pairs, in order to find the best <strong>B</strong> and <strong>W</strong> for this data. What does that mean? Basically, we will try a bunch of combinations of setting the bias variable <strong>B</strong>, and the slope variable <strong>W</strong>, to find the best fit for our data. Okay, but what does it mean to have the best fit on our data. Again, we figure this out by just thinking logically.</p><p>Consider the following graphs, and try to articulate why you think one of the linear regression lines better fits the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*1Civ3eB3DZbGhbXNmVgQ8Q.png" /><figcaption>The green line indicates the linear regression</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*TMoOwXNof2EGnz5GZV66SA.png" /><figcaption>The green line indicates the linear regression</figcaption></figure><p>Did you get an answer? Try to consider which line better represents the data. Clearly, it is the first image, but why? One might say because the line is closer to the data… and you would be right. The formal idea is actually called ordinary least squares, and the main concept is simply looking at the differences between the line and the actual data points. We will look into this a bit further later in the article, but for now, let us see how to implement this in sklearn.</p><pre>linear_regression.fit(Experience_train.reshape(-1, 1), Salary_train)</pre><p>Wow just one line, that’s awesome! Thanks, David Cournapeau (founder of sklearn). Also, note that we used reshape(-1, 1) on the experience values, this is because the fit() method expects a 2-D array, and the above way is just a simple strategy to do convert a 1-D array to 2-D. What does our linear regression look like now? See below for the fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*wl947SrEZGX3m7tkwPTlGQ.png" /></figure><p>Looks great, better than the above two fits! Now we have a model that understands our data, what next? Finding out if our model performs well on unseen data.</p><h4>4. Predicting New Data with our Linear Regression</h4><p>It is very important in machine learning to measure if one’s model is predicting well on not just the data one is using to train a model, but also, how the model performs on new, unseen data. Now, remember that bit of data we saved in step 1 and called the test data? Well in this step we use this data that was excluded from the data used to train the model and see how well our linear regression performs on this data. Thus, let us write the code to make predictions on the test set.</p><pre>Salary_predictions = linear_regression.predict(Experience_test.reshape(-1, 1))</pre><p>Once again, very simple. Note the reshape() function being used once again to transform the 1-D array into the required 2-D array format. When we visualize how this model performs on the new data we see the below graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*bIWTYAauxXbTzV7sD2AOdA.png" /></figure><p>This looks pretty good, the line seems to cut through the data points fairly well. This means our model is <em>generalizing</em> well on unseen data!</p><p>In summary, we got our data and split it into a training and test set according to typical ML practices. Next, we initialized a default linear regression model using sklearn. Then we used our data to <em>train</em> the linear regression to understand the relationship between experience and salary in our dataset. Finally, we used the model to predict unseen data to check if the linear regression generalizes well.</p><h3>Linear Regressions — Under the Hood</h3><p>As a software engineer, I always better-understood machine learning concepts when seeing them implemented from scratch in code. This is an idea Jeremy Howard utilizes in his fantastic course and book, Deep Learning for Coders². Hence, we will attempt this approach here with linear regressions.</p><h4>Formally defining the efficacy of the model fit</h4><p>Earlier in this article, we discussed an over-simplified idea of when a linear regression properly fit the data; we eye-balled how close the linear regression line came to the observed data points. This, however, is obviously not formal enough to instruct Python. Thus, we will look at one very common way to define how well the model fits the data called Ordinary Least Squares.</p><p>The ordinary least squares method of measuring how effective a fit is is when one compares a model’s individual predictions to the actual label of the data. For instance, if my model predicted that an individual with 5 years of experience made $80,000, but they actually made $75,000, my model would be overpredicting this observation by $5,000. This is similar to the ordinary least squares formulation which is the sum of all the errors of the model squared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*g1Abwz9RlD_MHRdT" /></figure><p>By taking the square of the differences we make sure that over predictions and under predictions do not cancel each other out. This also penalizes large errors much more than smaller errors (i.e. 0.⁵²=0.25 and ⁴²=16). Defining this function in Python can look like this.</p><pre>def OLS_loss(predictions, observations):<br>  return np.sum((predictions-observations)**2)</pre><pre># Example Input<br>preds = np.array([1, 2, 3])<br>obs = np.array([2, 4, 6])<br>OLS_loss(preds, obs) #-&gt; 14</pre><p>Notably, it is useful to know that practitioners often refer to measuring the efficacy of a model’s fit as a <em>loss function</em>.</p><h4>How the Model Learns</h4><p>When a machine learning engineer or data scientist speaks of a model learning, they often mean parameters being adjusted to better represent the training data. Moreover, when remembering our equation defined previously, the two parameters that the model should properly set are the <strong>B</strong>, the intercept, and the<strong> W</strong>, the coefficient of the <strong>X</strong> variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*iV3-oeE18CTUysA4" /></figure><p>How are these parameters changed when given training data? One very common idea in machine learning is to use something called gradient descent.</p><p>Nonetheless, let us forget about this lingo for a moment and work from first principles. In the last subsection, we described how we can formally define how effective a model’s fit is on our training data. That is great, and as we can see from our definition, we want to minimize this function as much as possible to have the least errors. One might suggest trying many different combinations of <strong>B</strong> and <strong>W</strong> and then taking the parameters with the lowest OLS score. Great suggestion! Unfortunately considering both of the parameters are continuous values this strategy is clearly dubious in this simple example and intractable with any scale of parameters for instance.</p><p>Maybe we could try a random combination and then try to improve the parameters from there. Let us set <strong>B</strong> and <strong>W</strong> both equal to 1 and see what our model fit looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*YeFW_Pj9TS5sJPV1TIV35A.png" /></figure><p>As one can see, this linear regression line is not near the actual data points and is thus not a great model. Our OLS returns 42333966023 which is indeed a very large number relative to our salary magnitudes. Obviously, we can see that we need to increase the <strong>B</strong> and <strong>W</strong>, but how can we explain this to Python. Considering we want to modify some parameters given some changing value (our loss function) we can look to calculus, the study of continuous change. Specifically, we would like to know how the OLS loss function changes as we manipulate <strong>B</strong> and <strong>W</strong>; which can be denoted with the following complex appearing equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/0*nU973lEj98u7wGMx" /></figure><p>If this is beyond your mathematical understanding, feel free to just understand that the top and bottom matrix elements are functions for calculating how the OLS loss changes as <strong>B</strong> and <strong>W</strong> change, respectively. Great! So now we can use these two functions to modify B and W.</p><p><strong>Simple Example for Illustration</strong></p><p>A good visual image to have of this process is a ball rolling down a hill to get to the lowest possible point. The lowest possible point is where the OLS loss is the minimum possible, and we get there by using the above gradient equations to lead us in making the right changes to our parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Lu56J-rj9X2_JvF0TscWeA.png" /></figure><p>However, instead of drawing out this curve of OLS seen in the above image, we use a much more “greedy” approach to save on computations expenses. We simply consider the current slope of the gradient function and move in the direction that minimizes this. Thus, the following graph is more indicative of how our model learns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*WReZ5hSvLvXvmiD7xWWURg.png" /></figure><p>Consider now that the purple slope is what we use to modify the example parameter. Specifically, the larger the slope, the more we adjust the parameter. When we continue this learning process a few times it might look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*bQJpz1U7vr1tRp4IjTHpcg.png" /></figure><p>Here we can see that the OLS loss gets closer and closer to our goal state of the lowest possible OLS loss. Also notice that the purple lines are decreasing in slope as the parameter changes are decreasing. If you haven’t realized already, we have actually arrived upon the <em>gradient descent</em> algorithm I alluded to through intuitive steps. Now let’s apply this to our experience and salary example and see what the code looks like.</p><p><strong>Gradient Descent Learning Implementation</strong></p><p>At this point, we are nearly ready to implement the code for how a linear regression model can “learn” from data, known commonly in the field as <em>fitting</em> a model on data. The one thing we left out is something called a <em>learning rate</em>, which is basically how large of updates to the parameters a model will make based on the gradient. Typically, this is just a multiplicative factor denoted as alpha (α) as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/0*B0LM5KrxjwSiIQD_" /></figure><p>Where does this learning rate value come from? This is an excellent question and to my knowledge, the answer to this is still developing; however, currently, practitioners typically try to find the right learning rate iteratively, using some reasonable starting point. There are even some algorithms out there to find the right learning rate for more complex models³. Nonetheless, let’s see what the code looks like for an individual fit.</p><pre>def single_fit(X, y, B, W, lr):<br>    y_predictions = B + X * W # Predictions for the gradients</pre><pre>    grad_b = -2*np.sum(y_predictions - y) # Gradient wrt B<br>    grad_w = -2*np.sum((y_predictions - Salary_train)*Experience_train) # Gradient wrt W<br>    B += grad_b*lr # Updating B param<br>    W += grad_w*lr # Updating W param<br>    return B, W</pre><p>This should make sense given what we have discussed before. If you are still confused try specifying what does not make sense and feel free to leave a comment/question. Let us see how our linear regression model changes after we fit the model a few times using a learning rate of 0.00025.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*ofW5jBd4pqylVrbTNWZanw.png" /></figure><p>We can see that the model is getting closer and closer to the observations and thus are learning from the data. Given all goes well, your model should converge on some parameters after fitting the model on the data several times. Thus, you might end up with a model similar to the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*6k8wSxkPWL5hpV44NUwc5w.png" /></figure><p>As can be seen here by the very similar 20th fit and 50th fit, this model converges after several training fits. The converged state seems to fairly effectively fit the data, meaning we are done right? Close, but not quite yet. We should see how our model generalizes on new data</p><h4>Making Predictions on New Data</h4><p>Computing the predictions is actually very simple once you have your test data set up (as we did previously). We just have to make a <em>forward pass</em> on our test data using our linear regression equation. Below is the relevant code snippet.</p><pre>def predict(X, B, W)<br>    return B + X*W</pre><p>If this is a familiar equation then you are paying great attention, we have been using this equation throughout already!</p><p>Now that we have our predictions let us see if we can get some intuitive idea of how well our model is performing on new data. Of course, we can use still visualize our model since we are using a simple example, so let’s do that first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*4bSYhqNFnEAkb9qY-qjcJw.png" /></figure><p>This looks reasonable! But what about if the data is in more than one dimension and we cannot visualize it? Well, one approach of understanding our model’s performance is using the mean absolute error (MAE). Explicitly, this equation returns the average error that our model makes on the data. The formal definition is the following intuitive equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*psCQsVWgIG7J2zvq" /><figcaption>Where n is the number of observations</figcaption></figure><p>The code for this formula is straightforward.</p><pre>def MAE(y_predictions, y_true):<br>    return np.sum(abs(y_predictions - y_true))/len(y_true)</pre><p>Awesome, when we pass in our model’s predictions we get a mean absolute error of ~4500. This simply means that on average our model predictions of an individual’s salary are off by ~4500. Not terrible, but you could argue that this isn&#39;t that amazing either.</p><h4>Summarizing what we have</h4><p>This has been hopefully a helpful look under the hood of the linear regression model so that you can better understand the ideas behind it. To summarize what we have learned, let’s organize our components into a linear regression class.</p><pre>class LinearRegressionOLS():<br>    <br>    # Setting the relevant model characteristics<br>    def __init__(self, B=10000, W=5000, lr=0.00025, n_iters=20):<br>        self.B = B<br>        self.W = W<br>        self.lr = lr<br>        self.n_iters = n_iters<br>        <br>    # Training loop for the model to learn on the data<br>    def fit(self, X, y):<br>        self.costs = []<br>        <br>        for i in range(self.n_iters):<br>            y_predictions = self.B + X * self.W # Predictions for the gradients<br>            grad_b = -2*np.sum(y_predictions - y) # Gradient wrt B<br>            grad_w = -2*np.sum((y_predictions - y)*X) # Gradient wrt W<br>            self.B += grad_b*lr # Updating B param<br>            self.W += grad_w*lr # Updating W param<br>        <br>        return self<br>    <br>    # Making predictions on data using the current model<br>    def predict(self, X):<br>        return self.B + X*self.W <br>    <br>    # Return the Mean Absolute Error<br>    def MAE(self, y_predictions, y_true):<br>        return np.sum(abs(y_predictions - y_true))/len(y_true)</pre><p>To use this linear regression class we can implement very similar code as in the previous section of this article with sklearn’s linear regression.</p><pre>linear_regression = LinearRegressionOLS()<br>linear_regression = linear_regression.fit(Experience_train, Salary_train)<br>predictions = linear_regression.predict(Experience_test)<br>print(&#39;Mean Absolute Error:&#39;, linear_regression.MAE(predictions, Salary_test)) </pre><p>Now you know the fundamentals of a linear regression model! The grasp of this fundamental algorithm is useful to understand more complex models such as Decision Trees and Neural Networks.</p><p>Thanks so much for reading! I hope this article was of some use to you, please feel free to leave any comments, questions, and feedback! If you are a beginner at machine learning and are wondering what some next steps are, I would recommend looking at multiple linear regressions and logistic regressions. Furthermore, one book I loved as a very solid introduction to machine learning was <a href="https://www.amazon.ca/Python-Machine-Learning-scikit-learn-TensorFlow/dp/1789955750/ref=asc_df_1789955750/?tag=googleshopc0c-20&amp;linkCode=df0&amp;hvadid=335305582969&amp;hvpos=&amp;hvnetw=g&amp;hvrand=1675503255465354843&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9001070&amp;hvtargid=pla-849711952499&amp;psc=1"><em>Python Machine Learning</em></a><em> </em>by Sebastian Raschka, Vahid Mirjalili.</p><p>¹ <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html">https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html</a></p><p>² <a href="https://www.amazon.ca/Deep-Learning-Coders-fastai-PyTorch/dp/1492045527/ref=asc_df_1492045527/?tag=googleshopc0c-20&amp;linkCode=df0&amp;hvadid=335305582969&amp;hvpos=&amp;hvnetw=g&amp;hvrand=15187852249388123725&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9001075&amp;hvtargid=pla-917301026067&amp;psc=1">https://www.amazon.ca/Deep-Learning-Coders-fastai-PyTorch/dp/1492045527/ref=asc_df_1492045527/?tag=googleshopc0c-20&amp;linkCode=df0&amp;hvadid=335305582969&amp;hvpos=&amp;hvnetw=g&amp;hvrand=15187852249388123725&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9001075&amp;hvtargid=pla-917301026067&amp;psc=1</a></p><p>³ <a href="https://fastai1.fast.ai/callbacks.lr_finder.html#Learning-Rate-Finder">https://fastai1.fast.ai/callbacks.lr_finder.html#Learning-Rate-Finder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94f9b72c282" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>