<?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 Sam Khosravian on Medium]]></title>
        <description><![CDATA[Stories by Sam Khosravian on Medium]]></description>
        <link>https://medium.com/@samkhosravi?source=rss-36388c1f4b3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2E84Pptktl6LNxXg3p8S5Q.jpeg</url>
            <title>Stories by Sam Khosravian on Medium</title>
            <link>https://medium.com/@samkhosravi?source=rss-36388c1f4b3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:48:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samkhosravi/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[Chapter 3: Applying Domain-Driven Design in Ruby on Rails]]></title>
            <link>https://samkhosravi.medium.com/chapter-3-applying-domain-driven-design-in-ruby-on-rails-5be6bb5b97dc?source=rss-36388c1f4b3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be6bb5b97dc</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Sam Khosravian]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 07:13:30 GMT</pubDate>
            <atom:updated>2025-06-11T07:13:30.594Z</atom:updated>
            <content:encoded><![CDATA[<p>In Chapter 2, we unpacked the core principles of Domain-Driven Design (DDD), like putting the business first, using a shared language, and organizing complexity. These ideas form a playbook for aligning developers and managers around a startup’s goals. But how do you turn these principles into working software? This chapter shows how to apply DDD in Ruby on Rails, using an online marketplace as an example to keep it clear. We’ll walk through practical steps to model business needs, keep code tidy, and connect technical and business teams. By the end, you’ll see how DDD transforms Rails apps into flexible systems that grow with your startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*Dup_wVr6N4SC_wPb.png" /></figure><h3>Why DDD Shines in Rails</h3><p>Ruby on Rails is a fantastic tool for building apps quickly, but startups often stumble as their apps get bigger. Picture an online marketplace managing orders, stock, and customer profiles. Without a clear approach, the code can turn into a mess — hard to update and out of sync with what managers need. DDD brings order to this chaos, turning principles into code that mirrors the business. Let’s explore seven steps to make DDD work in Rails, with examples to bring them to life.</p><h3>Step 1: Split the Business into Parts</h3><p>Every startup has different pieces to its business. For an online marketplace, these might include handling orders, tracking inventory, and managing customer accounts. DDD calls these pieces <em>subdomains</em>. Identifying them helps you focus on what drives the business.</p><p>In Rails, start by mapping out subdomains with your team. Meet with business experts — like managers or sales leads — to pinpoint the core activities. For the marketplace, three subdomains stand out:</p><ul><li><strong>Orders</strong>: Creating and processing purchases, including payments.</li><li><strong>Inventory</strong>: Keeping track of product stock.</li><li><strong>Customers</strong>: Managing user details and purchase history.</li></ul><h3>Why It Helps</h3><p>Breaking the business into subdomains keeps things clear. Mixing orders and inventory logic can lead to errors, like selling items that are out of stock. Subdomains give each part its own focus, so developers and managers know what they’re building. It’s like dividing a big project into smaller, doable tasks.</p><h3>Example</h3><p>The marketplace team brainstorms subdomains. Orders is the heart, driving sales. Inventory ensures products are available, and Customers tracks user data. In Rails, these become separate parts of the codebase, making it easier to work on one without messing up the others.</p><h3>Step 2: Draw Clear Lines</h3><p>Each subdomain needs its own space, called a <em>bounded context</em>. Think of it as a mini-world where specific rules and terms apply. For example, a “product” in Orders (something in a cart) is different from a “product” in Inventory (stock on hand). Bounded contexts keep these worlds separate to avoid confusion.</p><p>In Rails, you can use modules to organize bounded contexts. Here’s how it looks:</p><pre># Orders Context<br>module Orders<br>  class Order &lt; ApplicationRecord<br>    has_many :order_items<br>  end<br>end<br><br># Inventory Context<br>module Inventory<br>  class Product &lt; ApplicationRecord<br>    validates :stock_level, presence: true<br>  end<br>end</pre><h3>Why It Helps</h3><p>Bounded contexts prevent mix-ups. In one startup, using “product” in multiple ways caused orders to ignore stock limits, frustrating customers. By keeping contexts separate, teams update one area without breaking others, making code clearer. It’s like having separate drawers for tools — you always find what you need.</p><h3>Example</h3><p>The team sets up bounded contexts for the marketplace. Orders handles purchases and payments, with rules like “no order without payment.” Inventory tracks stock to ensure products are ready. Each context uses Rails modules, so developers can tweak orders without touching inventory code.</p><h3>Step 3: Use One Language</h3><p>To keep everyone aligned, DDD relies on a <em>shared language</em> — words used the same way in talks and code. Collaborate with business experts to define terms like “order,” “item,” or “customer.” In Rails, these become class names and methods, tying the code to the business.</p><h3>Why It Helps</h3><p>A shared language cuts confusion. In a startup, teams argued over what “payment” meant, delaying features. Clear terms ensure managers’ plans match developers’ code, speeding up work. It’s like everyone using the same map to navigate.</p><h3>Example</h3><p>The marketplace team agrees on:</p><ul><li><strong>Order</strong>: A customer’s purchase with items and a total.</li><li><strong>Item</strong>: A product in an order, with quantity and price.</li><li><strong>Customer</strong>: A person with a profile and purchase history.</li></ul><p>These terms show up in Rails code and team discussions. When a manager says, “Add a discount to orders,” developers know exactly what to build.</p><h3>Step 4: Model the Business</h3><p>DDD sorts business ideas into <em>entities</em> (objects with unique IDs) and <em>value objects</em> (fixed objects compared by values). This makes the code match how the business works.</p><h3>Entities</h3><p>Entities have a unique ID and can change. A customer is an entity because their ID stays the same, even if their email updates:</p><pre>class Customer &lt; ApplicationRecord<br>  validates :email, presence: true, uniqueness: true<br>end</pre><h3>Value Objects</h3><p>Value objects are unchangeable and compared by values. A price, like $50 USD, is a value object:</p><pre>class Price<br>  attr_reader :amount, :currency<br><br>  def initialize(amount, currency)<br>    @amount = amount<br>    @currency = currency<br>  end<br><br>  def ==(other)<br>    amount == other.amount &amp;&amp; currency == other.currency<br>  end<br>end</pre><h3>Why It Helps</h3><p>Clear models prevent errors. In one startup, treating prices like entities caused bugs when comparing them. Entities and value objects keep code logical, like labeling boxes — you know what’s inside.</p><h3>Example</h3><p>The team models:</p><ul><li><strong>Entity</strong>: Order, with an ID and changing status (e.g., “pending” to “shipped”).</li><li><strong>Value Object</strong>: Price, compared by amount and currency.</li></ul><p>These models align code with the business, so teams discuss orders and prices clearly.</p><h3>Step 5: Group Related Pieces</h3><p>Some objects work together. DDD uses <em>aggregates</em> to bundle entities and value objects into one unit, led by an <em>aggregate root</em>. The root ensures consistency. For the marketplace, an order is the root, grouping order items (entities) and a total price (value object):</p><pre>module Orders<br>  class Order &lt; ApplicationRecord<br>    has_many :order_items<br>    validates :total, presence: true<br><br>    def total<br>      order_items.sum { |item| item.quantity * item.unit_price }<br>    end<br>  end<br><br>  class OrderItem &lt; ApplicationRecord<br>    belongs_to :order<br>    validates :quantity, :unit_price, presence: true<br>  end<br>end</pre><h3>Why It Helps</h3><p>Aggregates enforce rules. Updating an item without checking the order can cause wrong totals. Aggregates keep the app reliable, like a chef ensuring every ingredient fits the recipe.</p><h3>Example</h3><p>The team defines the Order aggregate:</p><ul><li><strong>Root</strong>: Order, with ID, status, and total.</li><li><strong>Included</strong>: Order Items, with product, quantity, and price.</li><li><strong>Rule</strong>: The total must match the sum of item prices.</li></ul><p>This ensures no item is added without updating the total, keeping code solid.</p><h3>Step 6: Handle Data Cleanly</h3><p>Data is crucial, but it can clutter code. DDD uses <em>repositories</em> to manage data, like a librarian fetching books. A repository finds or saves objects, like orders, without mixing database details into business logic:</p><pre>class OrderRepository<br>  def self.find(id)<br>    Orders::Order.find(id)<br>  end<br><br>  def self.save(order)<br>    order.save!<br>  end<br>end</pre><h3>Why It Helps</h3><p>Repositories keep code tidy. In one startup, database code was everywhere, making updates tough. Repositories centralize data tasks, letting developers focus on the business and easing tests. It’s like storing files in one folder, not scattered across a desk.</p><h3>Example</h3><p>The team uses OrderRepository to fetch and save orders, hiding Rails’ database details. If the database changes, only the repository needs tweaking, saving time.</p><h3>Step 7: Capture Big Moments</h3><p>Businesses have key events, like an order being placed. DDD uses <em>domain events</em> to record these, notifying other parts of the app. For example, an “Order Placed” event might update stock or email the customer:</p><pre>class OrderPlacedEvent<br>  attr_reader :order_id<br><br>  def initialize(order_id)<br>      @order_id = order_id<br>  end<br>end<br><br>module Orders<br>  class Order &lt; ApplicationRecord<br>    after_create :publish_order_placed<br><br>    private<br>    def publish_order_placed<br>      RailsEventStore.publish(OrderPlacedEvent.new(id))<br>    end<br>  end<br>end</pre><h3>Why It Helps</h3><p>Events keep the app in sync. In a startup, missing a stock update after an order led to overselling. Events ensure every part reacts to changes, boosting reliability. It’s like a team shout-out — everyone’s updated instantly.</p><h3>Example</h3><p>The team sets up an “Order Placed” event. When an order is complete:</p><ul><li>Orders triggers the event.</li><li>Inventory reduces stock.</li><li>Customers logs the purchase.</li></ul><p>This coordination keeps the marketplace running smoothly, keeping users happy.</p><h3>Benefits of DDD in Rails</h3><p>Using DDD in Rails delivers:</p><ul><li><strong>Business Fit</strong>: Code mirrors processes, like order flows, making features easy to add.</li><li><strong>Clean Code</strong>: Contexts and repositories organize the app, simplifying fixes.</li><li><strong>Growth-Ready</strong>: Separate contexts let the app scale, handling more orders.</li></ul><p>Teams deliver features faster, and managers get apps that match their vision, like moving from a cluttered room to a sleek office.</p><h3>Challenges to Watch For</h3><p>DDD in Rails takes work. Teams need time to learn ideas like aggregates. Setting up contexts and repositories requires effort. Collaboration with business experts is a must. Rushing can lead to messy code, but starting small avoids this. We’ll tackle these challenges in the next chapter.</p><h3>What’s Next?</h3><p>This chapter showed how to apply DDD in Ruby on Rails, using an online marketplace to model business needs. We saw how principles become code that’s clear and scalable. But what happens when things get tough? In Chapter 4, we’ll explore common DDD challenges in Rails, like setting boundaries or testing, and share tips to overcome them.</p><p>How could DDD tidy up your Rails app? Think about it as we dive deeper. DDD is your path to software that powers your startup’s success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be6bb5b97dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 2: Core Principles of Domain-Driven Design]]></title>
            <link>https://samkhosravi.medium.com/chapter-2-core-principles-of-domain-driven-design-066b22121553?source=rss-36388c1f4b3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/066b22121553</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[business-development]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sam Khosravian]]></dc:creator>
            <pubDate>Tue, 20 May 2025 20:59:35 GMT</pubDate>
            <atom:updated>2025-05-20T20:59:35.963Z</atom:updated>
            <content:encoded><![CDATA[<p>In Chapter 1, we saw how Domain-Driven Design (DDD) brings startup teams together, creating software that grows with the business. It’s like a shared map, guiding developers and managers to focus on what matters most — the company’s heart. But what makes DDD so effective? This chapter breaks down the core principles of DDD in simple terms, showing how they simplify complex business needs and keep code clear. Using an online store as an example, we’ll explore these ideas and why they transform projects. By the end, you’ll understand the building blocks of DDD and how they set your startup up for success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*OCfXiVadXguGy_l_doGevQ.jpeg" /></figure><h3>Why Principles Make DDD Work</h3><p>Startups juggle a lot: rapid growth, shifting plans, and tricky business rules. Picture an online store managing orders, stock, and customer details. Without a clear plan, the software turns into a jumble, and teams clash over terms like “order” or “item.” DDD’s principles cut through this mess, organizing complexity and aligning everyone. They ensure the app reflects the business, saving time and reducing headaches. Let’s dive into the seven key principles, with examples to make them easy to grasp.</p><h3>Principle 1: Focus on the Business (Domain-Centric Approach)</h3><p>DDD starts with the business — what it does and why it’s unique. This <em>domain-centric approach</em> means understanding the company’s core before writing code. For an online store, the heart is handling orders, from adding items to a cart to delivering them. DDD asks teams to dig deep, working closely with business experts like managers or sales staff to get it right.</p><p>This teamwork is crucial. Developers and managers map out how the business runs. What’s an order? How do payments work? By answering these, the software solves real business problems, not just technical ones.</p><h4>Why It Helps</h4><p>Skipping this step spells trouble. Many startups code first, only to find the app doesn’t match the business needs, like missing special discounts for loyal customers. The result? Bugs and delays. DDD’s business focus prevents these errors, ensuring the app supports the company’s goals. It’s like sketching a house before building it — you know it’ll stand strong.</p><h4>Example</h4><p>For the online store, the team pinpoints the core: order processing. They learn from experts that an order includes items, a total price, and a status, like “pending.” This guides every choice, ensuring the app drives sales smoothly. Developers work with purpose, and managers see their ideas take shape.</p><h3>Principle 2: Speak the Same Language (Ubiquitous Language)</h3><p>Misunderstandings hurt teamwork. If developers call a purchase an “order” but managers call it a “sale,” confusion grows. DDD fixes this with a <em>ubiquitous language</em> — a shared set of words everyone uses, from meetings to code. For the online store, the team agrees: an “order” is a customer’s purchase with items and a price. This term appears in plans, chats, and software, keeping everyone on the same page.</p><h4>Why It Helps</h4><p>A shared language saves time and cuts errors. Without it, teams waste hours debating terms, like whether “payment” means a customer’s click or the bank’s approval. DDD’s language ensures clarity, letting ideas move smoothly from managers to developers. It’s like everyone using the same words — no translation needed.</p><h4>Example</h4><p>The store’s team defines:</p><ul><li><strong>Order</strong>: A customer’s purchase, with items and status.</li><li><strong>Item</strong>: A product in an order, with quantity and price.</li><li><strong>Customer</strong>: A person with a name and purchase history.</li></ul><p>These words show up in code and talks. When a manager says, “Track order status,” developers know exactly what to do. This clarity speeds up work and reduces mix-ups.</p><h3>Principle 3: Break It Down (Bounded Contexts)</h3><p>Big businesses are complex. An online store handles orders, inventory, and customers all at once. Mixing these in one codebase creates chaos. DDD uses <em>bounded contexts</em> to split the business into smaller, clear areas. Each context is like a mini-world with its own rules and terms.</p><p>For the store, the team sets three contexts:</p><ul><li><strong>Order Management</strong>: Covers order creation and payments.</li><li><strong>Inventory Management</strong>: Tracks product stock.</li><li><strong>Customer Management</strong>: Handles user profiles.</li></ul><p>In Order Management, “product” means an item in a cart. In Inventory Management, it’s about stock levels. This separation keeps each area focused.</p><h4>Why It Helps</h4><p>Bounded contexts tame complexity. Without them, orders might process without checking stock, upsetting customers. Each context works independently but connects when needed, making code easier to manage and grow. It’s like sorting books into library sections — finding what you need is quick and simple.</p><h4>Example</h4><p>The team defines Order Management to handle orders and payments, with rules like “no order without payment.” Inventory Management ensures products are in stock. Each context has its own code, so developers can tweak orders without breaking inventory. This keeps the store reliable, even as sales soar.</p><h3>Principle 4: Organize Objects (Entities and Value Objects)</h3><p>DDD sorts business ideas into two types of objects: <em>entities</em> and <em>value objects</em>. This keeps code clear and logical.</p><h4>Entities: Unique and Changeable</h4><p>Entities have a unique identity, like a key, and can change over time. For example, a customer has a unique ID. Their address might update, but they’re still the same person, tracked by that ID.</p><h4>Value Objects: Fixed and Equal</h4><p>Value objects are set and compared by their values, not an ID. A price, like $50 USD, is a value object. Two $50 USD prices are the same, no matter where they’re used. They don’t change once created.</p><h4>Why It Helps</h4><p>Sorting objects prevents mistakes. Mixing up types, like treating prices as entities, can cause errors, such as wrong comparisons. DDD’s approach ensures objects act as expected, making code easier to fix and understand. It’s like labeling tools in a box — you pick the right one every time.</p><h4>Example</h4><p>For the store:</p><ul><li><strong>Entity</strong>: Customer. A unique ID tracks each customer, even if their email changes.</li><li><strong>Value Object</strong>: Money. A price, like $50 USD, is compared by amount and currency.</li></ul><p>The team models these carefully, so developers and managers discuss customers and prices without confusion, keeping the app aligned with the business.</p><h3>Principle 5: Group Objects Wisely (Aggregates)</h3><p>Some objects belong together. DDD uses <em>aggregates</em> to group related entities and value objects into one unit, led by an <em>aggregate root</em>. The root ensures everything stays consistent. For the store, an order is an aggregate root, including order items (entities) and a total price (value object). The order checks that all items are valid and the total is correct.</p><h4>Why It Helps</h4><p>Aggregates enforce rules. Without them, you might change an order item without updating the order, leading to errors like wrong totals. Aggregates keep the app reliable, ensuring business logic holds. It’s like a coach guiding a team — everyone plays in sync.</p><h4>Example</h4><p>The team defines an “Order” aggregate:</p><ul><li><strong>Aggregate Root</strong>: Order. Tracks ID, status, and total.</li><li><strong>Included</strong>: Order Items. Each has a product, quantity, and price.</li><li><strong>Rule</strong>: The total must equal the sum of item prices.</li></ul><p>The order ensures no item is added without updating the total, keeping the code clean and accurate.</p><h3>Principle 6: Manage Data Smartly (Repositories)</h3><p>Data is vital, but it can clutter code. DDD uses <em>repositories</em> to handle data, like a librarian finding books. A repository fetches or saves objects, like orders, without mixing database details into business logic. This keeps the code focused and flexible — you can switch databases without rewriting the app.</p><h4>Why It Helps</h4><p>Repositories prevent chaos. Scattered database code makes updates hard. Repositories centralize data tasks, letting developers focus on the business. They also simplify testing by faking data. It’s like storing files in one drawer, not all over the desk.</p><h4>Example</h4><p>The store’s team creates an “OrderRepository” to:</p><ul><li>Find an order by ID.</li><li>Save an order and its items.</li></ul><p>The repository hides database complexity, so the code stays about orders, not storage. Switching databases only changes the repository, saving effort.</p><h3>Principle 7: Track Key Moments (Domain Events)</h3><p>Businesses have big moments, like an order being placed. DDD uses <em>domain events</em> to capture these, notifying other parts of the app. For example, an “Order Placed” event might update stock or email the customer.</p><h4>Why It Helps</h4><p>Events keep everything in sync. Without them, missing a stock update after an order can lead to overselling. Domain events ensure every part of the business responds, boosting reliability. It’s like a news flash — everyone gets the update instantly.</p><h4>Example</h4><p>The team defines an “Order Placed” event:</p><ul><li>Order Management triggers it when an order is complete.</li><li>Inventory Management lowers stock.</li><li>Customer Management updates the customer’s history.</li></ul><p>This teamwork keeps the store running smoothly, delighting customers.</p><h3>How These Principles Connect</h3><p>DDD’s principles work together like a well-oiled machine. The business focus sets the goal: build what the company needs. The shared language ensures everyone gets it. Bounded contexts simplify complexity. Entities, value objects, and aggregates structure the code. Repositories and events manage data and actions. Together, they create apps that are clear, scalable, and tied to the business.</p><p>For the online store, this means:</p><ul><li>Developers write code that nails business rules, like accurate orders.</li><li>Managers see features, like discounts, launch fast.</li><li>Teams use the same terms, avoiding slip-ups.</li></ul><p>These principles turn messy projects into wins, with less arguing and quicker results. It’s like fitting puzzle pieces together — each one builds a clear picture.</p><h3>Challenges to Watch For</h3><p>DDD isn’t a breeze. These principles take time to learn, especially for new teams. Setting bounded contexts can be tricky — where does one end? The shared language needs constant agreement, which takes effort. Aggregates and repositories must be built carefully to avoid confusion. These hurdles are worth it, though, for the teamwork and clean code DDD brings. We’ll tackle solutions in later chapters.</p><h3>What’s Next?</h3><p>This chapter explained DDD’s core principles, showing how they align teams and tame complexity. But how do you turn these ideas into code? In Chapter 3, we’ll dive into using DDD with Ruby on Rails, with examples to model an online store’s orders, aggregates, and more. You’ll see these principles come alive in a working app.</p><p>Which DDD principle could spark your team’s next win? Think about it as we move to coding. DDD is your tool to create software that fuels your startup’s success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=066b22121553" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 1: Why Domain-Driven Design Matters for Startups]]></title>
            <link>https://samkhosravi.medium.com/chapter-1-why-domain-driven-design-matters-for-startups-35a8762396d7?source=rss-36388c1f4b3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a8762396d7</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Sam Khosravian]]></dc:creator>
            <pubDate>Mon, 19 May 2025 19:53:15 GMT</pubDate>
            <atom:updated>2025-05-19T19:53:15.875Z</atom:updated>
            <content:encoded><![CDATA[<p>Startups are exciting, fast-paced, and full of big ideas. But there’s a common hurdle: developers and managers often don’t speak the same language. Developers dive into code and databases, while managers focus on customers and growth. This disconnect creates confusion, slows projects, and sparks frustration. There’s a solution that brings everyone together — Domain-Driven Design, or DDD. This approach helps teams build software that matches the business’s heart, saving time and boosting success. Let’s explore what DDD is, why it’s perfect for startups, and how it unites teams to create apps customers love.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*kox20huHTrMlcPDSjF6pUg.jpeg" /></figure><h3>What Is Domain-Driven Design?</h3><p>Domain-Driven Design is a way to build software that puts the business first. Think of it as a map that turns your company’s unique ideas into clear, working code. Instead of starting with technical details like servers or tables, DDD focuses on understanding what your business does. For example, in an online store, what’s an order? How do customers buy products? These questions guide the software’s design.</p><p>DDD is ideal for startups with complex needs, like managing orders, tracking inventory, or handling payments. Without a plan, the code can become a messy knot, hard to fix or grow. DDD cuts through this chaos by creating a model that reflects the business, making it easy for developers and managers to understand. It’s like drawing a clear picture everyone can follow.</p><h3>A Startup Story</h3><p>Picture a startup launching an online marketplace. The managers want cool features — think discounts or loyalty programs — but the developers are stuck. The code is jumbled, and every change breaks something. This isn’t about skill; it’s about communication. Managers talk about “customer experiences,” while developers worry about “database queries.” Sound familiar? DDD solves this by giving teams a shared way to talk and work, focusing on the business itself.</p><h3>Why Startups Need DDD</h3><p>Startups move at lightning speed, testing ideas, launching products, and scaling up, all on a tight budget. But rushing can lead to mistakes, like code that’s tough to update or features that miss the mark. DDD helps startups avoid these traps in four key ways, making it a must-have tool.</p><h3>1. Teamwork Through a Shared Language</h3><p>In many startups, developers and managers don’t fully get each other. A manager might say, “Make checkouts faster,” but developers think, “Which part of the code?” DDD creates a <em>shared language</em> — words like “order,” “customer,” or “payment” that everyone agrees on. These terms show up in meetings, plans, and code, cutting confusion.</p><p>For example, the marketplace team might define “order” as a customer’s purchase, including items and payment details. Developers use “Order” in their app, and managers use it in strategies. This clarity aligns everyone, like giving the team a single playbook to win the game.</p><h3>2. Handling Complex Business Rules</h3><p>Startups often have tricky rules. Imagine the marketplace has a rule: “Give a 10% discount on orders over $100, but only for new customers.” Without a clear method, these rules get lost in messy code, causing bugs. DDD breaks the business into smaller chunks, called <em>subdomains</em>, like Orders, Inventory, or Customers. Each chunk has its own rules, making them easier to manage.</p><p>DDD also uses <em>bounded contexts</em> to keep these chunks separate. A bounded context is like a mini-world with its own rules. For instance, a “product” in Orders (something in a cart) is different from a “product” in Inventory (stock on hand). This separation keeps the code organized, even as the business grows.</p><h3>3. Software That Grows with You</h3><p>Startups evolve fast. One day, the marketplace is a small shop; the next, it’s handling thousands of orders. DDD builds apps that adapt. By modeling the business, the code mirrors how the company works. When managers want a new feature, like gift cards, developers can update the model without starting over. This saves time and money.</p><p>DDD also keeps the code clean by avoiding shortcuts that pile up as <em>technical debt</em>. Regular improvements, called refactoring, ensure the app stays tidy. It’s like cleaning your desk daily instead of letting clutter build up.</p><h3>4. Happier Teams, Better Results</h3><p>DDD makes everyone feel valued. Developers love that the code is clear and tied to the business. Managers appreciate that features launch quickly and match their vision. This teamwork boosts morale and productivity. Startups using DDD see less arguing and more building, with everyone focused on creating a product customers adore.</p><h3>How DDD Unites Developers and Managers</h3><p>Misalignment between teams can quietly hurt a startup. Developers want neat code; managers want quick results. DDD brings them together by making the business the star. Here’s how it happens.</p><h3>A Shared Mission</h3><p>DDD begins with teamwork. Developers, managers, and business experts meet to define the <em>core domain</em> — the most important part of the company. For the marketplace, it’s processing orders smoothly. This shared goal unites everyone. Developers aren’t just coding; they’re solving business problems. Managers aren’t just setting deadlines; they’re shaping the app’s heart.</p><h3>Clear Communication</h3><p>The shared language is a game-changer. In one startup, teams wasted time debating what “payment” meant — when a customer clicked “buy” or when the bank confirmed it? DDD makes teams agree on one meaning and use it everywhere. The result? Fewer errors and faster launches. It’s like everyone speaking the same language, making ideas flow from planning to coding.</p><h3>Tools to Connect Vision and Code</h3><p>DDD provides tools like <em>entities</em>, <em>value objects</em>, and <em>aggregates</em> to turn business ideas into reality. An entity is something unique, like a customer with an ID, even if their address changes. A value object is fixed, like a price ($50 USD). An aggregate groups related items, like an order with its products, to keep things consistent. These tools let developers build exactly what managers imagine, closing the gap between dreams and reality.</p><h3>Why Skipping DDD Hurts Startups</h3><p>Ignoring DDD might feel faster — just code and go. But the cost is steep:</p><ul><li><strong>Messy Code</strong>: Hard to fix, full of bugs.</li><li><strong>Team Tension</strong>: Developers and managers point fingers.</li><li><strong>Missed Chances</strong>: Slow updates lose customers.</li></ul><p>DDD is worth the effort. It keeps code clear, teams aligned, and apps ready to grow. For the marketplace, DDD could mean launching loyalty programs in weeks, not months, keeping customers happy and profits up.</p><h3>How to Start with DDD</h3><p>Ready to try DDD in your startup? Here’s a simple plan:</p><ul><li><strong>Gather Your Team</strong>: Bring developers, managers, and business experts together to talk about what your company does best.</li><li><strong>Start Small</strong>: Focus on one area, like orders. Define its key terms and rules.</li><li><strong>Learn the Basics</strong>: Explore DDD ideas like entities and bounded contexts. Online guides or books are a great start.</li><li><strong>Try It Out</strong>: Use DDD on a small feature to see how it feels with a shared language and clear model.</li></ul><p>It might seem tough at first, but DDD gets easier with practice. Each step strengthens your app and team.</p><h3>What’s Next?</h3><p>This chapter introduced DDD and why it’s a must for startups. It aligns teams, simplifies complex rules, and builds apps that grow with you. But how do you make DDD work in a real project? In Chapter 2, we’ll explore DDD’s core principles — like shared language, bounded contexts, and aggregates — and show how they come to life in a Ruby on Rails app.</p><p>What’s one way your team could communicate better? Think about it as you read on. DDD is your path to a startup that thrives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a8762396d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 1: Gardening with AI: Making Your Green Thumb Greener with Simple Regression Models]]></title>
            <link>https://samkhosravi.medium.com/episode-1-gardening-with-ai-making-your-green-thumb-greener-with-simple-regression-models-fdb83d260c23?source=rss-36388c1f4b3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdb83d260c23</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[torch]]></category>
            <dc:creator><![CDATA[Sam Khosravian]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 14:33:07 GMT</pubDate>
            <atom:updated>2023-07-09T14:40:47.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GsjABrvXbneAK2_YfZABw.jpeg" /><figcaption>AI whispers to the soil, and the garden grows.</figcaption></figure><h3><strong>Introduction</strong></h3><p>Hey there! Welcome back to our blog. Today, we’re going to mix our love for nature with a dash of tech magic — artificial intelligence (AI). Isn’t that cool?</p><p>Ever found yourself staring at your wilting roses or drooping tomatoes, wondering what you did wrong? You gave them enough sunlight, water, and the soil seemed fine. So, what’s the issue? It’s like your plants are trying to tell you something, but you just can’t understand.</p><p>Now, imagine if you had a ‘plant translator’, right?</p><p>Imagine an app that takes a few details about your garden — how much sunlight it gets, how much it rained recently, the soil’s pH level — and gives you a prediction about your garden’s health. Maybe it’s too much sun, or you need to water them less. Wouldn’t that be a game-changer?</p><p>Well, this isn’t some fantasy. This is real, and it’s called deep learning using regression models. Think of regression models as the ‘crystal ball’ of AI. You feed them some information, and they give you predictions.</p><p>For our plants, this ‘crystal ball’ predicts how healthy your garden will be. With this data, the AI models can help your garden bloom just as you dreamed.</p><p>In this post, we’ll explore how these fantastic regression models work. We’ll take a journey into AI and deep learning, and see how it can help your garden. Are you ready to mix your green thumb with some AI? Keep reading, and let’s dig in!</p><h3>Unveiling the Magic of Regression Models</h3><p>Let’s dive into the fascinating world of regression models in deep learning. Picture this: deep learning is like a keen detective in your garden, carefully examining how factors like sunlight, watering, and soil composition affect your plants’ growth.</p><p>In this detective story, regression models are the magnifying glass, revealing the hidden links and patterns between these factors. They transform complex data into a picture we can understand, just like a painter turning a beautiful landscape into a masterpiece.</p><p>To visualize a regression model, imagine a web of connected dots. Each dot represents a factor affecting your plants — like how long they’ve been growing, or how much sunlight they get. The lines between the dots, called weights, show how important each factor is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Bkh-4Dwu0nQtPGwqFXANtQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Regression_analysis">Linear Regression</a></figcaption></figure><p>Let’s use the factors “growth time” and “sunlight” as an example. The weight of each factor shows how much it influences the plants’ growth. If the “growth time” weight is heavy, it means this factor plays a major role in the plant’s height. On the contrary, if the “sunlight” weight is heavy, it implies that sunlight has a bigger impact on the plant’s growth.</p><p>In the training phase, the regression model adjusts these weights based on the patterns it finds in the data. It’s like the model is learning from experience. It gives more importance to factors with a stronger influence on the height, and less importance to weaker ones.</p><p>As it sifts through the data, the regression model creates a mathematical formula that represents the connections between the factors. With this formula and the adjusted weights, the model can predict the height of a plant based on the input factors, even for new and unseen data.</p><p>In the world of deep learning, regression models are invaluable for revealing complex relationships and making useful predictions. They learn, adapt, and provide insights beyond simple correlations.</p><p>Next, we’ll dive deeper into how to gather and prepare data for training a regression model. So, buckle up for this exciting journey into the world of AI-enhanced gardening!</p><h3>Creating Your Garden’s Data Diary with AI</h3><p>As we’ve embarked on this exciting journey into AI-enhanced gardening, let’s step into the shoes of our plants. Consider every individual in your garden meticulously jotting down the story of their growth — the hours of sunshine they reveled in, the unique pH of their nurturing soil, the moisture level of their surroundings, and notably, their upward growth. Just like entries in a diary, each line of our dataset will record these attributes for 1000 plants in our AI-nurtured garden.</p><p>Our ‘garden diary’ would be somewhat like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a59b0623a962bc74987f637cbc632731/href">https://medium.com/media/a59b0623a962bc74987f637cbc632731/href</a></iframe><p>Imagine each datapoint as a seedling in our garden. The parameters like ‘Growing Days’, ‘Soil pH’, ‘Sunlight Hours’, and ‘Humidity’ are the environmental factors, the sunlight, the rain, and the soil nourishing the seedling. ‘Plant Height’ is our blossoming flower, the one we are eagerly watching grow.</p><p>In this garden, our regression model is akin to a seasoned gardener, who understands how these environmental factors, like sunlight and rain, affect the growth of the flower. With our regression model, we aim to predict how tall our flower will grow based on its environmental factors, the nourishment it receives.</p><p>With the power of Python, alongside the pandas and numpy libraries, we can orchestrate similar dramas for our AI director to understand:</p><pre>import pandas as pd<br>import numpy as np<br><br># Number of plants<br>n = 1000<br><br># Create the dataframe<br>df = pd.DataFrame({<br> &#39;Plant ID&#39;: np.arange(1, n+1),<br> &#39;Growing Days&#39;: np.random.randint(20, 50, n),<br> &#39;Soil pH&#39;: np.random.uniform(6.0, 7.5, n).round(1),<br> &#39;Sunlight Hours&#39;: np.random.uniform(5.0, 9.0, n).round(1),<br> &#39;Humidity&#39;: np.random.randint(50, 80, n),<br> &#39;Plant Height&#39;: np.random.randint(20, 50, n)<br>})<br><br># Display the first 5 rows of the dataframe<br>print(df.head())</pre><p>Once we’ve gathered the data, we prepare it for our AI director. We split it into two acts — a training act, where the model learns the roles and relationships, and a testing act, which gauges how well our director can predict the performance based on the cast.</p><p>In the next step, we’ll hand over this garden scene to our regression model and observe how it unravels the relationships to make predictions. Brace yourself as we continue on this exhilarating journey of AI-assisted gardening!</p><h3>Applying Regression Models: The Detailed Journey of the AI Garden</h3><p>Embarking on our AI-assisted gardening adventure, we’ll leverage a deep learning technique called regression modeling. This process starts with data collection about our garden’s conditions such as sunlight, soil pH, and humidity. We’ll split this data into training and testing sets for our model to learn from and be evaluated on. Using an Artificial Neural Network (ANN), the model will process the data through multiple layers, adjusting weights and biases to improve prediction accuracy. After iterative learning and fine-tuning, we’ll assess the model’s performance using the testing data. Join us as we delve into this exciting journey of turning our AI model into an expert gardener.</p><h4>Training and Testing Data</h4><p>Think of the training and testing data as a student’s journey through school. The training set is like the regular school days, full of lessons, experiments, and hands-on learning. It’s where the student (our AI model) gathers knowledge, understanding concepts and their relationships, much like how a student understands different subjects and topics at school. In our garden context, the ‘subjects’ would be the various factors like sunlight hours, soil pH, and humidity, among others. This training period forms the majority of the learning process, which is why we use about 80% of our data for this stage.</p><p>On the other hand, the testing set is akin to the final exams at the end of the school year. It’s a chance to evaluate how much the student (our AI model) has understood and how effectively they can apply their knowledge to new, unseen questions (data). In our garden scenario, these would be new sets of sunlight, soil, and humidity conditions. This ‘exam’ is critical because it provides a realistic gauge of the model’s ability to predict plant growth in different situations. That’s why we set aside about 20% of our data for this crucial assessment phase.</p><p>By using training and testing data, we ensure that our AI model is well-equipped to understand the complex relationships in our garden and make accurate predictions, much like a well-educated student ready to tackle real-world problems.</p><h4>Input Layer</h4><p>Imagine a field researcher diligently measuring the garden’s conditions every day — the amount of sunlight, the pH of the soil, the humidity, and the growing days for each plant. The results of these measurements, these exact numeric values, serve as the inputs for our model.</p><p>Now, in our ANN, each neuron in the input layer corresponds to one type of measurement, i.e., one input feature. For example, one neuron will receive the value for sunlight hours, another for soil pH, another for humidity, and yet another for the number of growing days.</p><p>It’s as if we’re giving each neuron a specific task — “You, neuron A, take the sunlight data; you, neuron B, handle the soil pH data,” and so on. It’s important to note that these neurons aren’t “in charge of” or “tracking” the data in the sense that they’re not actively measuring or observing these factors; rather, they’re receptacles for the data we’ve measured and collected.</p><p>These neurons in the input layer receive the raw data and pass it on to the next layer of neurons (the hidden layer) in a processed form, ready for the complex task of identifying patterns and relationships. The way these neurons pass on the information depends on the weights and bias, which initially can be random values, but will be optimized during the training process.</p><p>So, in summary, the input layer of an ANN in our scenario acts like the data collection station, receiving the raw gardening data that we’ve collected and starting the process of feeding this information through the neural network.</p><h4>Hidden Layers</h4><p>Imagine the hidden layers in our neural network as a team of seasoned gardeners who are experienced in identifying specific patterns that influence plant growth. Each gardener represents a neuron in the hidden layer, and they each specialize in recognizing certain growth patterns or factors.</p><p>Now, let’s introduce the concept of ‘weights’ and ‘biases.’ In our garden analogy, consider ‘weights’ as the level of importance each gardener assigns to different growth factors. Some gardeners might believe that sunlight is the crucial element, while others might advocate for soil pH or humidity. These ‘weights’ are like the gardeners’ beliefs on the significance of each factor on plant growth.</p><p>In the beginning, these ‘weights’ are assigned randomly. However, as the gardeners (neurons) continue to observe and learn from the garden’s behavior (during the training phase), they adjust their ‘weights.’ This is similar to how our experienced gardeners might change their beliefs about what’s most important for plant growth as they gather more insights and experiences.</p><p>‘Biases,’ on the other hand, are akin to each gardener’s unique perspective or intuition that they bring to the table based on their individual experiences. Some gardeners might have an inherent belief that certain types of plants always grow taller, irrespective of the external conditions. These inherent beliefs act as ‘biases’ in our neural network, nudging the network’s decision in a certain direction.</p><p>The crucial role of these hidden layers is to perform complex calculations with the input data, taking into account these weights and biases. The objective is to identify patterns that significantly predict a plant’s height. As the neurons learn and adjust, the ‘weights’ and ‘biases’ are fine-tuned to help the model make the most accurate predictions.</p><p>Each neuron in the hidden layer has a different set of weights and biases, allowing them to recognize and emphasize different patterns in the data. As the processed information flows through the hidden layers, the layers collectively capture a comprehensive understanding of the factors influencing plant growth.</p><p>Remember, though, we often cannot directly interpret the computations in these hidden layers. They’re called ‘hidden’ for a reason — their operations are like a black box to us. But they are essential for our model to understand complex patterns and make accurate predictions.</p><p>So, in summary, the hidden layers of our AI model, equipped with their adjusted ‘weights’ and ‘biases’, work like a team of expert gardeners decoding patterns in our garden, offering a deeper understanding of what contributes to healthy plant growth.</p><h4>Activation Function</h4><p>Let’s now move to the concept of ‘activation functions,’ an essential mechanism in neural networks.</p><p>Think of the activation function as a gatekeeper in our garden scenario. After the gardeners (neurons) in the hidden layer have done their job of assessing the factors affecting plant growth and weighing their importance (using the weights and biases), it’s the gatekeeper’s task to decide what information should be passed forward.</p><p>An activation function in a neural network does just that. It takes in the output from a neuron (the calculated weights and biases) and decides whether this output is relevant enough to be passed on to the next layer. This decision is made based on a certain threshold.</p><p>For instance, if we use a simple activation function like ReLU (Rectified Linear Unit), it works like a gatekeeper who lets through all positive information and blocks all negative. In other words, if the output from a neuron is positive, it gets passed on to the next layer. If it’s negative, it’s set to zero and not transferred forward. This kind of gatekeeping is useful when we want to introduce non-linearity into our model, helping it learn from not just simple but also complex and diverse patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfIE6Ht4Xa0hpiefmgjdcg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a></figcaption></figure><p>However, not all activation functions are like ReLU. There are many other types of activation functions such as Sigmoid, Tanh, or Softmax, each having different rules for what information gets passed on. Choosing the right activation function depends on the specific requirements of the neural network and what kind of data it’s dealing with.</p><p>In summary, activation functions serve as gatekeepers in our AI model, deciding what information, derived from the patterns observed by our gardener-neurons, should be passed forward. This helps in filtering out the noise and focusing on the most impactful factors influencing our plant’s growth.</p><h4>output layer</h4><p>The output layer in our neural network can be seen as the grand finale of our garden scenario, the last phase of our AI’s work. This is where we reap the fruits of our labor and see the final predictions made by the model.</p><p>Consider the output layer as our Chief Gardener. After all the data analysis, decision making, and pattern recognition done by the various staff members (neurons in input and hidden layers) and the gatekeepers (activation functions), the Chief Gardener takes all this processed information to make the final call. The Chief Gardener’s decision represents the neural network’s final prediction — in our case, the predicted plant height.</p><p>The neurons in the output layer take the information passed on by the last hidden layer, apply another round of weights, biases, and activation function, and output the final result. This result could be a single value (as in our case, where we’re predicting a single value — the plant’s height) or multiple values depending on the problem at hand.</p><p>For instance, if our AI model is predicting whether a plant will be healthy (yes or no), then our output layer will have two neurons, each giving the probability of ‘yes’ and ‘no’. The neuron with the higher probability decides the final prediction.</p><p>In our case, however, as we are predicting the plant’s height (a continuous value), our output layer has just one neuron. This neuron gives the final prediction of the plant’s height based on all the processed information it received.</p><p>In a nutshell, the output layer in our AI model acts as the Chief Gardener, bringing together all the analyses and decisions made in the previous layers to provide a final prediction — the anticipated height of our plant.</p><h4>Learning from Errors</h4><p>Learning from Errors, also known as backpropagation, is like a crucial feedback session in our garden scenario. Imagine you’ve been growing a specific type of flower in your garden and expecting it to grow to a certain height. However, after a couple of weeks, you realize the flowers are not growing as tall as expected. What do you do? You take a step back, analyze what might have gone wrong, and make necessary adjustments to your gardening strategy.</p><p>In our AI model, this is exactly what backpropagation does. When the output layer (the Chief Gardener) makes a prediction about the plant’s height, this predicted value is compared to the actual height of the plant from our training dataset. The difference between the predicted and actual values is the “error” made by the model.</p><p>In a perfect world, our AI model would predict the exact plant height every time, but in reality, this isn’t usually the case, especially not in the beginning. There will be some errors, and these errors are essential for the model to learn and improve.</p><p>The model investigates these errors much like a gardener would scrutinize their plants. It uses a technique called “gradient descent” to minimize these errors. The gradient descent process is like the model’s way of tracing its steps back through the garden to identify where things might have gone wrong. It adjusts the weights and biases in the hidden layers and the output layer — the factors that determine how much importance is given to each input — in a direction that will reduce the error.</p><p>This process of feedback, adjustment, and learning from errors is repeated multiple times, over many cycles (or “epochs”). With each cycle, the model adjusts its weights and biases a bit more, getting better and better at making accurate predictions.</p><p>In essence, learning from errors through backpropagation is the model’s way of perfecting its strategy, making it a more effective and accurate predictor of plant height in our AI-assisted garden.</p><h4>Error Calculation</h4><p>This is a critical step in understanding how well our model is performing. Consider it as a performance review for our AI gardener. We need a way to quantitatively assess how accurately our model is predicting the plant heights compared to the actual measurements.</p><p>We do this by calculating the ‘loss’ or the ‘cost’, terms used interchangeably to describe the numerical difference between our model’s predictions and the actual values. In our gardening analogy, it’s like measuring the gap between the expected height of our plants and their actual heights.</p><p>To calculate this loss, we use a Loss Function. In the case of regression problems like ours, a commonly used loss function is the Mean Squared Error (MSE). The MSE measures the average of the squares of the errors — that is, the average squared difference between the predicted and actual values.</p><p>Imagine if our AI gardener expects a rose to grow 10 inches tall, but it only reaches 8 inches. The error here would be 2 inches. The MSE squares this error (resulting in 4 in this case), and does so for each plant, then averages these squared errors to get the mean squared error. This gives us a numerical value that represents the average error in our model’s predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*yyTcs4Lb-nncuVXOXvxL1w.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean Squared Error</a></figcaption></figure><p>Our goal is to minimize this loss. A lower MSE means our predictions are closer to the actual values, implying a better-performing model. We use the backpropagation and gradient descent processes, as discussed earlier, to adjust our model in an attempt to reduce this error.</p><p>In essence, the process of error calculation and minimization is an ongoing performance review and improvement effort for our model, ensuring our AI gardener becomes more and more proficient at predicting the heights of plants as it continues learning.</p><p>So there you have it, we’ve covered the main steps and components of a neural network used for regression tasks, from data collection and preparation, through the layers of the neural network, to learning from errors and minimizing them. With this understanding, we’re now ready to delve into the practical application using PyTorch and TensorFlow.</p><h4>Walking Through an Example</h4><p>You can find the Torch Full code with good documentation here:</p><p><a href="https://github.com/hdkhosravian/deep_learning_tutorial/blob/main/Gardening_with_AI_Making_Your_Green_Thumb_Greener_with_Simple_Regression_Models_Torch.ipynb">deep_learning_tutorial/Gardening_with_AI_Making_Your_Green_Thumb_Greener_with_Simple_Regression_Models_Torch.ipynb at main · hdkhosravian/deep_learning_tutorial</a></p><h3>Summary</h3><p>In this article, we’ve learned the basic concepts and steps of building, training, and evaluating a simple linear regression model using PyTorch. The learning process of our model has been compared to a gardener’s efforts to grow his plants efficiently.</p><ol><li>Creating a Dataset: We generated a dataset that mimics the gardening scenario, where factors like ‘Growing Days’, ‘Soil pH’, ‘Sunlight Hours’, ‘Humidity’ influence the ‘Plant Height’. The data was normalized to ensure efficient learning.</li><li>Data Splitting: We split the data into training and testing sets. The training set is used for the learning process, while the testing set is used to evaluate the model’s performance on unseen data.</li><li>Model Definition: A simple linear regression model with 4 input features (parameters influencing plant growth) and 1 output feature (plant height) was created.</li><li>Activation Function: We described the activation function (ReLU) as a gatekeeper that lets positive signals pass through to the next layer.</li><li>Loss Function and Optimizer: We defined Mean Squared Error as our loss function (like the gardener measuring his error in predicting plant growth) and Stochastic Gradient Descent as our optimizer (the gardener’s action plan to minimize this error).</li><li>Model Training: The model learned from the training data by adjusting its parameters. It used the backward() function to calculate the gradients (directions to improve) and the step() function to update parameters accordingly.</li><li>Model Evaluation: We tested the trained model on the test data to assess how well it had learned from the training process.</li></ol><p>By understanding these concepts and steps, we can better grasp how machine learning models learn from data to make predictions, similar to how a gardener iteratively refines his gardening methods based on his observations and results.</p><h3>What’s next?</h3><p>In the next episode of this series, “Episode 2: A Friendly Introduction to Classification,” we’ll delve into the world of classification problems. We’ll learn how to set up a supervised learning model using an Artificial Neural Network (ANN) to classify data. We will continue to leverage our gardening analogy to make complex concepts intuitive and easy to grasp. Stay tuned for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdb83d260c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Episode 0: Jumping into the Fun World of AI, Deep Learning, and Neuroscience — My Personal Journey]]></title>
            <link>https://samkhosravi.medium.com/episode-0-jumping-into-the-fun-world-of-ai-deep-learning-and-neuroscience-my-personal-journey-73b448255995?source=rss-36388c1f4b3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b448255995</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[personal-journeys]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sam Khosravian]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 16:44:43 GMT</pubDate>
            <atom:updated>2023-06-09T16:44:43.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>Episode 0: Jumping into the Fun World of AI, Deep Learning, and Neuroscience — My Personal Journey</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YgOtFB7F0CZPVq7snwv_-Q.jpeg" /><figcaption>brain with neural connections</figcaption></figure><p>Hey everyone! Welcome to the first blog post of our thrilling journey together. We are about to dive into the awesome world of technology, our brain’s magic, and where those two meet.</p><p>I’m a Software Engineer with a big love for Ruby on Rails and Python, but my real passion? That’s the incredible universe of artificial intelligence (AI) and deep learning, and the way it intersects with neuroscience to unlock, and maybe even upgrade, our brain’s fantastic powers.</p><p>My own adventure into these exciting areas started at Stanford University and IBM. There, I learned the ins and outs of Data Science and Machine Learning. That’s when I got my first taste of AI, neural networks, and how deep learning can shed new light on our understanding of the brain.</p><p>But, getting here wasn’t a cakewalk. Learning all this stuff was tough, especially because a lot of the resources online are jam-packed with fancy words and complex ideas. Sometimes, they didn’t even seem to connect with real-life problems. But, no pain, no gain, right? Every challenge was a stepping stone that brought me closer to finding what I love doing.</p><p>Now, I’m in this awesome place where I get to work on cool projects that blend AI, deep learning, and neuroscience in fresh and innovative ways. And guess what? I believe in sharing the knowledge that I’ve gained. That’s why I’m super excited to share all these learnings with you, through this blog.</p><p>If you’re into these fields but find the tech jargon a bit much, you’re in the right place. We’ll break down these big concepts into fun and easy bites and apply them to real-life situations.</p><p>So, what’s up next? In our first ‘official’ blog post (Episode 1), we’re going to look at a fun project: “AI as a Soil Whisperer”. We’ll see how we can use basic regression models to guess how well your home garden could do based on things like soil pH, sunlight, and humidity. Sounds fun, huh?</p><p>So, stay tuned! Let’s unravel the mysteries of AI, deep learning, and neuroscience together, one post at a time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b448255995" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>