<?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 Nikhil Cheke on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Cheke on Medium]]></description>
        <link>https://medium.com/@nicks-cheke44?source=rss-533913bcef90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0FrM82sTWijIPIIIatzG7A.jpeg</url>
            <title>Stories by Nikhil Cheke on Medium</title>
            <link>https://medium.com/@nicks-cheke44?source=rss-533913bcef90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:37:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicks-cheke44/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[Knowledge Distillation: A Comprehensive Guide]]></title>
            <link>https://nicks-cheke44.medium.com/knowledge-distillation-a-comprehensive-guide-ca0b703ba68a?source=rss-533913bcef90------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca0b703ba68a</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nikhil Cheke]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 09:36:03 GMT</pubDate>
            <atom:updated>2024-09-23T09:36:03.215Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Knowledge distillation is a model compression technique where a smaller, less complex model (student model) is trained to mimic the behavior of a larger, more accurate model (teacher model). The goal is to transfer the knowledge learned by the larger model into a smaller model, allowing it to achieve comparable performance with much fewer computational resources.</em></p><p><em>This method is particularly useful when deploying models on resource-constrained devices, like mobile phones, edge devices, or real-time systems, where running a large model is impractical.</em></p><h3>Theory of Knowledge Distillation</h3><h4>1. Teacher Model:</h4><p>The <strong>teacher</strong> is a large, pre-trained model. It is usually trained using the conventional training method with a dataset and labeled outputs. The teacher model is powerful due to its complexity, but it may be slow and resource-heavy.</p><h4>2. Student Model:</h4><p>The <strong>student</strong> is a smaller, less complex model designed to mimic the teacher’s performance. Its architecture can have fewer layers, parameters, or simpler operations, making it more efficient in terms of speed and memory usage.</p><h4>3. Soft Targets:</h4><p>Instead of training the student model on hard labels (i.e., ground truth), the student model is trained on the <strong>soft targets</strong> produced by the teacher model. Soft targets contain more information than hard labels. For example, for a multi-class classification task, a teacher might produce outputs like:</p><ul><li>Dog: 90%</li><li>Wolf: 8%</li><li>Cat: 2%</li></ul><p>These probabilities (soft labels) give insight into the teacher’s confidence in each class, not just the correct class.</p><h4>4. Temperature Scaling:</h4><p>To smooth the output probabilities and make them more informative, the softmax output of the teacher model is divided by a temperature value T. A higher T makes the probability distribution softer and more uniform, highlighting the relative probabilities of incorrect classes.</p><p>The softmax function with temperature scaling is given as:</p><h4>Pi = [exp⁡(zi/T)] / [∑j exp⁡(zj/T)]</h4><p>Where zi​ are the logits (the unnormalized outputs) from the model, and T is the temperature parameter.</p><h4>5. Loss Function:</h4><p>In knowledge distillation, the student model is trained using a combination of two losses:</p><ul><li><strong>Cross-Entropy Loss</strong> for the hard labels (ground truth).</li><li><strong>Kullback-Leibler (KL) Divergence</strong> Loss for the soft labels (output probabilities of the teacher).</li></ul><p>The total loss is a weighted sum of the two losses:</p><h4>L = α.Lhard + (1-α)Lsoft</h4><p>Where:</p><ul><li>Lhard​ is the cross-entropy loss between the student’s predictions and the ground truth.</li><li>Lsoft​ is the distillation loss (KL divergence) between the softmax outputs of the teacher and student models.</li><li>α is a balancing factor between the two losses.</li></ul><h3>Practical Example</h3><p>In this section, I’ll provide a step-by-step implementation using <strong>PyTorch</strong> to distill a smaller student model from a larger teacher model on the <strong>MNIST</strong> dataset.</p><h4>Step 1: Install Dependencies</h4><pre>pip install torch torchvision</pre><h4>Step 2: Define the Teacher and Student Models</h4><p>We’ll define two convolutional neural networks (CNNs), one for the teacher (large model) and one for the student (small model).</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from torch.utils.data import DataLoader<br><br># Define the larger Teacher model<br>class TeacherNet(nn.Module):<br>    def __init__(self):<br>        super(TeacherNet, self).__init__()<br>        self.conv1 = nn.Conv2d(1, 32, 3, 1)<br>        self.conv2 = nn.Conv2d(32, 64, 3, 1)<br>        self.fc1 = nn.Linear(9216, 128)<br>        self.fc2 = nn.Linear(128, 10)<br><br>    def forward(self, x):<br>        x = F.relu(self.conv1(x))<br>        x = F.relu(self.conv2(x))<br>        x = F.max_pool2d(x, 2)<br>        x = torch.flatten(x, 1)<br>        x = F.relu(self.fc1(x))<br>        x = self.fc2(x)<br>        return x<br><br># Define the smaller Student model<br>class StudentNet(nn.Module):<br>    def __init__(self):<br>        super(StudentNet, self).__init__()<br>        self.conv1 = nn.Conv2d(1, 16, 3, 1)<br>        self.conv2 = nn.Conv2d(16, 32, 3, 1)<br>        self.fc1 = nn.Linear(4608, 64)<br>        self.fc2 = nn.Linear(64, 10)<br><br>    def forward(self, x):<br>        x = F.relu(self.conv1(x))<br>        x = F.relu(self.conv2(x))<br>        x = F.max_pool2d(x, 2)<br>        x = torch.flatten(x, 1)<br>        x = F.relu(self.fc1(x))<br>        x = self.fc2(x)<br>        return x</pre><h4>Step 3: Define the Knowledge Distillation Loss</h4><p>We’ll define a custom loss function that combines cross-entropy loss with the teacher’s soft targets.</p><pre>class DistillationLoss(nn.Module):<br>    def __init__(self, teacher_model, temperature=2.0, alpha=0.5):<br>        super(DistillationLoss, self).__init__()<br>        self.teacher_model = teacher_model<br>        self.temperature = temperature<br>        self.alpha = alpha<br>        self.ce_loss = nn.CrossEntropyLoss()  # Hard label loss<br>        self.kl_loss = nn.KLDivLoss(reduction=&quot;batchmean&quot;)  # Distillation loss<br><br>    def forward(self, student_logits, teacher_logits, labels):<br>        # Cross-entropy loss with true labels<br>        ce_loss = self.ce_loss(student_logits, labels)<br>        <br>        # KL divergence loss between teacher and student predictions (softened)<br>        student_soft = torch.log_softmax(student_logits / self.temperature, dim=-1)<br>        teacher_soft = torch.softmax(teacher_logits / self.temperature, dim=-1)<br>        distill_loss = self.kl_loss(student_soft, teacher_soft) * (self.temperature ** 2)<br><br>        # Weighted combination of both losses<br>        return self.alpha * ce_loss + (1 - self.alpha) * distill_loss</pre><h4>Step 4: Training the Teacher Model</h4><pre># Hyperparameters<br>batch_size = 64<br>learning_rate = 0.001<br>epochs = 5<br><br># Data loading<br>transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])<br>train_dataset = datasets.MNIST(&#39;./data&#39;, train=True, download=True, transform=transform)<br>train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)<br><br># Train the Teacher model<br>teacher_model = TeacherNet().cuda()<br>optimizer = optim.Adam(teacher_model.parameters(), lr=learning_rate)<br><br>def train_teacher(model, loader, optimizer):<br>    model.train()<br>    criterion = nn.CrossEntropyLoss()<br>    for epoch in range(epochs):<br>        total_loss = 0<br>        for data, target in loader:<br>            data, target = data.cuda(), target.cuda()<br>            optimizer.zero_grad()<br>            output = model(data)<br>            loss = criterion(output, target)<br>            loss.backward()<br>            optimizer.step()<br>            total_loss += loss.item()<br>        print(f&quot;Epoch {epoch+1}, Loss: {total_loss/len(loader)}&quot;)<br><br>train_teacher(teacher_model, train_loader, optimizer)</pre><h4>Step 5: Training the Student Model with Knowledge Distillation</h4><pre># Train the Student model using distillation<br>student_model = StudentNet().cuda()<br>optimizer_student = optim.Adam(student_model.parameters(), lr=learning_rate)<br><br>def train_student(teacher_model, student_model, loader, optimizer, temperature=2.0, alpha=0.5):<br>    teacher_model.eval()  # Freeze teacher model<br>    student_model.train()  # Train student model<br>    criterion = DistillationLoss(teacher_model, temperature, alpha)<br>    <br>    for epoch in range(epochs):<br>        total_loss = 0<br>        for data, target in loader:<br>            data, target = data.cuda(), target.cuda()<br><br>            # Forward pass through the teacher model<br>            with torch.no_grad():<br>                teacher_logits = teacher_model(data)<br>            <br>            # Forward pass through the student model<br>            student_logits = student_model(data)<br>            <br>            # Compute the distillation loss<br>            loss = criterion(student_logits, teacher_logits, target)<br>            <br>            # Backpropagation<br>            optimizer.zero_grad()<br>            loss.backward()<br>            optimizer.step()<br>            <br>            total_loss += loss.item()<br>        print(f&quot;Epoch {epoch+1}, Loss: {total_loss/len(loader)}&quot;)<br><br>train_student(teacher_model, student_model, train_loader, optimizer_student)</pre><h3>Explanation of the Code:</h3><ol><li><strong>Teacher Model</strong>: The teacher model is a larger CNN that has been trained on the MNIST dataset using the ground-truth labels (cross-entropy loss). It is kept frozen during the student model training.</li><li><strong>Student Model</strong>: The student model is a smaller, more efficient CNN. Instead of training it with just hard labels, it is trained using both the hard labels (ground truth) and the soft labels (teacher’s logits).</li><li><strong>Distillation Loss</strong>: A custom DistillationLoss class is defined, which combines the hard label loss (cross-entropy) and the soft label loss (KL divergence) with a weighting factor α and temperature T.</li><li><strong>Training the Student</strong>:</li></ol><ul><li>For each batch, the student model computes predictions on the input data.</li><li>Simultaneously, the teacher model generates soft targets by forwarding the same data.</li><li>The loss is computed by mixing the cross-entropy loss (for hard labels) and the KL divergence loss (between teacher and student soft logits).</li><li>The student model is updated using backpropagation.</li></ul><h3>Tuning Hyperparameters:</h3><ul><li><strong>Temperature T</strong>: A higher temperature produces softer probability distributions, which helps the student learn better from the teacher’s knowledge.</li><li><strong>Alpha α</strong>: Controls the weight of hard-label cross-entropy loss and soft-label distillation loss. A typical value is α=0.5, balancing both contributions.</li></ul><h3>Advantages of Knowledge Distillation:</h3><p>Knowledge distillation offers several advantages, particularly in scenarios where deploying large models is not feasible due to resource constraints. Here are some key benefits:</p><p><strong>Model Compression: </strong>The primary advantage of knowledge distillation is the ability to compress large, complex models into smaller, more efficient models. The student model is typically much smaller than the teacher model, which reduces memory usage, making it easier to deploy on edge devices, mobile phones, or web services.<strong><br>Faster Inference: </strong>Smaller student models tend to have fewer parameters and lighter architectures, which makes them faster at inference time. This is especially important for real-time applications such as chatbots, mobile apps, and IoT devices, where speed is critical.</p><p><strong>Retained Performance: </strong>Despite being smaller, student models often retain a large portion of the performance of the teacher model. By learning from the soft predictions of the teacher model, the student can capture intricate patterns that it might not learn from hard labels alone.</p><p><strong>Improved Generalization:</strong> Since the student model learns from the teacher’s softer output probabilities (which contain richer information than hard labels), the student often generalizes better, especially in cases of noisy data or limited training samples.</p><p><strong>Flexibility in Model Architecture:</strong> Knowledge distillation allows for flexibility in choosing the architecture of the student model. The student model doesn’t need to have the same architecture as the teacher model, allowing for custom design choices based on the deployment requirements, such as depth, number of parameters, or activation functions.</p><p><strong>Reduced Overfitting: </strong>Distillation can act as a form of regularization. Since the student is trained on the teacher’s predictions, it tends to focus on capturing broader patterns rather than overfitting to specific examples or noise in the data.</p><p><strong>Ensemble Distillation: </strong>Knowledge distillation can also be extended to ensemble models. Instead of training a student from a single teacher, you can distill knowledge from multiple models or an ensemble of teachers into a single student model, allowing the student to leverage the combined strengths of the ensemble.</p><p><strong>Model Deployment in Low-Resource Environments: </strong>By compressing models into smaller sizes, knowledge distillation enables the deployment of AI models in low-resource environments where computational power and memory are limited. This is crucial for applications in areas like autonomous vehicles, drones, or healthcare devices.</p><p><strong>Cross-Domain Knowledge Transfer:</strong>In some cases, the student model can be trained on a different data domain than the teacher model, leveraging the teacher’s knowledge to perform well on a task that might not have enough training data.</p><h3>Conclusion</h3><p>Knowledge distillation is a powerful technique for compressing large, complex models into smaller, more efficient versions without significant loss of performance. By transferring the knowledge from a high-performing teacher model to a smaller student model, we achieve the dual benefits of reducing computational resource consumption and maintaining accuracy.</p><p>This approach is particularly relevant in domains like natural language processing (NLP), where state-of-the-art models such as BERT, GPT, and other transformer-based architectures are often too large to deploy in real-time applications. By distilling these models, we can enable their use in mobile devices, edge computing, and other resource-constrained environments, where speed and efficiency are critical.</p><p>As machine learning models continue to grow in complexity, the importance of techniques like knowledge distillation will only increase. Future research could focus on refining distillation methods to better handle diverse tasks, improving the transfer of knowledge across domains, and addressing challenges like distilling from an ensemble of teacher models.</p><p>In conclusion, knowledge distillation offers an effective solution for model compression, enabling the deployment of high-performing models in real-world environments where computational resources are limited, and speed is essential.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca0b703ba68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing in Machine Learning: A Detailed Guide]]></title>
            <link>https://nicks-cheke44.medium.com/data-preprocessing-in-machine-learning-a-detailed-guide-c710df69073f?source=rss-533913bcef90------2</link>
            <guid isPermaLink="false">https://medium.com/p/c710df69073f</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nikhil Cheke]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 16:37:49 GMT</pubDate>
            <atom:updated>2024-08-22T16:37:49.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Data preprocessing is a crucial step in the creation of machine learning models, as it ensures that the data is clean, consistent, and ready for the model to learn from. Here’s a structured approach to data preprocessing:</p><h3>1. Data Collection</h3><h4><strong>Gather Data</strong>:</h4><p>The first step is to collect data from relevant sources, which might include databases, CSV files, APIs, or web scraping. The quality and quantity of the data you collect will significantly impact the performance of your machine learning model.</p><h4><strong>Understand the Data</strong>:</h4><p>After collecting the data, it’s essential to explore and understand it. This includes understanding the features (columns), the target variable (what you want to predict), the types of data (numeric, categorical, text), and identifying potential issues such as missing values, outliers, or inconsistencies. Use tools like Pandas for Python to load and inspect your data, and visualization tools like Matplotlib or Seaborn to explore it visually.</p><h3>2. Data Cleaning</h3><h4><strong>Handling Missing Values</strong>:</h4><p><strong>Remove Missing Data</strong>: If the dataset has missing values that are not significant or are randomly scattered (missing completely at random), you might decide to remove these rows or columns. However, this is only advisable when the proportion of missing data is small, as dropping too much data can lead to loss of valuable information.</p><p><strong>Impute Missing Data</strong>: When removing data isn’t an option, imputing (filling in) missing values is crucial. Techniques for imputation include:</p><ul><li><strong>Mean/Median Imputation</strong>: Replace missing values with the mean or median of the column, which is useful for numerical data.</li><li><strong>Mode Imputation</strong>: For categorical data, replace missing values with the most frequent value (mode).</li><li><strong>Predictive Imputation</strong>: Use models like k-Nearest Neighbors (KNN) to predict and fill in missing values based on other available data.</li><li><strong>Forward/Backward Fill</strong>: In time series data, missing values can be filled based on previous (forward fill) or subsequent (backward fill) values.</li></ul><h4><strong>Outlier Detection and Treatment</strong>:</h4><ul><li><strong>Identify Outliers</strong>: Outliers are data points that differ significantly from other observations. They can be detected using statistical methods like Z-scores (which measure the number of standard deviations away from the mean a data point is) or the Interquartile Range (IQR), which measures statistical dispersion.</li><li><strong>Handle Outliers</strong>: Once identified, outliers can be handled by: <strong>1. Removing</strong>: Simply exclude outliers from the dataset if they are errors or if they unduly influence the model. 2.<strong>Transforming</strong>: Apply transformations like log or square root to reduce the impact of outliers. 3.<strong>Capping/Flooring</strong>: Set upper and lower bounds (e.g., the 5th and 95th percentiles) and replace outliers beyond these limits with these thresholds.</li></ul><h4><strong>Duplicate Data Removal</strong>:</h4><ul><li><strong>Identify Duplicates</strong>: Duplicates can occur due to data entry errors or merging datasets. They can be identified using functions like pandas.DataFrame.duplicated() in Python.</li><li><strong>Remove Duplicates</strong>: Once identified, duplicates should be removed to prevent them from skewing the analysis or model results.</li></ul><h3>3. Data Transformation</h3><h4><strong>Feature Scaling</strong>:</h4><ul><li><strong>Normalization</strong>: Normalization scales the data to a range between 0 and 1 or -1 and 1. This is particularly useful when the model relies on distance metrics, like K-Nearest Neighbors (KNN) or Neural Networks. ​​</li><li><strong>Standardization</strong>: Standardization rescales data so that it has a mean of 0 and a standard deviation of 1, which is important for algorithms like Support Vector Machines (SVM) or logistic regression.</li></ul><h4><strong>Encoding Categorical Variables</strong>:</h4><ul><li><strong>Label Encoding</strong>: Label encoding converts categorical variables into integers. For example, the categories “red”, “green”, “blue” could be encoded as 0, 1, and 2, respectively. This method is simple but can introduce ordinal relationships where none exist.</li><li><strong>One-Hot Encoding</strong>: One-hot encoding converts categorical variables into a binary matrix, where each category is represented by a binary vector. For example, “red”, “green”, “blue” would become three binary columns, with only one column being 1 for each category and the others being 0. This method is useful for algorithms that can’t handle categorical data directly.</li></ul><h4><strong>Feature Engineering</strong>:</h4><ul><li><strong>Create New Features</strong>: Sometimes, the original features might not be sufficient to capture the underlying patterns in the data. In such cases, you can create new features by combining or transforming existing ones. For example, you can create interaction features by multiplying two features together or create polynomial features to model non-linear relationships.</li><li><strong>Polynomial Features</strong>: Polynomial features are new features created by raising existing features to a power.</li></ul><h3>4. Dimensionality Reduction</h3><h4><strong>Feature Selection</strong>:</h4><ul><li><strong>Remove Irrelevant Features</strong>: Some features might not contribute to the model’s predictive power or may even introduce noise. Feature selection techniques, like correlation analysis, can help identify and remove such features. For instance, if two features are highly correlated, one of them might be redundant and could be dropped.</li><li><strong>Regularization Techniques</strong>: Techniques like Lasso (L1 regularization) and Ridge (L2 regularization) not only prevent overfitting but also help in feature selection by shrinking less important feature coefficients to zero.</li></ul><h4><strong>Principal Component Analysis (PCA)</strong>:</h4><ul><li><strong>Reduce Dimensionality</strong>: PCA is a technique that reduces the dimensionality of the data by transforming it into a new set of variables (principal components), which are linear combinations of the original variables. The goal is to capture the most variance with the fewest components. This is especially useful when you have a large number of features, as it can reduce computational complexity and improve model performance.</li></ul><h3>5. Data Splitting</h3><h4><strong>Train-Test Split</strong>:</h4><ul><li><strong>Split Data</strong>: To evaluate the performance of a model, the dataset is typically split into a training set (used to train the model) and a testing set (used to evaluate the model’s performance). A common split ratio is 70–30 or 80–20, depending on the size of the dataset.</li><li><strong>Why Split Data?</strong>: Splitting the data helps prevent overfitting, where a model performs well on training data but poorly on unseen data. By testing the model on a separate set of data (the test set), you can get a better estimate of its real-world performance.</li></ul><h4><strong>Cross-Validation</strong>:</h4><ul><li><strong>K-Fold Cross-Validation</strong>: This technique involves splitting the data into K folds and training the model K times. Each time, a different fold is used as the validation set, while the remaining K-1 folds are used for training. The model’s performance is averaged across all K folds to give a more reliable estimate. Cross-validation is particularly useful for small datasets, where splitting into just training and test sets might not provide enough data for training.</li></ul><h3>6. Handling Imbalanced Data</h3><h4><strong>Resampling Techniques</strong>:</h4><ul><li><strong>Oversampling</strong>: When dealing with imbalanced data (where one class is underrepresented), oversampling increases the number of instances in the minority class. Techniques like SMOTE (Synthetic Minority Over-sampling Technique) generate synthetic examples based on existing ones.</li><li><strong>Undersampling</strong>: This technique involves reducing the number of instances in the majority class to balance the dataset. However, this can lead to loss of valuable data and should be done carefully.</li></ul><h4><strong>Synthetic Data Generation</strong>:</h4><p>In cases where oversampling or undersampling might not be sufficient, generating synthetic data for the minority class can help balance the dataset. Techniques like SMOTE create synthetic samples by interpolating between existing minority class samples.</p><h3>7. Data Augmentation (For Images/Text)</h3><ul><li><strong>Images</strong>: Data augmentation in images involves applying transformations like rotation, flipping, zooming, and shifting to create more diverse training data. This helps improve the model’s robustness by exposing it to various forms of the same data.</li><li><strong>Text</strong>: Text data can be augmented by techniques like paraphrasing (rewriting sentences with the same meaning), synonym replacement (substituting words with their synonyms), or back-translation (translating text to another language and back to introduce variation).</li></ul><h3>8. Data Integration</h3><ul><li><strong>Merge Data</strong>: If you have multiple datasets, data integration involves merging them into a single dataset. This step must ensure consistency in data formats, types, and units. For instance, merging sales data with customer demographic data could enrich the feature set for a predictive model.</li><li><strong>Feature Union</strong>: When combining features from different datasets, you might need to align them carefully, especially when dealing with time-series data or data with different sampling rates. Feature union can help bring together features from different sources while maintaining their integrity.</li></ul><h3>9. Data Encoding for Time Series</h3><ul><li><strong>Date Features</strong>: In time series data, dates often carry valuable information. Extracting features like year, month, day, hour, day of the week, or even whether the date falls on a weekend or holiday can provide important context for the model. For instance, sales might vary significantly between weekdays and weekends, or during certain months of the year.</li><li><strong>Lag Features</strong>: Lag features are created by shifting the time series data backward by a specific number of time steps. This helps in capturing the temporal dependencies between observations. For example, to predict sales today, you might include sales data from the past week as features.</li><li><strong>Rolling Statistics</strong>: Calculate rolling means, medians, or standard deviations over a specified window (e.g., 7-day or 30-day rolling averages) to capture trends and seasonality in the data. These features help the model understand the data’s short-term and long-term patterns.</li><li><strong>Difference Features</strong>: Sometimes, the difference between consecutive time points is more informative than the actual values. By calculating and using these differences, the model can better capture changes over time.</li></ul><h3>Example Using Python and Scikit-Learn</h3><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.impute import SimpleImputer<br>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.ensemble import RandomForestClassifier<br><br># Load dataset<br>data = pd.read_csv(&#39;data.csv&#39;)<br><br># Data Cleaning<br>data.drop_duplicates(inplace=True)<br>data.fillna(method=&#39;ffill&#39;, inplace=True)<br><br># Define Features and Target<br>X = data.drop(&#39;target&#39;, axis=1)<br>y = data[&#39;target&#39;]<br><br># Data Transformation<br>numeric_features = [&#39;age&#39;, &#39;income&#39;]<br>categorical_features = [&#39;gender&#39;, &#39;education&#39;]<br><br>numeric_transformer = Pipeline(steps=[<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;mean&#39;)),<br>    (&#39;scaler&#39;, StandardScaler())])<br><br>categorical_transformer = Pipeline(steps=[<br>    (&#39;imputer&#39;, SimpleImputer(strategy=&#39;constant&#39;, fill_value=&#39;missing&#39;)),<br>    (&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))])<br><br>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&#39;num&#39;, numeric_transformer, numeric_features),<br>        (&#39;cat&#39;, categorical_transformer, categorical_features)])<br><br># Split Data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Create and Train Model<br>model = Pipeline(steps=[(&#39;preprocessor&#39;, preprocessor),<br>                        (&#39;classifier&#39;, RandomForestClassifier())])<br><br>model.fit(X_train, y_train)<br><br># Evaluate Model<br>accuracy = model.score(X_test, y_test)<br>print(f&#39;Model accuracy: {accuracy}&#39;)</pre><p>This guide outlines the essential steps for data preprocessing in machine learning, including data cleaning, transformation, and encoding. It covers techniques such as handling missing values, outlier treatment, feature scaling, and dimensionality reduction. Special attention is given to encoding categorical variables, handling imbalanced data, and preparing time series data through feature extraction like lag features and rolling statistics. These preprocessing steps are critical for enhancing model performance and ensuring that the data is well-suited for analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c710df69073f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Rasa NLU custom component for spell checking in incoming message]]></title>
            <link>https://nicks-cheke44.medium.com/building-rasa-nlu-custom-component-for-spell-checking-in-incoming-message-742527b35d27?source=rss-533913bcef90------2</link>
            <guid isPermaLink="false">https://medium.com/p/742527b35d27</guid>
            <category><![CDATA[rasa-nlu]]></category>
            <category><![CDATA[rasa]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[custom-component]]></category>
            <dc:creator><![CDATA[Nikhil Cheke]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 12:15:18 GMT</pubDate>
            <atom:updated>2020-10-08T12:15:18.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4B2BcHMGNAn3KuzAdFYWpA.png" /></figure><h3><strong>Overview</strong></h3><p>Using pre built Rasa pipeline components we can do multiple things in customising the Rasa models. But in some situations we might want to implement features which are not pre built in Rasa NLU. One of such feature is spell checking. When Rasa NLU model receives incoming message from user with spelling mistakes, this might lead to incorrect intent classification and entity extraction. We can think about multiple solutions for spell checking problem as follows,</p><pre>1. Add all possible spelling mistakes in lookup table<br>2. Add all possible spelling mistakes in training data<br>3. Build a custom component for spell checking</pre><p>First two solutions from above list will take lot of time to prepare both lookup table and training data. So we will go with building custom component for spell checking.</p><h3>Adding a custom Spell Checker Component to the Rasa NLU</h3><p>In this spell checker custom component we are using <em>pyspellchecker </em>algorithm<em>. pyspellchecker </em>uses a <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a> algorithm to create all permutations from given input word within an edit distance of 2. It then compares all permutations (insertions, deletions, replacements, and transpositions) to known words in a word frequency list. It then select one word which is found more often in the frequency list as the correct result.</p><p><strong>Installation</strong></p><pre>pip install pyspellchecker</pre><p><strong>Example</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc0961ae86b65fa2a0be48301a05ff3/href">https://medium.com/media/4dc0961ae86b65fa2a0be48301a05ff3/href</a></iframe><p>Output of the above code will look like this,</p><pre>Misspelled word: pythen<br>Corrected word: python</pre><p>So now we are good to go for custom component code, let’s create <em>spellchecking.py</em> file as a component and <em>CorrectSpelling</em> as a component class,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/162a3fcdf423df16f4ae98a755693cb4/href">https://medium.com/media/162a3fcdf423df16f4ae98a755693cb4/href</a></iframe><p>In above code, in <em>process</em> function we are tokenising the input text from user and doing spell checking word by word on it. Finally building a sentence from these corrected tokens. That’s it! We are ready to pass this corrected sentence to further component mentioned in the pipeline.</p><p><strong>Where to put this component in the pipeline?</strong></p><p>It completely depends on your problem, but in current issue of spell checking we have to put this component before tokenisation in the pipeline. As a modification if you are passing tokens from tokenisation component directly to spell checker then you can put this component after tokenisation step in the pipeline. You can mention custom component in the following way in <em>nlu_config.yml</em> file,</p><pre>- name: &quot;spellchecking.CorrectSpelling&quot;</pre><p>Now you are ready to train the model and test the result against spelling mistakes.</p><p><strong>Training and Testing</strong></p><p>Before training the model and testing the input text, we have to set <em>pythonpath</em> for this rasa project so that Rasa can find our component,</p><pre>export PYTHONPATH=/path_to_your_project_dir/:$PYTHONPATH</pre><p>Now you can go for training and testing the Rasa model,</p><pre>1. rasa train nlu --config nlu_config.yml<br>2. rasa shell nlu</pre><h3><strong>Summary</strong></h3><p>In this post, we have learned how to create custom components for spell checking and how to add them to the Rasa NLU pipeline. There is a huge scope in writing your own component according to the given requirements.</p><p>Thanks, happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=742527b35d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First time Git Push for an open source project]]></title>
            <link>https://nicks-cheke44.medium.com/first-time-git-push-for-an-open-source-project-f24208ad6cb2?source=rss-533913bcef90------2</link>
            <guid isPermaLink="false">https://medium.com/p/f24208ad6cb2</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[git-push]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Nikhil Cheke]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 09:07:57 GMT</pubDate>
            <atom:updated>2020-12-02T12:15:56.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyM6CDN33knY9j9YHHXjTA.png" /></figure><p>I experienced this when I was contributing to an open source project for the first time. I clone the open source repository in my local, created new local branch and started working on it. When I was done with the changes, I tried to push the changes. But I ended up with this,</p><pre>remote: Permission to xxxxx/xxx.git denied to [your user name].<br>fatal: unable to access &#39;https/github.com/xxxx/xxxx.git&#39;:The requested URL returned error: 403</pre><p>After exploring multiple options as a solution, I found following working solution,</p><p><strong>Step 1:</strong></p><p>Go to open source repo page,</p><p>click on <em>Fork</em> button, which is present in top right corner of the page,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*_jGD7esk5wjJy_r1A1SM7g.png" /></figure><p>This will take you to your own Github page.</p><p><strong>Step 2:</strong></p><p>Now clone your forked repository instead of original, for this click on Code button,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*7atG7N_xhUrJZQ68IC-DKw.png" /></figure><p>Click on https and copy the https link.</p><p><strong>Step 3:</strong></p><p>Now clone the repo, create your local branch, made the code changes, add and commit those changes and push the code,</p><pre>1. git clone &lt;git repo https link&gt;<br>2. git checkout -b &lt;local branch name&gt;<br>3. git add .<br>4. git commit -m &quot;&lt;add comments&gt;&quot;<br>5. git push --set-upstream origin &lt;local branch name&gt;</pre><p><strong>Step 4:</strong></p><p>Go to your Github page and create new pull request.</p><p>That’a all ! Now wait for original author to accept it !</p><p>Hope this will help you. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f24208ad6cb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>