<?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 Tarini Mohapatra on Medium]]></title>
        <description><![CDATA[Stories by Tarini Mohapatra on Medium]]></description>
        <link>https://medium.com/@tarinitm?source=rss-cacb37e0717f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5Grv2kG8ey3aOfbZ96TqAQ.jpeg</url>
            <title>Stories by Tarini Mohapatra on Medium</title>
            <link>https://medium.com/@tarinitm?source=rss-cacb37e0717f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:41:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tarinitm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Run Claude Code CLI with OpenRouter and DeepSeek for Low-Cost AI Engineering]]></title>
            <link>https://medium.com/@tarinitm/how-to-run-claude-code-cli-with-openrouter-and-deepseek-for-low-cost-ai-engineering-ab0e87f9d285?source=rss-cacb37e0717f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab0e87f9d285</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Tarini Mohapatra]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 16:28:06 GMT</pubDate>
            <atom:updated>2026-08-08T16:28:06.236Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to routing Anthropic’s powerful terminal agent through OpenRouter, bypassing subscription locks, and setting up an optimized AI Systems environment.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB2CHEL4ZaTd6Fd5r-Fxcg.png" /><figcaption><em>Terminal Code Environment</em></figcaption></figure><p>Anthropic’s<strong> Claude Code</strong> is one of the most powerful CLI coding agents available. It operates directly inside your terminal, reads multi-file repositories, runs shell commands (kubectl, docker, git), and automatically fixes code based on runtime logs.</p><p>However, out of the box, Claude Code defaults to Anthropic’s $20–$100–$200/month<br>subscription or direct Anthropic Console API billing.</p><p>If you are an AI Systems Engineer, you often want:</p><p>1. Pay-as-you-go flexibility without locked monthly subscriptions.<br>2. Access to high-performance open-weights models like DeepSeek-V4-Flash, DeepSeek-R1, or NVIDIA Nemotron.<br>3. Zero Data Retention (ZDR) options and prompt caching discounts.</p><p>In this guide, we will walk through how to configure Claude Code CLI to route through OpenRouter, bypass the interactive browser login screen, and set up a custom workspace optimized for AI Engineering.</p><h3>The Architecture: How It Works</h3><p>OpenRouter provides an Anthropic-compatible API gateway. By pointing Claude Code’s environment variables to OpenRouter’s base URL and supplying an OpenRouter Bearer token, Claude Code communicates with OpenRouter seamlessly without realizing it isn’t talking directly to Anthropic’s servers.</p><pre>+-------------------+       +-----------------------+       +------------------------+<br>|  Claude Code CLI  | ----&gt; |   OpenRouter Gateway  | ----&gt; | DeepSeek / Nemotron /  |<br>|   (Your Terminal) |       | (openrouter.ai/api)   |       |   Claude Sonnet    |<br>+-------------------+       +-----------------------+       +------------------------+</pre><h3>Step 1: Install Claude Code CLI</h3><p>First, ensure you have Node.js (v18+) installed. Then install Claude Code<br>globally via npm:</p><pre>npm install -g @anthropic-ai/claude-code</pre><p>Clear any previous Anthropic authentication sessions:</p><pre>claude /logout</pre><h3>Step 2: Get Your OpenRouter API Key</h3><p>1. Head over to openrouter.ai and sign up with your GitHub or Google account. There will be a setup wizard, figure that out, its straight forward. <br>2. Navigate to openrouter.ai/keys. <br>3. Click <strong>Create Key</strong>, name it code-monkey/claude-code-key (Anything you feel like), and copy the key (it starts with<br> sk-or-v1-…).</p><h3>Step 3: Configure Environment Variables</h3><blockquote>This is the most critical step. Claude Code normally launches a browser popup asking for OAuth login unless you explicitly set ANTHROPIC_API_KEY= “” (an empty<br>string) and pass your key via ANTHROPIC_AUTH_TOKEN.</blockquote><p>Add the following configuration to your ~/.zshrc or ~/.bashrc file:</p><pre># 1. Point to OpenRouter&#39;s API Gateway<br>export ANTHROPIC_BASE_URL=&quot;https://openrouter.ai/api&quot;<br># 2. Supply your OpenRouter API key as the Auth Token<br>export ANTHROPIC_AUTH_TOKEN=&quot;sk-or-v1-YOUR_OPENROUTER_KEY_HERE&quot;<br># 3. Explicitly empty ANTHROPIC_API_KEY to bypass browser OAuth login<br>export ANTHROPIC_API_KEY=&quot;&quot;<br># 4. Set your default model (e.g., DeepSeek V4 Flash)<br>export ANTHROPIC_MODEL=&quot;deepseek/deepseek-v4-flash&quot;<br>export ANTHROPIC_DEFAULT_SONNET_MODEL=&quot;deepseek/deepseek-v4-flash&quot;<br># 5. Enable Gateway Model Discovery &amp; disable unknown model window warnings<br>export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=&quot;1&quot;<br>export CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=&quot;1&quot;<br>After pasting this, reload your shell configuration:<br>source ~/.zshrc # Or source ~/.bashrc</pre><h3>Step 4: Create a CLAUDE.md File for AI Systems Context</h3><p>Claude Code automatically reads a file named CLAUDE.md located in the root of your project repository. You can use this file to give the CLI agent full context about your hardware limits, CUDA versions, and deployment targets.</p><p>Create a <strong>CLAUDE.md</strong> in your project root:</p><pre># AI Systems Project Context<br>## Tech Stack<br>- **Frameworks:** Python 3.10+, PyTorch 2.x, vLLM, Hugging Face Transformers, PEFT/LoRA<br>- **Infra &amp; Orchestration:** Docker, Kubernetes (EKS/GKE), Helm, NVIDIA GPU Operator<br>- **CI/CD &amp; MLOps:** GitHub Actions, MLflow<br>## Hardware Constraints<br>- **Default GPU Target:** NVIDIA A10G / L4 (24GB VRAM)<br>- **CUDA Version:** 12.1<br>## Conventions<br>- Always include GPU resource requests (`nvidia.com/gpu: 1`) and readiness probes in Kubernetes deployment manifests.<br>- Prefer `vLLM` or `Triton Inference Server` for high-performance LLM serving.<br></pre><h3>Step 5: Launch and verify</h3><p>Run <strong>claude</strong> in your terminal:</p><pre>claude</pre><p>Because <strong>ANTHROPIC_API_KEY=”” </strong>and <strong>ANTHROPIC_AUTH_TOKEN</strong> are set, <strong>Claude Code will skip</strong> the browser login prompt and take you straight into the interactive terminal prompt.</p><h4>Testing Prompt:</h4><p>Try requesting a Kubernetes GPU manifest inside the <strong>claude</strong> prompt:</p><pre>&quot;Generate a Kubernetes Deployment YAML for serving a fine-tuned Llama-3–8B model using vLLM on a single NVIDIA GPU.&quot;</pre><p>Claude Code will parse your CLAUDE.md context, connect to DeepSeek-V4-Flash via OpenRouter, and output a valid K8s deployment spec right in your terminal.</p><h3>Bonus: Privacy &amp; Cost Optimization</h3><p>1. Zero Data Retention (ZDR): You can toggle on “Require Zero Data Retention”in your OpenRouter account privacy settings. OpenRouter will automatically filter routes to ensure your code is only sent to endpoints that do not retain or train on your inputs. <strong>Please study more about this cause there are some models where ZDR isnt available and you need to take a call what to do. </strong><br>2. Prompt Caching Savings: Models like DeepSeek on OpenRouter support prompt caching. When running long CLI sessions where repository context is re-sent, prompt caching can reduce input token costs by up to 90%.</p><h3>Conclusion</h3><p>By bridging <strong>Claude Code CLI </strong>with <strong>OpenRouter</strong>, you get the best of both worlds:</p><ul><li>The powerful multi-file and terminal execution abilities of Claude Code.</li><li>The flexibility, low cost, and open-weights selection of OpenRouter’s model marketplace.</li></ul><p>Whether you are building LLM fine-tuning pipelines, deploying GPU Kubernetes clusters, or writing MLOps CI/CD workflows, this setup offers an incredibly fast and cost-effective AI development environment.</p><p>Have you tried running terminal AI agents with open-weights models? Let me know your setup in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab0e87f9d285" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression — The Fundamentals Revision]]></title>
            <link>https://medium.com/@tarinitm/logistic-regression-the-fundamentals-revision-1e5a0d1cde3c?source=rss-cacb37e0717f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5a0d1cde3c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Tarini Mohapatra]]></dc:creator>
            <pubDate>Sun, 28 May 2023 10:13:56 GMT</pubDate>
            <atom:updated>2023-05-28T15:09:08.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logistic Regression — The Fundamentals Revision</h3><p>Logistic Regression for a revision point of view or you can also read this article before studying logistic regression cause that would really help you in the understanding of the topic.</p><ol><li><strong>Binary Classification:</strong> Logistic regression is specifically designed for binary classification tasks, where the dependent variable has two classes (e.g., 0 and 1). The predicted probability is compared to a threshold value to assign instances to one of the classes.</li><li><strong>Objective:</strong> Logistic regression is a <strong>binary classification</strong> algorithm used to model the relationship between independent variables and the probability of belonging to a certain class.</li><li><strong>Logistic Function:</strong> Logistic regression uses the logistic function (also known as the sigmoid function) to <strong>transform </strong>the linear combination of inputs into a <strong>probability </strong>value between 0 and 1.</li><li><strong>It’s a classification algorithm but still called regression</strong>, why? — Cause it’s a regression algorithm, it still predicts the probability of success but we use thresholds for binary classification.</li><li><strong>Maximum Likelihood Estimation:</strong> Logistic regression estimates the parameters (weights) by maximizing the likelihood of the observed data under the logistic regression model. This involves finding the set of weights that maximizes the probability of observing the given data.</li><li><strong>Log Odds and Odds Ratio</strong>: Logistic regression models the log-odds (logarithm of the odds) of the dependent variable. The odds ratio represents the change in odds for a one-unit change in an independent variable.</li><li><strong>Decision Boundary:</strong> Logistic regression uses a decision boundary to separate instances into different classes. The decision boundary is typically set at a probability threshold (e.g., 0.5), where probabilities above the threshold are classified as one class, and below as the other class.</li><li><strong>Evaluation Metrics:</strong> Various evaluation metrics can be used to assess the performance of logistic regression, including accuracy, precision, recall, F1 score, and area under the ROC curve (AUC-ROC).</li><li><strong>Assumptions:</strong> Logistic regression assumes that the relationship between the independent variables and the log-odds is linear, the observations are independent, there is no multicollinearity among the independent variables, and the absence of influential outliers.</li><li><strong>Feature Engineering:</strong> Proper feature engineering plays a crucial role in logistic regression. Selecting relevant features and transforming them appropriately can improve the performance of the model.</li><li><strong>Interpretability:</strong> Logistic regression provides interpretable results as it estimates the impact of each independent variable on the outcome in terms of odds ratios or probability changes.</li><li><strong>Handling Imbalanced Data:</strong> Logistic regression can be sensitive to imbalanced class distributions. Techniques like class weighting, oversampling, or undersampling can be used to handle imbalanced data.</li><li><strong>Regularization:</strong> Regularization techniques like L1 and L2 regularization can be applied in logistic regression to prevent overfitting and improve generalization.</li><li><strong>Handling Missing Values: </strong>Logistic regression requires complete data without missing values. Missing values must be imputed or dealt with using appropriate techniques before fitting the model.</li></ol><p>Logistic regression is applicable to a wide range of binary classification problems, where the goal is to predict a binary outcome or assign instances to one of two classes. It is particularly suitable when the dependent variable is categorical and the relationship between the independent variables and the log-odds of the dependent variable is assumed to be linear.</p><p>Here are some examples of problems where logistic regression can be applied effectively:</p><ol><li>Medical Diagnosis: Logistic regression can be used to predict the presence or absence of a particular disease based on patient characteristics, such as symptoms, medical history, and test results.</li><li>Credit Risk Assessment: Logistic regression can help in assessing the creditworthiness of individuals or companies, predicting the likelihood of default based on factors like income, credit history, and loan amount.</li><li>Customer Churn Prediction: Logistic regression can be used to identify customers who are likely to churn or discontinue using a service, based on their behavior, demographics, or usage patterns.</li><li>Fraud Detection: Logistic regression can help detect fraudulent activities, such as credit card fraud or insurance fraud, by analyzing various features and patterns associated with fraudulent transactions.</li><li>Spam Email Classification: Logistic regression can be used to classify emails as either spam or non-spam based on features like email content, sender information, and email header analysis.</li><li>Employee Attrition Prediction: Logistic regression can assist in predicting employee attrition or turnover based on factors like job satisfaction, salary, years of experience, and performance metrics.</li><li>Market Segmentation: Logistic regression can be applied to segment customers into different categories or target markets based on their characteristics, preferences, or purchasing behavior.</li></ol><p>It’s important to note that logistic regression assumes that the relationship between the independent variables and the log-odds is linear. If the relationship is more complex, or if there are interactions between variables, other machine learning algorithms such as decision trees, random forests, or neural networks may be more appropriate.</p><p>When comparing logistic regression to other popular machine learning algorithms, several trade-offs can be considered. Here are some key trade-offs of logistic regression compared to other comparable algorithms:</p><ol><li>Linearity Assumption: Logistic regression assumes a linear relationship between the independent variables and the log-odds of the dependent variable. If the relationship is non-linear, logistic regression may not perform well. In contrast, algorithms like decision trees, random forests, or neural networks can capture non-linear relationships more effectively.</li><li>Model Complexity: Logistic regression is a relatively simple model with fewer parameters compared to more complex algorithms. While simplicity can be an advantage in terms of interpretability and computational efficiency, it may limit the model’s ability to capture intricate patterns in the data. More complex algorithms like ensemble methods (e.g., gradient boosting) or deep learning models can potentially achieve higher predictive performance but might be more computationally expensive and harder to interpret.</li><li>Handling of Missing Values and Outliers: Logistic regression requires complete and clean data without missing values or outliers. Missing values must be imputed or dealt with in some way before applying logistic regression. Other algorithms, such as decision trees or random forests, can handle missing values and outliers more gracefully due to their non-parametric nature.</li><li>Feature Engineering: Logistic regression relies heavily on proper feature engineering to extract meaningful and informative features. Selecting or creating appropriate features is crucial for logistic regression to perform well. In contrast, algorithms like random forests or deep learning models can handle raw or high-dimensional data more effectively, often requiring less feature engineering.</li><li>Class Imbalance: Logistic regression can be sensitive to imbalanced class distributions, where one class has significantly fewer instances than the other. If the data is imbalanced, logistic regression may struggle to capture the minority class well. In such cases, algorithms like support vector machines (SVM) or ensemble methods with class-weighted approaches might be more suitable.</li><li>Interpretability: Logistic regression provides interpretable results by estimating the impact of each independent variable on the outcome. The coefficients can be easily interpreted in terms of odds ratios or probability changes. In contrast, some complex models like neural networks or black-box models may offer higher predictive performance but lack interpretability.</li></ol><p>Ultimately, the choice of algorithm depends on the specific characteristics of the dataset, the goals of the project, and the trade-offs that are most important for the particular use case. It is often beneficial to explore and compare different algorithms to determine the best approach for a given problem.</p><p>The phrase “linear relationship between the independent variables and the log-odds of the dependent variable” means that logistic regression assumes a linear association between the independent variables (also known as predictor variables or features) and the logarithm of the odds of the dependent variable (the variable being predicted or classified).</p><p>In logistic regression, the log-odds (also referred to as the logit) of the probability of the dependent variable belonging to a certain class is modeled as a linear combination of the independent variables. This linear relationship is represented by the equation:</p><p>logit(p) = β0 + β1 * x1 + β2 * x2 + … + βn * xn</p><p>Where:</p><ul><li>logit(p) represents the logarithm of the odds (log-odds) of the probability p.</li><li>β0, β1, β2, …, βn are the regression coefficients (weights) associated with the independent variables x1, x2, …, xn, respectively.</li></ul><p>The linear relationship assumes that a unit change in an independent variable results in a proportional change in the log-odds of the dependent variable. However, it’s important to note that while the relationship is linear in terms of the weights, the relationship between the independent variables and the predicted probabilities is not necessarily linear due to the application of the logistic (sigmoid) function.</p><p>The logistic function applied to the linear combination of the independent variables allows the model to estimate probabilities between 0 and 1, converting the linear relationship into a non-linear relationship when mapping the probabilities to the observed classes.</p><p>Overall, the assumption of a linear relationship between the independent variables and the log-odds of the dependent variable is a fundamental assumption in logistic regression, allowing the model to capture the association between the features and the probability of belonging to a particular class.</p><p>Let&#39;s derive logistic regression.</p><p>To derive logistic regression, let’s start with the formulation of linear regression and then introduce the logistic function to transform it into a form suitable for binary classification.</p><p>In linear regression, we have a set of independent variables (features) denoted as x1, x2, …, xn, and we want to predict a continuous dependent variable y. The relationship between the features and the predicted variable is modeled as:</p><p>y = β0 + β1 * x1 + β2 * x2 + … + βn * xn + ε</p><p>where β0, β1, β2, …, βn are the regression coefficients (weights), and ε represents the error term.</p><p>Now, to transform this linear regression model into a binary classification algorithm using logistic regression, we introduce the logistic function (also known as the sigmoid function). The logistic function is defined as:</p><p>σ(z) = 1 / (1 + e^(-z))</p><p>where z is the linear combination of the features and their corresponding weights:</p><p>z = β0 + β1 * x1 + β2 * x2 + … + βn * xn</p><p>We interpret the output of the logistic function σ(z) as the probability that the dependent variable belongs to the positive class.</p><p>To convert the linear regression equation into the logistic regression form, we replace the predicted variable y with the log-odds (also known as logits) of the probability:</p><p>logit(p) = ln(p / (1 — p))</p><p>where p represents the probability of belonging to the positive class. By substituting p with σ(z), we have:</p><p>logit(p) = ln(σ(z) / (1 — σ(z)))</p><p>Simplifying this equation further, we can express the log-odds as a linear combination of the features:</p><p>logit(p) = β0 + β1 * x1 + β2 * x2 + … + βn * xn</p><p>Finally, to obtain the predicted probability p, we apply the inverse of the logistic function to the log-odds:</p><p>p = σ(logit(p))</p><p>In practice, logistic regression estimates the regression coefficients β0, β1, β2, …, βn by maximizing the likelihood of the observed data under the logistic regression model. This optimization process is typically performed using techniques such as maximum likelihood estimation or gradient descent.</p><p>The derived logistic regression model allows us to predict the probability of an instance belonging to the positive class based on the values of the independent variables. A decision boundary can then be defined to classify instances as positive or negative based on a chosen threshold probability (commonly 0.5).</p><p>Here’s a step-by-step explanation of how logistic regression works:</p><ol><li>Data Representation: Logistic regression requires labeled training data, where each data point has a set of independent variables (features) and a corresponding binary outcome or label (0 or 1).</li><li>Hypothesis Representation: The logistic regression model assumes a linear relationship between the independent variables and the log-odds (also known as logits) of the dependent variable. It uses a logistic function, also called the sigmoid function, to map the linear combination of inputs to a probability value between 0 and 1. Where “z” represents the linear combination of the input features and model parameters (weights), and “σ(z)” represents the predicted probability.</li><li>Training: The goal of logistic regression is to find the optimal set of weights that minimizes the error between the predicted probabilities and the true labels in the training data. This is typically done by maximizing the likelihood of the observed data under the model. The optimization process can be achieved using various algorithms such as gradient descent or Newton’s method.</li><li>Decision Boundary: Once the logistic regression model is trained, it can be used to make predictions on new, unseen data. A decision boundary is established based on the estimated parameters. The decision boundary is a threshold value (often 0.5) that separates the two classes. If the predicted probability is above the threshold, the data point is classified as the positive class; otherwise, it is classified as the negative class.</li><li>Evaluation: To assess the performance of the logistic regression model, various evaluation metrics can be used, such as accuracy, precision, recall, and F1 score. Additionally, techniques like cross-validation and ROC curves can provide further insights into the model’s performance and generalization ability.</li></ol><p>Some questions for the readers.</p><ol><li>What is logistic regression? This question tests your understanding of the basic concept and definition of logistic regression as a binary classification algorithm that models the relationship between independent variables and the log-odds of the dependent variable.</li><li>What is the difference between linear regression and logistic regression? This question assesses your ability to differentiate between linear regression (used for regression tasks) and logistic regression (used for classification tasks), highlighting the key distinctions in terms of the nature of the dependent variable and the type of relationship modeled.</li><li>What is the logistic function (or sigmoid function)? This question examines your familiarity with the logistic function, which maps the linear combination of inputs to a probability value between 0 and 1, enabling logistic regression to estimate probabilities for classification.</li><li>How is logistic regression trained? This question evaluates your understanding of the training process of logistic regression, including the estimation of model parameters (weights) that minimize the error between predicted probabilities and true labels, typically through maximum likelihood estimation or optimization algorithms like gradient descent.</li><li>What evaluation metrics can be used for logistic regression? This question tests your knowledge of evaluation metrics suitable for logistic regression, such as accuracy, precision, recall, F1 score, or area under the ROC curve (AUC-ROC), and your ability to interpret and apply these metrics.</li><li>What is the purpose of the decision boundary in logistic regression? This question assesses your comprehension of how logistic regression uses a decision boundary to classify instances based on the predicted probabilities, with a threshold typically set at 0.5.</li><li>What are some assumptions of logistic regression? This question explores your familiarity with the assumptions made by logistic regression, such as linearity between the independent variables and the log-odds, absence of multicollinearity, independence of observations, and absence of influential outliers.</li><li>How can you handle overfitting in logistic regression?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5a0d1cde3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The basics of Linear Regression]]></title>
            <link>https://medium.com/@tarinitm/the-basics-of-linear-regression-cbfff0264b18?source=rss-cacb37e0717f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbfff0264b18</guid>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[basics]]></category>
            <dc:creator><![CDATA[Tarini Mohapatra]]></dc:creator>
            <pubDate>Sat, 27 May 2023 11:25:15 GMT</pubDate>
            <atom:updated>2023-05-27T11:25:15.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*iiX70ITAHiibRkEvAqsKJg.png" /><figcaption>Credit goes to my bad handwriting 🤣</figcaption></figure><p>This article is regarding linear regression in a nutshell. Please note that this article does not go in-depth regarding the mathematics involved in it. This is indeed helpful to revise Linear Regression.</p><p>Well, you can also frame these points as questions and study the topic more effectively.</p><p>Points to summarize/revise it:-</p><ol><li><strong>Linear relationship:</strong> Linear regression assumes a linear relationship between the independent variables and the dependent variable. This means that the change in the dependent variable is directly proportional to the change in the independent variables.</li><li>It <strong>assumes a linear relationship</strong> between the independent variables and the dependent variable, meaning that the change in the dependent variable is directly proportional to the change in the independent variables.</li><li>The goal of linear regression is to <strong>find the best-fitting line</strong> that <strong>represents the relationship</strong> between the variables. This line is called the regression line or the best-fit line.</li><li><strong>Y = b0 + b1<em>X1 + b2</em>X2 + … + bn*Xn. </strong>Where Y is the dependent variable or the variable being predicted. X1, X2, …, Xn are the independent variables or the predictors. b0, b1, b2, …, bn are the coefficients or the slopes of the regression line.</li><li><strong>The coefficients</strong> determine the <strong>impact</strong> of each independent variable on the dependent variable. The coefficient b0 represents the y-intercept, the point where the regression line crosses the y-axis.</li><li><strong>Intercept</strong>: The coefficient b0 represents the y-intercept, which is the value of the dependent variable when all the independent variables are zero. It indicates the starting point of the regression line on the y-axis.</li><li><strong>Objective function</strong>: Linear regression aims to minimize an objective function called the “mean squared error” (MSE) or “sum of squared errors” (SSE). It measures the average squared difference between the predicted values and the actual values of the target variable.</li><li><strong>Assumptions</strong>: Linear regression has several assumptions, including linearity, independence of errors, constant variance (homoscedasticity), and normality of residuals. Violations of these assumptions can affect the validity of the model.</li><li><strong>R-squared</strong>: R-squared is a measure of the proportion of variance in the dependent variable that can be explained by the independent variables. It ranges from 0 to 1, where a higher value indicates a better fit of the model to the data.</li><li><strong>Significance of coefficients</strong>: It is important to assess the statistical significance of the coefficients to determine if there is a significant relationship between the independent and dependent variables. Statistical tests, such as t-tests, p-values, and confidence intervals, can be used for this purpose.</li><li><strong>Multicollinearity</strong>: Multicollinearity occurs when there is a high correlation between independent variables. It can cause instability in the coefficients and make it difficult to interpret the individual effects of the variables. It is important to check for multicollinearity and consider techniques like variable selection or dimensionality reduction if it is present.</li><li><strong>Categorical variables</strong>: Linear regression can handle categorical variables by converting them into numerical representations using techniques like one-hot encoding or dummy variables. This allows the incorporation of categorical information into the regression model.</li><li><strong>Goodness of fit</strong>: Various measures can be used to assess the goodness of fit of a linear regression model, such as R-squared, and adjusted R-squared. These measures help evaluate how well the model fits the data.</li><li><strong>Residual analysis</strong>: Residuals are the differences between the actual values and the predicted values of the dependent variable. Residual analysis helps check the assumptions of linear regression, including the normality of residuals, homoscedasticity, and the absence of patterns or trends in the residuals.</li><li><strong>Overfitting</strong>: Overfitting occurs when a model performs well on the training data but poorly on new, unseen data. It happens when the model captures noise or random fluctuations instead of the underlying true relationship. Techniques like regularization or cross-validation can help address overfitting. Bias-Variance Trade-off.</li><li><strong>Outliers</strong>: Outliers are extreme observations that can have a disproportionate influence on the regression line. It is important to identify and handle outliers appropriately, as they can distort the results</li><li><strong>Gradient descent</strong>: Gradient descent is an optimization algorithm commonly used to find the optimal coefficients (weights) in linear regression. It iteratively updates the coefficients in the direction of the steepest descent of the objective function, gradually minimizing the error.</li><li><strong>Feature scaling</strong>: It is important to scale or normalize the input features in linear regression to ensure that they are on a similar scale. Common techniques include standardization (mean = 0, standard deviation = 1) or normalization (scaling to a specific range).</li><li><strong>Bias term</strong>: In machine learning, linear regression often includes a bias term or intercept (b0) in addition to the coefficients for the independent variables. The bias term allows the regression line to have an offset from the origin.</li><li><strong>Model evaluation</strong>: To assess the performance of a linear regression model, various evaluation metrics are used, such as mean squared error (MSE), root mean squared error (RMSE), mean absolute error (MAE), or R-squared. These metrics help quantify the accuracy and goodness of fit of the model.</li><li><strong>Training and testing</strong>: It is important to split the available data into training and testing sets. The training set is used to train the linear regression model, while the testing set is used to evaluate its performance on unseen data. This helps estimate how well the model generalizes to new instances. We can also use train, validation, and test set.</li><li><strong>Regularization</strong>: Regularization techniques, such as Ridge regression and Lasso regression, can be applied to linear regression to prevent overfitting. Regularization adds a penalty term to the objective function, encouraging simpler and more generalizable models.</li><li><strong>Limitations</strong>: While linear regression is a powerful and widely used algorithm, it has limitations. It assumes a linear relationship between variables, which may not always hold. Nonlinear relationships may require other regression techniques. Additionally, linear regression is sensitive to outliers and may not handle complex data patterns well.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbfff0264b18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers in NLP]]></title>
            <link>https://medium.com/@tarinitm/transformers-in-nlp-18df5347b7ca?source=rss-cacb37e0717f------2</link>
            <guid isPermaLink="false">https://medium.com/p/18df5347b7ca</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[explained-in-simple-terms]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Tarini Mohapatra]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 04:22:13 GMT</pubDate>
            <atom:updated>2023-03-05T04:22:13.186Z</atom:updated>
            <content:encoded><![CDATA[<h4>Trying to understand Transformers in simple terms</h4><p>This article assumes that you have a basic understanding of</p><ol><li>Feed Forward Networks</li><li>Backpropagation</li><li>Deep learning algorithms like ANN, LSTM, GRU, and CNN.</li></ol><h3>Introduction</h3><p><strong>Transformers</strong> are just another type of neural network which only uses feedforward layers and attention layers so the name of the seminal paper “Attention is all you need&quot;.</p><p>The architecture visually looks like the one below. The left side is the encoder block and the right side is the decoder block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*mf-7zMYM0EGbMi599M2n0g.png" /><figcaption>Attention is all you need</figcaption></figure><h3>Why Learn Transformers?</h3><p>Well, what I think is the need to find a new one there must be at least one of the three reasons.</p><ol><li>Efficiency</li><li>Performance</li><li>Better than previous</li></ol><p>In the machine learning context efficiency can mean training or inference. The performance here means model performance on the unseen test set. The previous sets of deep learning algorithms like LSTM or GRU or CNN provided good performance and good efficiency but there are certain drawbacks to them.</p><ol><li>CNNs The ability to capture long-term dependencies.</li><li>LSTM&#39;s abilities to capture long-term dependencies are suboptimal.</li><li>RNN-type networks like LSTM/GRU are very notorious to train for big datasets cause they work sequentially and are computationally expensive.</li><li>Very limited interpretability.</li></ol><p>So Transformers addresses the computational efficiency in the train problem and the long sequence problem. In layman’s terms transformer could understand the pattern of text without recurrence and thus the updation of gradient is faster and simpler.</p><h3>How do Transformers Work?</h3><p>The simplest way you could answer this is</p><p>We give in an input, and something happens let&#39;s say it is a black box and an output is generated like magic.</p><p>Now, let&#39;s cut open the black box to see the inside of it.</p><p>It consists of an encoder block and a decoder block.</p><p>Let’s see on a high level the job of these two blocks.</p><p><strong>Encoder</strong> is responsible to give the context vector of the input sequence. The context vector is nothing but a fancy name for vectors that contains information on the input sequences such that that vector kind of gives the summary of the input and the objective to form a context vector is to get a numerical representation such that ideally there isn’t the loss of information.</p><p><strong>Decoder</strong> is responsible to generate the output desired sequence. It takes the help of the context vector to generate the output sequence.</p><p>Let&#39;s go step by step by zooming in on the transformer architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*wAV5kmMqfLZuEEhACMh_yA.png" /><figcaption>Encoder Part of transformers</figcaption></figure><h3>The Pipeline of Transformers</h3><p>We will learn the pipeline of the transformers in steps</p><p><strong>Step 1</strong>:- Word Embedding Layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*9J2-_0MU3qsBxtUlltc2bw.png" /><figcaption>Step 1: The input sequence to the input embedding layer</figcaption></figure><p>But first, how do we get here? The input text is passed through a tokenizer. Now, what is a tokenizer? A tokenizer is an object which helps us to break the complex input sequence into more simplified smaller units called tokens. There are different ways to do tokenization maybe by rules, statistical, or neural network based. The way we tokenize the text is crucial cause that step also helps determines how the model looks into the sentence.</p><p>So after we tokenize, we feed the resulting tokens to the word embedding layer. Now, what is the word embedding layer? To put it simply it is a look-up table (python dictionary) where the representations of the token value and the token is the key.</p><p>Input is the batch and sequence (b, s)</p><p>Output is batch, sequence, and embedding dimension (b, s, d_m)</p><p><strong>Step 2</strong>:- Positional Encoding Layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*R3MIgxA0-lBTxc2lIuSQVw.png" /><figcaption>Step2: Positional Encoding</figcaption></figure><p>From the name itself, we can know that this layer has something to do with the output from the input embedding layer i.e. word embedding being encoded and it has something to do with positions.</p><blockquote>This layer gives some kind of information on time steps as we see in RNN-type networks. The sequence information is important. The encoding can be done in many ways but in the paper “Attention Is All You Need” they used sine and cosine functions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*Kywwg21qHCdmVu943Pg4uA.png" /><figcaption>Positional Encoding</figcaption></figure><p>Till now the input goes through the word embedding layer and positional encoding layer and we get a resulting matrix that contains the representations of words with positional information in it.</p><p>Input is batch, sequence, and embedding dimension (b, s, d_m)</p><p>Output is batch, sequence, and embedding dimension (b, s, d_m)</p><p><strong>Step 3</strong>:- Input to Encoder layer</p><p>An encoder consists of</p><ol><li>Multi-Head attention</li><li>Feed Forward Network</li><li>Add and Norm</li></ol><p>This step is key to understanding the faster efficiency of training data, and how are the authors able to achieve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*dFbDCH1Nsz0_5HiEHcGJrw.png" /><figcaption>Step3:- Input to the encoder</figcaption></figure><p><strong>Step 3 a</strong>:- Multi-Headed Attention</p><p>This layer&#39;s main is self-attention over the inputs. But what is self-attention? The idea of self-attention is to focus on different parts of an input sequence for different tokens including itself. Mathematically it simply calculates the weighted sum at each position where the weights are learned based on the similarity between each pair of positions. Self-attention is computed by Scaled Dot product attention. It looks something like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*AdDHJvgL-z5NbNN_dWDqrQ.png" /><figcaption>Scaled Dot Product Attention</figcaption></figure><p>The 1st phase here is to create 3 vectors from the input to encoder block vectors. So for each token, we create a query, key, and value vector. These vectors are created by multiplying the embedding by three matrices that we trained during the training process namely W_q, W_k, and W_v.</p><p>Point to note that the query, key, and value concept come from the retrieval system. For example, when you type a query to search for a video on youtube, the engine will run a query to get the set of keys for the example video title, etc, and present you the best-matched video (value)(taken from a StackOverflow answer).</p><p>The 2nd phase here is to calculate the self-attention score. The score is calculated by having a dot product between the query vectors of all the tokens in input and the key vector of the respective token in consideration. This is the matmul step.</p><p>The third phase is to divide the self-attention score by the square root of the dimension of the key vector for stable gradients to avoid exploding effects. This is scale step.</p><p>The fourth phase is to run a softmax through the scores. This is the softmax step. Softmax gives us the probability distribution.</p><p>The fifth phase is to multiply the value vector of that token by the softmax we got for that token which produces weighted value vectors. This is the matmul step.</p><p>The sixth phase is, to sum up, weighted value vectors.</p><p>The weighted value vector is the output of the self-attention layer for that position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*WWPuf_FQqegte8M-EOm5hg.png" /><figcaption>The screen-shot was taken from Jay Almar Blog</figcaption></figure><p>These phases are for the calculation of the self-attention network.</p><p>Now the same thing happens to all the heads</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*WrqrwZo5dfgQKGPA5s7mNQ.png" /><figcaption>Multihead attention</figcaption></figure><p>There are two benefits of this layer:-</p><ol><li>Operations are easily parallelizable as we do matrix multiplication. The outputs of multiple heads are not dependent on each other.</li><li>Multi-head attention makes the context vector formed at the end of the encoder better because it looks at the same input sequence from different perspectives.</li></ol><p>For each attention head, we get a vector at the end. So all of the vectors output from the attention head is concatenated at the end to make a vector more suitable to the dimensionality of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*sfAMaPnOhzJqKPspQyDLzA.png" /><figcaption>The image was taken from Jay Almar Blog</figcaption></figure><p>This process is highly parallelizable but it is just a weighted average.</p><p>Input is batch, sequence, and embedding dimension (b, s, d_m)</p><p>Intermediate is batch, sequence, and embedding dimension reduced 512 to 64 (concatenation)(b, s, d_m)</p><p>Output is batch, sequence, and embedding dimension(b, s, d_m)</p><p>Step 3 b :- FFNN</p><p>The output of the multi-head attention layer is passed through a feed-forward neural network that applies two linear transformations and a nonlinear transformation(ReLU or GELU) to the output of multi-head attention. This network operates independently in each position.</p><p>What I think this layer really does is as</p><ol><li>Learn complex local relation</li><li>Make sure that the attention head is in the next encoder and has a different representation of data for different perspectives.</li><li>It also acts like a regularizer by adding dropouts.</li></ol><pre>Linear -&gt; Relu/Gelu -&gt; Linear</pre><p>Step 3c:- Add &amp; Norm</p><p>In this step, the residual connection is added to the output from the previous layer with the input to the previous layer to preserve any information we lost, maybe. The outputs are then normalized. The layer normalization substantially reduces the train time.</p><pre>ouyputs = layer_norm(resudial_conection(input, sublayer(output)))</pre><p>Step 4:- The context vector is generated.</p><p>So step 3 happens for the number of layers the encoder layers are stacked. A final output matrix containing continuous representation from the input is generated called the context vector.</p><p>This warps up the encoder part.</p><p>Now comes the decoder part. The decoder is autoregressive. The decoder takes the previous output generated by it and the output from the context vector as inputs for generating the current response. It stops decoding with it predicts &lt;END&gt; token.</p><p>Step 4:- Output sequence embeddings and their positional embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*h8XbVcDKuybJabidiEueEQ.png" /><figcaption>Embedding for the output sequence</figcaption></figure><p>The output sequence goes through an embedding layer and a positional encoding layer just like we saw in the encoder to get positional embeddings.</p><p>Step 5- Decoder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*LylUb6YHJlMM-7uSEA_Taw.png" /><figcaption>Decoder</figcaption></figure><p>A decoder looks something like this. it consists of</p><ol><li>Masked Multi-head attention</li><li>Encoder-Decoder Multi-Head Attention</li><li>Feed Forward Network</li><li>Add and Norm</li></ol><p>Step 5 a:- Masked Multihead Attention</p><p>We now know how multi-head attention in encoder block functions. In the decoder block, it employs a special technique of masking the future sequences in order to make the model learn. As the property of the model is auto-regressive, we mask all the values to inputs of the softmax which correspond to an illegal connection.</p><p>Step 5 b:- Encoder-Decoder Multi-Head attention</p><p>Here the queries and the keys are the output of the encoder a.k.a the context vector. The values are the output of the masked multi-head attention.</p><p>The main idea of this layer is what part of the context vector (generated by the encoder) is responsible for that particular sequence in output.</p><p>Step 5 c:- Point Wise Feedforward Layer</p><p>It is the same that happens in the encoder so repeating it here won&#39;t really matter.</p><p>Step 5d:- Add and Norm</p><p>It is the same that happens in the encoder so repeating it here won’t really matter.</p><p>Step 5 happens for the number of times the decoder layers are stacked.</p><p>Step 6:- Linear Classifier</p><p>This layer is the classifier head. Suppose you have 20,000 words to predict, so you will have 20,000 linear layer neurons to map it from the last decoder output.</p><p>Step 7:- Softmax</p><p>The output of the linear step is of size 20,000 we apply softmax over the vector and get a probability distribution. Finally, we take the index of the max-probability and that is our output.</p><p>The transformer model architecture looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*huYoDj6j_RW8YpEtXa1kuA.png" /></figure><h3>Let&#39;s see a dry run through Transformers</h3><p>First, the tokenizer tokenizes the input sentence to individual tokens according to a certain strategy.</p><p>The tokens are then fed into an input embedding layer which converts each token to a vector representation of fixed size(embedding size) and applies positional encoding to them.</p><p>The embedded positional tokens then go into the encoder block consisting of multi-head attention, feedforward network, and layer normalization.</p><p>The embedded positional tokens go to the multi-head attention layer which does self-attention and allows the model to capture the dependencies between tokens of the sequence.</p><p>The output of the multi-head attention layers is then concatenated and fed into the layer normalization part where the residuals and added with the concatenated outputs and layer normalization is done.</p><p>The output of that layer normalization is then fed into a position-wise Feedforward network and consists of two linear layers with a nonlinearity between them to capture the non-linear complex relationships in the sequence and make the n+1th multi-head encoder see a different perspective about the sequences.</p><p>At the end of all the encoders, it produces a context vector to represent a vector having a complex relationship in the input sequence.</p><p>The desired output sequence is fed to the embedding and position encoder layer making it have the embedded position encoded vector. The model is autoregressive i.e. it takes the context vector and previous output to make the current output. The embedded position encoded vector is then fed to the decoder consisting of masked multi-head attention, add and norm layer, feed-forward layer, and the encoder-decoder attention layer.</p><p>The encoded positional output sequence is fed to the masked multi-head attention, here the future tokens are masked to avoid illegal operations that maintain the auto-regressive property of the model.</p><p>The outputs from the layer along with the output from the encoder are then fed to the encoder-decoder multi-head attention. The context vector is used as the key and value and the masked attention output is the query to find the pattern between the input and desired output sequence.</p><p>Then the feedforward and addition of residual takes place and finally, a linear classification head is placed to map with output dimension and a softmax to get the probability distribution. So depending on our logic we select the desired token for generating the output sequence.</p><p>And it learns via backpropagating the loss and updating the weights.</p><h3>Some questions to think about or just test your understanding:-</h3><ol><li>Transformers/Bert is a huge network, how do we arrive if we want to use it and if so how do we put it into production?</li><li>What actually makes the transformer network so good in terms of performance?</li><li>How does Transformer architecture handle variable-length input sequences?</li><li>What is the difference between an encoder and a decoder in transformer architecture?</li><li>What is BERT? Why doesn&#39;t it have a decoder?</li><li>Tasks for transformer-like architecture and bert-like architecture.</li></ol><h3>References and pictures were taken:-</h3><ol><li><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a> (Attention is all you need)</li><li><a href="https://arxiv.org/abs/1810.04805">https://arxiv.org/abs/1810.04805</a> (BERT)</li><li><a href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer/</a> (Jay’s Blog)</li><li><a href="https://www.youtube.com/watch?v=rBCqOTEfxvg">https://www.youtube.com/watch?v=rBCqOTEfxvg</a> (Attention is all you need; Attentional Neural Network Models | Łukasz Kaiser | Masterclass)</li></ol><p>Hope you liked this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18df5347b7ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>