<?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 Kalpesh Rajput on Medium]]></title>
        <description><![CDATA[Stories by Kalpesh Rajput on Medium]]></description>
        <link>https://medium.com/@kr342803?source=rss-af39b979694f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z6fbhfjPxLt-jO00VprBTQ.jpeg</url>
            <title>Stories by Kalpesh Rajput on Medium</title>
            <link>https://medium.com/@kr342803?source=rss-af39b979694f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:06:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kr342803/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[OpenClaw Is Mind-Blowing: Complete Local Setup Guide on Ubuntu (From Zero to Running AI Gateway)]]></title>
            <link>https://medium.com/@kr342803/openclaw-is-mind-blowing-complete-local-setup-guide-on-ubuntu-from-zero-to-running-ai-gateway-00ef81ae5da8?source=rss-af39b979694f------2</link>
            <guid isPermaLink="false">https://medium.com/p/00ef81ae5da8</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[aigents]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[openclaw]]></category>
            <dc:creator><![CDATA[Kalpesh Rajput]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 05:15:38 GMT</pubDate>
            <atom:updated>2026-03-05T05:15:38.611Z</atom:updated>
            <content:encoded><![CDATA[<p>AI agents are evolving quickly, but tools that make them <strong>practical for developers</strong> are still rare. Recently I came across <strong>OpenClaw</strong>, and honestly — it’s one of the most impressive AI infrastructure tools I’ve used.</p><p>OpenClaw acts like a <strong>central AI gateway</strong> that connects models, automation tools, chat channels, and agents into one programmable system. Instead of wiring multiple APIs and scripts manually, OpenClaw gives you a <strong>structured environment to run AI agents, connect channels, and manage workflows</strong>.</p><p>In this article, I’ll walk you through <strong>a complete setup from scratch</strong> so that by the end you will have <strong>OpenClaw running locally on Ubuntu with Docker</strong>.</p><p>No prior OpenClaw knowledge required.</p><h3>Why OpenClaw Is Interesting</h3><p>Before we jump into setup, here’s why OpenClaw stands out.</p><p>OpenClaw provides:</p><p>• AI agent orchestration<br>• A WebSocket gateway for agents<br>• Built-in chat interfaces<br>• Model routing and control<br>• Plugin system for integrations<br>• Automation workflows</p><p>Instead of building AI tools separately, OpenClaw acts as a <strong>control layer for your AI ecosystem</strong>.</p><p>Think of it like:</p><pre>Your AI Control Center</pre><h3>What We Will Build</h3><p>By the end of this guide you will have:</p><p>• OpenClaw running locally<br>• Dockerized environment<br>• Persistent configuration<br>• Gemini AI connected<br>• Control UI running in browser</p><p>Architecture:</p><pre>Host Machine (Ubuntu / WSL)<br>        │<br>        ▼<br>Docker Engine<br>        │<br>        ▼<br>OpenClaw Container<br>        │<br>        ▼<br>AI Model APIs (Gemini)<br>        │<br>        ▼<br>OpenClaw Control UI</pre><h3>Prerequisites</h3><p>Make sure you have the following installed.</p><h3>Ubuntu (or WSL Ubuntu)</h3><p>Any modern Ubuntu version works.</p><p>Example:</p><pre>Ubuntu 22.04+</pre><h3>Install Docker</h3><p>Update packages:</p><pre>sudo apt update</pre><p>Install Docker:</p><pre>sudo apt install docker.io docker-compose -y</pre><p>Start Docker service:</p><pre>sudo systemctl start docker<br>sudo systemctl enable docker</pre><p>Verify installation:</p><pre>docker --version<br>docker compose version</pre><h3>Step 1: Create Project Directory</h3><p>Create a working directory.</p><pre>mkdir ~/openclaw-docker<br>cd ~/openclaw-docker</pre><p>This will hold all configuration files.</p><h3>Step 2: Create Dockerfile</h3><p>Create the Dockerfile.</p><pre>nano Dockerfile</pre><p>Paste the following configuration.</p><pre>FROM node:22-slim</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br>    git \<br>    chromium \<br>    chromium-driver \<br>    ca-certificates \<br>    fonts-liberation \<br>    libatk-bridge2.0-0 \<br>    libgtk-3-0 \<br>    libnss3 \<br>    libxss1 \<br>    libasound2 \<br>    xdg-utils \<br>    --no-install-recommends \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre>WORKDIR /app</pre><pre>RUN npm install -g openclaw@2026.3.1</pre><pre>EXPOSE 18789</pre><pre>CMD [&quot;openclaw&quot;, &quot;gateway&quot;]</pre><h3>What This Dockerfile Does</h3><p>This configuration:</p><p>• Installs Node runtime<br>• Installs browser dependencies<br>• Installs OpenClaw CLI<br>• Starts OpenClaw gateway automatically</p><h3>Step 3: Create Docker Compose File</h3><p>Now create a compose file to manage the container.</p><pre>nano docker-compose.yml</pre><p>Paste this configuration.</p><pre>version: &quot;3.9&quot;</pre><pre>services:<br>  openclaw:<br>    build: .<br>    container_name: openclaw-container<br>    ports:<br>      - &quot;18789:18789&quot;<br>    volumes:<br>      - /home/YOUR_USERNAME/.openclaw:/root/.openclaw<br>    environment:<br>      - GOOGLE_API_KEY=YOUR_GEMINI_API_KEY<br>    restart: unless-stopped</pre><p>Replace:</p><pre>YOUR_USERNAME<br>YOUR_GEMINI_API_KEY</pre><h3>Step 4: Build Docker Image</h3><p>Build the container image.</p><pre>docker build --no-cache -t openclaw-docker .</pre><p>This step installs all dependencies and packages OpenClaw into the container.</p><h3>Step 5: Start OpenClaw</h3><p>Now start the system.</p><pre>docker compose up -d</pre><p>Verify container is running.</p><pre>docker ps</pre><p>You should see:</p><pre>openclaw-container   Up</pre><h3>Step 6: Open the OpenClaw Dashboard</h3><p>Open your browser and go to:</p><pre>http://localhost:18789</pre><p>You will see the <strong>OpenClaw Control UI</strong>.</p><h3>Step 7: Retrieve Authentication Token</h3><p>OpenClaw uses a secure gateway token.</p><p>Retrieve it with:</p><pre>openclaw config get gateway.auth.token</pre><p>Or check configuration file:</p><pre>cat ~/.openclaw/openclaw.json</pre><p>Locate:</p><pre>gateway.auth.token</pre><h3>Step 8: Login to the Dashboard</h3><p>Open the dashboard using your token.</p><pre>http://localhost:18789/?token=YOUR_TOKEN</pre><p>You are now authenticated.</p><h3>Step 9: Pair Your Device</h3><p>First browser access requires device approval.</p><p>List devices:</p><pre>openclaw devices list</pre><p>Approve device if needed:</p><pre>openclaw devices approve DEVICE_ID</pre><p>Refresh the browser.</p><h3>Step 10: Verify Gateway</h3><p>Check gateway status.</p><pre>openclaw health</pre><p>You should see the gateway running.</p><h3>Useful Docker Commands</h3><p>Stop the container:</p><pre>docker compose stop</pre><p>Stop and remove containers:</p><pre>docker compose down</pre><p>Restart service:</p><pre>docker compose up -d</pre><p>View logs:</p><pre>docker logs openclaw-container</pre><p>Enter container shell:</p><pre>docker exec -it openclaw-container sh</pre><h3>Where OpenClaw Stores Data</h3><p>OpenClaw stores its configuration in:</p><pre>~/.openclaw</pre><p>Inside the container this path becomes:</p><pre>/root/.openclaw</pre><p>Because we mounted a volume, your configuration <strong>persists even if the container restarts</strong>.</p><h3>What You Can Do Next</h3><p>Now that OpenClaw is running locally, you can explore:</p><p>• AI agent automation<br>• Chat channel integrations<br>• Plugins and skills<br>• Webhooks and workflows<br>• Multi-model routing</p><p>OpenClaw essentially becomes your <strong>personal AI operations platform</strong>.</p><h3>Final Thoughts</h3><p>OpenClaw is still evolving, but it’s already a powerful foundation for building <strong>AI automation systems, personal assistants, and intelligent workflows</strong>.</p><p>Running it inside Docker gives you:</p><p>• reproducibility<br>• isolation<br>• easy deployment<br>• scalable architecture</p><p>If you’re experimenting with <strong>AI agents or autonomous workflows</strong>, OpenClaw is definitely worth exploring.</p><p>If you found this guide helpful, feel free to share it with other developers exploring AI infrastructure.</p><p>Happy building 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00ef81ae5da8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ A Beginner’s Guide to Artificial Neural Networks (ANN) — Build One Step-by-Step in Python]]></title>
            <link>https://medium.com/@kr342803/a-beginners-guide-to-artificial-neural-networks-ann-build-one-step-by-step-in-python-e63371c9ef1d?source=rss-af39b979694f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e63371c9ef1d</guid>
            <dc:creator><![CDATA[Kalpesh Rajput]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 05:28:42 GMT</pubDate>
            <atom:updated>2025-10-21T05:28:42.537Z</atom:updated>
            <content:encoded><![CDATA[<h4>🧠 A Beginner’s Guide to Artificial Neural Networks (ANN) — Build One Step-by-Step in Python</h4><blockquote><em>“The best way to understand neural networks is to build one.”</em></blockquote><p>Artificial Neural Networks (ANNs) are the foundation of modern AI.<br> They power everything from self-driving cars to spam detection, yet their core concept is surprisingly simple.</p><p>In this guide, we’ll break down <strong>what an ANN is</strong>, explain <strong>each layer clearly</strong>, and finally <strong>build one from scratch using Python and TensorFlow</strong> — step by step.</p><h3>💡 What Is an Artificial Neural Network?</h3><p>An <strong>Artificial Neural Network (ANN)</strong> is a machine learning model inspired by how the human brain processes information.<br> It consists of interconnected “neurons” organized in layers — where each neuron learns patterns from data by adjusting <strong>weights</strong> and <strong>biases</strong>.</p><p><em>Image: A simple neural network with input, hidden, and output layers.</em></p><h3>🧩 The Three Main Layers of an ANN</h3><p>Let’s understand how each layer contributes to the learning process.</p><h3>🔹 1. Input Layer — Where Data Enters</h3><p>The <strong>input layer</strong> receives data and passes it forward.<br> Each neuron in this layer represents one <strong>feature</strong> in your dataset.</p><p>📘 Example:<br> If your dataset has two features — Age and Salary — the input layer will have <strong>2 neurons</strong>.</p><p>No actual “learning” happens here; this layer only forwards the data.</p><h3>🔹 2. Hidden Layers — Where Learning Happens</h3><p>Hidden layers are where the model <strong>learns complex patterns</strong>.<br> Each neuron performs a weighted sum of inputs and applies an <strong>activation function</strong> to introduce non-linearity.</p><p>Mathematically:<br> {Output} = f(w_1x_1 + w_2x_2 + b)<br> Where:</p><ul><li>(w) = weights</li><li>(x) = inputs</li><li>(b) = bias</li><li>(f) = activation function</li></ul><h4>⚙️ Common Activation Functions:</h4><p>Activation Range Best Used For <strong>ReLU</strong> (max(0, x)) 0 → ∞ Most common for hidden layers <strong>Sigmoid</strong> 0 → 1 Binary output probabilities <strong>Tanh</strong> -1 → 1 Data centered around zero</p><p>ReLU (Rectified Linear Unit) is the go-to choice for hidden layers in modern neural networks.</p><h3>🔹 3. Output Layer — Where Predictions Are Made</h3><p>The <strong>output layer</strong> produces the final result.<br> Its activation function depends on your problem type:</p><p>Problem Type Output Neurons Activation Function Binary Classification 1 sigmoid Multi-class Classification # of classes softmax Regression 1 linear</p><h3>🚀 Let’s Build an ANN in Python (Step-by-Step)</h3><p>Now, let’s create a simple neural network using <strong>TensorFlow Keras</strong>.<br> We’ll predict whether a customer will <strong>buy a product</strong> (1) or <strong>not</strong> (0) based on two inputs: Age and Salary.</p><h3>🧱 Step 1: Import Required Libraries</h3><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense</pre><h3>📊 Step 2: Create a Simple Dataset</h3><pre>data = {<br>    &#39;Age&#39;: [22, 25, 47, 52, 46, 56, 55, 60, 34, 40],<br>    &#39;Salary&#39;: [25000, 30000, 50000, 52000, 48000, 60000, 58000, 62000, 40000, 45000],<br>    &#39;Purchased&#39;: [0, 0, 1, 1, 1, 1, 1, 1, 0, 1]<br>}<br>df = pd.DataFrame(data)</pre><h3>✂️ Step 3: Split Features and Target</h3><pre>X = df[[&#39;Age&#39;, &#39;Salary&#39;]]<br>y = df[&#39;Purchased&#39;]</pre><h3>⚖️ Step 4: Train-Test Split and Feature Scaling</h3><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><pre>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)</pre><p>Scaling ensures all features are on the same scale — crucial for ANN performance.</p><h3>🧠 Step 5: Build the ANN Model</h3><pre>model = Sequential()</pre><pre># Input + Hidden layer<br>model.add(Dense(8, input_dim=2, activation=&#39;relu&#39;))</pre><pre># Second hidden layer<br>model.add(Dense(4, activation=&#39;relu&#39;))</pre><pre># Output layer<br>model.add(Dense(1, activation=&#39;sigmoid&#39;))</pre><h3>🤔 Why Did We Choose 8 Neurons?</h3><p>There’s no fixed rule — it’s a <strong>hyperparameter</strong>.<br> Think of neurons as “brain power” — more neurons mean more learning capacity, but also more risk of overfitting.</p><p>✅ A good rule of thumb:<br> [<br> \text{Hidden Neurons} \approx \frac{\text{Input Neurons} + \text{Output Neurons}}{2}<br> ]</p><p>Then adjust based on performance.</p><h3>⚙️ Step 6: Compile the Model</h3><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><ul><li><strong>Adam</strong> → adaptive optimizer (works well by default)</li><li><strong>Binary Crossentropy</strong> → best loss for binary classification</li><li><strong>Accuracy</strong> → metric to track during training</li></ul><h3>🏋️ Step 7: Train the Model</h3><pre>model.fit(X_train, y_train, epochs=50, batch_size=2, verbose=1)</pre><p>Each <strong>epoch</strong> means the model has seen all training samples once.<br> A <strong>batch size</strong> of 2 means it updates weights every 2 samples.</p><h3>🧪 Step 8: Evaluate the Model</h3><pre>loss, accuracy = model.evaluate(X_test, y_test)<br>print(f&quot;Test Accuracy: {accuracy:.2f}&quot;)</pre><h3>🔮 Step 9: Make Predictions</h3><pre>y_pred = (model.predict(X_test) &gt; 0.5).astype(&quot;int32&quot;)<br>print(&quot;Predictions:&quot;, y_pred.flatten())</pre><h3>🧾 Example Output</h3><pre>Epoch 50/50<br>4/4 [==============================] - 0s 2ms/step - loss: 0.32 - accuracy: 1.00<br>1/1 [==============================] - 0s 60ms/step - loss: 0.38 - accuracy: 0.50<br>Predictions: [1 1]</pre><h3>📈 Summary: What Each Layer Does</h3><p>Layer Activation Purpose Input — Accepts features Hidden 1 ReLU Learns initial patterns Hidden 2 ReLU Learns deeper features Output Sigmoid Predicts probability (0 or 1)</p><h3>🧩 Tuning Your ANN</h3><p>Once your base model works:</p><ul><li>Increase or decrease neurons in each layer</li><li>Add or remove hidden layers</li><li>Try different activation functions (relu, tanh, leaky_relu)</li><li>Use dropout to prevent overfitting</li></ul><p>Tuning is how you turn a simple network into a powerful model.</p><h3>🧠 Key Takeaways</h3><ul><li>ANNs are inspired by how the human brain processes information.</li><li>Each layer has a role — Input (receive data), Hidden (learn), Output (predict).</li><li>The number of neurons is <strong>not fixed</strong> — you tune it experimentally.</li><li>Normalizing data and choosing the right activation function are crucial for performance.</li></ul><h3>🏁 Final Words</h3><p>Building your first ANN might seem intimidating, but as you saw — it’s just a few lines of code once you understand the layers.</p><p>Start small. Play around. Observe how your network behaves.<br> The more you experiment, the better you’ll understand how machines learn.</p><h3>✨ Recommended Next Steps</h3><ul><li>Visualize training accuracy &amp; loss curves using Matplotlib.</li><li>Try multi-class classification using softmax.</li><li>Experiment with dropout layers to reduce overfitting.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e63371c9ef1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essentials of Hyperparameter Tuning for Regression Models]]></title>
            <link>https://medium.com/@kr342803/essentials-of-hyperparameter-tuning-for-regression-models-ab173a283cfe?source=rss-af39b979694f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab173a283cfe</guid>
            <dc:creator><![CDATA[Kalpesh Rajput]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 11:38:15 GMT</pubDate>
            <atom:updated>2025-03-07T11:38:15.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCq7jjrTnaXC11u0-X1w4w.jpeg" /></figure><h3>Optimize Your ML Model with GridSearchCV and RandomizedSearchCV or <strong>Fine-tuning advanced models</strong> like <strong>XGBoost</strong> and <strong>LightGBM</strong></h3><h3>Introduction</h3><p>In machine learning, hyperparameter tuning plays a crucial role in improving the performance of a model. Choosing the right hyperparameters can significantly enhance a model’s accuracy and efficiency. But how do we find the best parameters for a given model?</p><p>In this article, we will explore:<br> ✅ What hyperparameter tuning is and why it matters<br> ✅ The difference between <strong>GridSearchCV</strong> and <strong>RandomizedSearchCV</strong><br> ✅ Implementing <strong>hyperparameter tuning</strong> for a regression model using <strong>Decision Tree</strong> and <strong>Random Forest</strong><br> ✅ Evaluating the model and saving it for future use</p><p>By the end of this guide, you’ll be able to fine-tune any regression model using <strong>Scikit-learn</strong> and <strong>improve predictions effectively</strong>! 🚀</p><h3>1. Understanding Hyperparameter Tuning</h3><h3>What Are Hyperparameters?</h3><p>Hyperparameters are the <strong>configurations</strong> of a model that are <strong>not learned</strong> from the data. Instead, they are set <strong>before training</strong> to control the learning process.</p><p>Some common hyperparameters in regression models include:</p><ul><li>max_depth – Controls how deep the decision tree grows.</li><li>n_estimators – The number of trees in a Random Forest.</li><li>learning_rate – Controls the step size in boosting algorithms.</li></ul><h3>Why Tune Hyperparameters?</h3><p>Selecting the wrong hyperparameters can lead to <strong>underfitting</strong> (too simple) or <strong>overfitting</strong> (too complex). Hyperparameter tuning helps us find the best settings for a model to <strong>improve performance</strong> and <strong>reduce errors</strong>.</p><h3>2. Methods for Hyperparameter Tuning</h3><p>There are two popular approaches to hyperparameter tuning in Scikit-learn:</p><h3>🔹 GridSearchCV (Exhaustive Search)</h3><ul><li>Tries all possible combinations of hyperparameters.</li><li>Guarantees finding the best combination but is computationally expensive.</li></ul><h3>🔹 RandomizedSearchCV (Random Sampling)</h3><ul><li>Randomly selects hyperparameter combinations.</li><li>Faster than GridSearchCV but may not find the absolute best parameters.</li></ul><h3>3. Hyperparameter Tuning with GridSearchCV</h3><p>Let’s fine-tune a <strong>Decision Tree Regressor</strong> using GridSearchCV.</p><h3>📌 Step 1: Import Libraries &amp; Load Data</h3><pre>import numpy as np<br>import pandas as pd<br>import joblib<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error<br># Load dataset (Replace with your dataset)<br>df = pd.read_csv(&quot;your_dataset.csv&quot;)<br># Split features and target<br>X = df.drop(columns=[&quot;target&quot;])  # Replace &quot;target&quot; with your actual column name<br>y = df[&quot;target&quot;]<br># Train-test split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><h3>📌 Step 2: Define Hyperparameter Grid &amp; Apply GridSearchCV</h3><pre># Define model<br>dt_regressor = DecisionTreeRegressor(random_state=42)<br># Define hyperparameter grid<br>param_grid = {<br>    &#39;max_depth&#39;: [5, 10, 15, 20],<br>    &#39;min_samples_split&#39;: [2, 5, 10],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4]<br>}<br># Perform Grid Search<br>grid_search = GridSearchCV(dt_regressor, param_grid, cv=5, scoring=&#39;r2&#39;, n_jobs=-1)<br>grid_search.fit(X_train, y_train)<br># Get best model and parameters<br>best_model = grid_search.best_estimator_<br>best_params = grid_search.best_params_<br>print(&quot;Best Parameters:&quot;, best_params)</pre><h3>📌 Step 3: Evaluate the Tuned Model</h3><pre># Make predictions on test data<br>y_pred = best_model.predict(X_test)<br># Evaluate performance<br>r2 = r2_score(y_test, y_pred)<br>mae = mean_absolute_error(y_test, y_pred)<br>rmse = mean_squared_error(y_test, y_pred, squared=False)  # sqrt of MSE<br>print(f&quot;R² Score: {r2:.4f}&quot;)<br>print(f&quot;Mean Absolute Error: {mae:.4f}&quot;)<br>print(f&quot;Root Mean Squared Error: {rmse:.4f}&quot;)</pre><h3>4. Hyperparameter Tuning with RandomizedSearchCV</h3><p>Now, let’s tune a <strong>Random Forest Regressor</strong> using <strong>RandomizedSearchCV</strong> for faster tuning.</p><h3>📌 Step 1: Define Hyperparameter Grid &amp; Apply RandomizedSearchCV</h3><pre>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.model_selection import RandomizedSearchCV<br># Define model<br>rf_regressor = RandomForestRegressor(random_state=42)<br># Define hyperparameter grid<br>param_dist = {<br>    &#39;n_estimators&#39;: np.arange(50, 500, 50),<br>    &#39;max_depth&#39;: [None, 10, 20, 30, 40],<br>    &#39;min_samples_split&#39;: [2, 5, 10],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4],<br>    &#39;max_features&#39;: [&#39;auto&#39;, &#39;sqrt&#39;]<br>}<br># Perform Randomized Search<br>random_search = RandomizedSearchCV(rf_regressor, param_dist, n_iter=20, cv=5, scoring=&#39;r2&#39;, n_jobs=-1, random_state=42)<br>random_search.fit(X_train, y_train)<br># Get best model and parameters<br>best_rf_model = random_search.best_estimator_<br>best_rf_params = random_search.best_params_<br>print(&quot;Best Parameters:&quot;, best_rf_params)</pre><h3>📌 Step 2: Evaluate the Tuned Model</h3><pre># Make predictions<br>y_pred_rf = best_rf_model.predict(X_test)<br># Evaluate performance<br>r2_rf = r2_score(y_test, y_pred_rf)<br>mae_rf = mean_absolute_error(y_test, y_pred_rf)<br>rmse_rf = mean_squared_error(y_test, y_pred_rf, squared=False)<br>print(f&quot;R² Score: {r2_rf:.4f}&quot;)<br>print(f&quot;Mean Absolute Error: {mae_rf:.4f}&quot;)<br>print(f&quot;Root Mean Squared Error: {rmse_rf:.4f}&quot;)</pre><h3>5. Hyperparameter Tuning with XGBoost</h3><p><a href="https://xgboost.ai/">XGBoost</a> is an optimized gradient boosting library known for its high performance. Let’s fine-tune it using <strong>RandomizedSearchCV</strong>.</p><h3>📌 Step 1: Install and Import XGBoost</h3><pre>!pip install xgboost<br>import xgboost as xgb<br>from sklearn.model_selection import RandomizedSearchCV</pre><h3>📌 Step 2: Define Hyperparameter Grid &amp; Apply RandomizedSearchCV</h3><pre># Define model<br>xgb_regressor = xgb.XGBRegressor(objective=&quot;reg:squarederror&quot;, random_state=42)<br># Define hyperparameter grid<br>xgb_param_grid = {<br>    &#39;n_estimators&#39;: [100, 300, 500],<br>    &#39;learning_rate&#39;: [0.01, 0.05, 0.1],<br>    &#39;max_depth&#39;: [3, 5, 7, 10],<br>    &#39;subsample&#39;: [0.6, 0.8, 1.0],<br>    &#39;colsample_bytree&#39;: [0.6, 0.8, 1.0]<br>}<br># Perform Randomized Search<br>random_search_xgb = RandomizedSearchCV(xgb_regressor, xgb_param_grid, cv=5, scoring=&#39;r2&#39;, n_jobs=-1, random_state=42)<br>random_search_xgb.fit(X_train, y_train)<br># Get best model and parameters<br>best_xgb_model = random_search_xgb.best_estimator_<br>best_xgb_params = random_search_xgb.best_params_<br>print(&quot;Best XGBoost Parameters:&quot;, best_xgb_params)</pre><h3>6. Hyperparameter Tuning with LightGBM</h3><p><a href="https://lightgbm.readthedocs.io/en/latest/">LightGBM</a> is a gradient boosting framework designed for efficiency.</p><h3>📌 Step 1: Install and Import LightGBM</h3><pre>!pip install lightgbm<br>import lightgbm as lgb</pre><h3>📌 Step 2: Define Hyperparameter Grid &amp; Apply RandomizedSearchCV</h3><pre># Define model<br>lgb_regressor = lgb.LGBMRegressor(random_state=42)<br># Define hyperparameter grid<br>lgb_param_grid = {<br>    &#39;n_estimators&#39;: [100, 300, 500],<br>    &#39;learning_rate&#39;: [0.01, 0.05, 0.1],<br>    &#39;num_leaves&#39;: [20, 31, 40],<br>    &#39;max_depth&#39;: [-1, 10, 20],<br>    &#39;subsample&#39;: [0.6, 0.8, 1.0]<br>}<br># Perform Randomized Search<br>random_search_lgb = RandomizedSearchCV(lgb_regressor, lgb_param_grid, cv=5, scoring=&#39;r2&#39;, n_jobs=-1, random_state=42)<br>random_search_lgb.fit(X_train, y_train)<br># Get best model and parameters<br>best_lgb_model = random_search_lgb.best_estimator_<br>best_lgb_params = random_search_lgb.best_params_<br>print(&quot;Best LightGBM Parameters:&quot;, best_lgb_params)</pre><h3>7. Save and Load the Best Model</h3><p>Once you have the best model, save it for future use.</p><pre># Save model<br>joblib.dump(best_rf_model, &quot;best_rf_model.pkl&quot;)<br># Load model (when needed)<br>loaded_model = joblib.load(&quot;best_rf_model.pkl&quot;)<br># Make a sample prediction<br>sample_input = X_test.iloc[0].values.reshape(1, -1)  # Example single row<br>sample_prediction = loaded_model.predict(sample_input)<br>print(f&quot;Sample Prediction: {sample_prediction}&quot;)</pre><h3>Conclusion</h3><p>Hyperparameter tuning is essential to improve the performance of machine learning models. In this article, we:<br> ✅ Used <strong>GridSearchCV</strong> for exhaustive tuning of a <strong>Decision Tree Regressor</strong><br> ✅ Used <strong>RandomizedSearchCV</strong> for faster tuning of a <strong>Random Forest Regressor</strong><br> ✅ Evaluated models using <strong>R² Score, MAE, and RMSE</strong><br> ✅ Saved and loaded the best model for future use</p><p>Now, you can apply these techniques to any <strong>regression model</strong> and fine-tune it efficiently. 🎯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab173a283cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Coding in Machine Learning: A Best Practice Approach]]></title>
            <link>https://medium.com/@kr342803/modular-coding-in-machine-learning-a-best-practice-approach-558f84d471c7?source=rss-af39b979694f------2</link>
            <guid isPermaLink="false">https://medium.com/p/558f84d471c7</guid>
            <category><![CDATA[modular-programming]]></category>
            <dc:creator><![CDATA[Kalpesh Rajput]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 05:03:16 GMT</pubDate>
            <atom:updated>2025-02-15T05:03:16.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Gmq25Y_qJ7lCSe1O0vN1eQ.png" /></figure><h3>Introduction</h3><p>As machine learning (ML) projects grow in complexity, writing clean, maintainable, and reusable code becomes crucial. <strong>Modular coding</strong> is a programming paradigm that emphasizes breaking down a project into smaller, reusable components. It enhances <strong>readability, debugging, collaboration, and scalability</strong> of ML projects.</p><p>This blog will discuss the importance of modular coding, its key principles, and how to implement it effectively in machine learning projects.</p><h3>Why Modular Coding Matters in ML</h3><ol><li><strong>Code Reusability</strong>: Avoid duplication by reusing functions and classes across different projects.</li><li><strong>Maintainability</strong>: Changes and updates become easier with well-defined modules.</li><li><strong>Collaboration</strong>: Teams can work on independent modules without affecting the entire project.</li><li><strong>Scalability</strong>: Modular code helps scale ML pipelines by adding new features seamlessly.</li><li><strong>Debugging &amp; Testing</strong>: Isolated components make debugging and unit testing more efficient.</li></ol><h3>Key Principles of Modular Coding</h3><ol><li><strong>Separation of Concerns</strong> — Keep different aspects of the code (data handling, preprocessing, model training, etc.) in separate modules.</li><li><strong>Encapsulation</strong> — Hide implementation details and expose only necessary functionalities.</li><li><strong>Reusability</strong> — Create generalized functions that can be reused across different projects.</li><li><strong>Loose Coupling</strong> — Ensure minimal dependency between modules for flexibility.</li><li><strong>Clear Interface</strong> — Define input and output formats for each module.</li></ol><h3>Real-World Scenario: Predicting Customer Churn for an E-commerce Company</h3><h3>Problem Statement:</h3><p>An e-commerce company wants to predict customer churn to take proactive retention measures. The challenge is handling vast customer data efficiently and ensuring the ML pipeline remains scalable as the business grows</p><h3>Implementing Modular Coding in ML</h3><h3>1. Structuring the Project</h3><p>A modular ML project should follow a well-structured directory layout:</p><pre>project_name/<br>│── data_processing/<br>│   ├── load_data.py<br>│   ├── preprocess.py<br>│   ├── feature_engineering.py<br>│<br>│── model/<br>│   ├── train.py<br>│   ├── evaluate.py<br>│   ├── predict.py<br>│<br>│── pipeline/<br>│   ├── data_pipeline.py<br>│   ├── training_pipeline.py<br>│<br>│── components/<br>│   ├── data_ingestion.py<br>│   ├── model_builder.py<br>│   ├── evaluation.py<br>│<br>│── notebooks/<br>│   ├── exploratory_analysis.ipynb<br>│   ├── model_training.ipynb<br>│<br>│── utils/<br>│   ├── helper_functions.py<br>│   ├── config.py<br>│   ├── logging_setup.py<br>│   ├── exception_handling.py<br>│<br>│── app.py<br>│── requirements.txt<br>│── README.md</pre><p>Each module has a specific role, making the code easier to navigate and manage.</p><h3>2. Modularizing Data Processing</h3><pre># load_data.py<br>import pandas as pd<br><br>def load_data(file_path):<br>    &quot;&quot;&quot;Loads data from a CSV file.&quot;&quot;&quot;<br>    return pd.read_csv(file_path)<br><br># preprocess.py<br>def clean_data(df):<br>    &quot;&quot;&quot;Handles missing values and outliers.&quot;&quot;&quot;<br>    df = df.dropna()<br>    return df</pre><h3>3. Creating a Modular Model Training Pipeline</h3><pre># train.py<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br><br>def train_model(X, y):<br>    &quot;&quot;&quot;Trains a RandomForest model.&quot;&quot;&quot;<br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>    model = RandomForestClassifier()<br>    model.fit(X_train, y_train)<br>    return model, X_test, y_test</pre><h3>4. Modular Evaluation and Prediction</h3><pre># evaluate.py<br>from sklearn.metrics import accuracy_score<br><br>def evaluate_model(model, X_test, y_test):<br>    &quot;&quot;&quot;Evaluates the model and returns accuracy.&quot;&quot;&quot;<br>    y_pred = model.predict(X_test)<br>    return accuracy_score(y_test, y_pred)<br><br># predict.py<br>def make_prediction(model, new_data):<br>    &quot;&quot;&quot;Makes predictions on new data.&quot;&quot;&quot;<br>    return model.predict(new_data)</pre><h3>5. Logging and Exception Handling</h3><p>Implementing logging and exception handling helps track errors and debugging information effectively.</p><pre># logging_setup.py<br>import logging<br><br>def setup_logger():<br>    logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>    return logging.getLogger(__name__)<br><br># exception_handling.py<br>class CustomException(Exception):<br>    def __init__(self, message):<br>        super().__init__(message)<br><br># Example usage in a module<br>def divide(a, b):<br>    try:<br>        return a / b<br>    except ZeroDivisionError:<br>        raise CustomException(&quot;Division by zero is not allowed.&quot;)</pre><h3>6. Implementing an ML Pipeline</h3><p>Pipelines automate the entire ML workflow by chaining different components together.</p><pre># training_pipeline.py<br>from data_processing.load_data import load_data<br>from model.train import train_model<br>from model.evaluate import evaluate_model<br><br>if __name__ == &quot;__main__&quot;:<br>    df = load_data(&quot;data.csv&quot;)<br>    X, y = df.drop(&quot;target&quot;, axis=1), df[&quot;target&quot;]<br>    model, X_test, y_test = train_model(X, y)<br>    accuracy = evaluate_model(model, X_test, y_test)<br>    print(f&quot;Model Accuracy: {accuracy}&quot;)</pre><h3>Best Practices for Modular ML Code</h3><ol><li><strong>Use Configuration Files</strong> — Store hyperparameters and file paths in a separate config.py file.</li><li><strong>Version Control</strong> — Maintain proper versioning using Git for tracking changes.</li><li><strong>Unit Testing</strong> — Write unit tests for each module using pytest.</li><li><strong>Documentation</strong> — Add docstrings and comments for better readability.</li><li><strong>Logging</strong> — Implement logging to track errors and debugging information.</li><li><strong>Pipeline Implementation</strong> — Automate workflow using well-structured pipelines.</li><li><strong>Notebook Management</strong> — Use Jupyter notebooks for exploration while keeping production code modular.</li></ol><h3>Conclusion</h3><p>Modular coding in machine learning <strong>improves efficiency, readability, and maintainability</strong>. By following a structured approach, breaking down complex tasks into independent modules, and adhering to best practices, ML engineers can build <strong>scalable and robust</strong> machine learning systems.</p><p>Start modularizing your next ML project and experience the benefits firsthand!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=558f84d471c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>