<?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 Dr. Dhanya NM on Medium]]></title>
        <description><![CDATA[Stories by Dr. Dhanya NM on Medium]]></description>
        <link>https://medium.com/@dhanyahari07?source=rss-ad0b01dc4651------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n54qk7LooJDvrK-IaF0B6Q.jpeg</url>
            <title>Stories by Dr. Dhanya NM on Medium</title>
            <link>https://medium.com/@dhanyahari07?source=rss-ad0b01dc4651------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:28:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhanyahari07/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[Improving Time Series Prediction Models Using Cyclic Features Encoding in Neural Networks]]></title>
            <link>https://medium.com/@dhanyahari07/improving-time-series-prediction-models-using-cyclic-features-encoding-in-neural-networks-0eebef307fc2?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/0eebef307fc2</guid>
            <category><![CDATA[cyclic-feature-encoding]]></category>
            <category><![CDATA[time-series-data-analysis]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 11:08:23 GMT</pubDate>
            <atom:updated>2025-06-09T11:08:23.325Z</atom:updated>
            <content:encoded><![CDATA[<p>This article deals with cyclic features and their encoding techniques for more efficient modeling.</p><p>Cyclic feature encoding is a method used to handle cyclical or periodic features in machine learning, such as time-related features (hours of the day, days of the week) or angular measurements (degrees, radians). These features exhibit cyclical behavior, meaning their values “wrap around” at certain points, creating an artificial discontinuity if encoded naively.</p><p>Cyclic feature encoding is a technique used in machine learning to represent cyclical data, such as time-series data or periodic features.</p><p>For example:</p><ul><li>The hour 23 (11 PM) is numerically distant from hour 0 (midnight), but conceptually they are just one hour apart.</li><li>In angles, 0° and 360° represent the same direction, yet they seem far apart numerically.</li></ul><p>If you were to encode a cyclic feature directly as a number, machine learning models (especially linear models) may fail to capture its cyclic structure, treating the endpoints as distinct rather than close together. This can harm performance in tasks where the cyclical nature is critical.</p><p>Cyclic feature encoding transforms the feature into two components using the sine and cosine functions, which map the values into a circular space. This maintains the cyclical continuity, avoiding the artificial discontinuity seen in raw numerical encoding.</p><p>This article analyses the performance of a machine-learning model taking cyclic features as such and encode these features using appropriate techniques.</p><p>Dataset</p><p><a href="https://www.kaggle.com/datasets/prasad22/weather-data/data">Weather Data</a></p><p><strong>Cyclic Encoding</strong></p><p>The following method can be used to encode the cyclic data using a transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*6_E2Kg-EQ3x1uFwsBczUzg.png" /></figure><ul><li>x : the value of the cyclic feature (e.g., hour = 15)</li><li>P: the period of the cycle (e.g., 24 for hours in a day)</li><li>xsin and xcos ​: the encoded values you feed into your model</li></ul><p>The following is the code for cyclic encoding and create a pytorch model</p><p><strong>import necessary packages</strong></p><pre>import pandas as pd<br>import numpy as np<br>from torch.utils.data import Dataset, DataLoader<br>import torch<br>import torch.nn as nn</pre><p><strong>Data import to pandas dataframe</strong></p><p>import data and change the data type of date-time column,this line is used to convert the Date_Time column in a DataFrame to <strong>pandas datetime objects</strong>. This is essential for any kind of <strong>time-based feature extraction</strong> (e.g., hour, day, month)</p><pre>df = pd.read_csv(&#39;weather_data.csv&#39;)  <br>df[&#39;Date_Time&#39;] = pd.to_datetime(df[&#39;Date_Time&#39;])</pre><p><strong>Pre-processing the dataset and cyclic encoding</strong></p><pre>def preprocess_weather_data(df):<br>    df = df.copy()<br>    df[&quot;Date_Time&quot;] = pd.to_datetime(df[&quot;Date_Time&quot;])<br>    df[&quot;hour&quot;] = df[&quot;Date_Time&quot;].dt.hour<br>    df[&quot;dayofweek&quot;] = df[&quot;Date_Time&quot;].dt.dayofweek<br>    df[&quot;month&quot;] = df[&quot;Date_Time&quot;].dt.month<br><br>    # Cyclic encoding<br>    df[&quot;hour_sin&quot;] = np.sin(2 * np.pi * df[&quot;hour&quot;] / 24)<br>    df[&quot;hour_cos&quot;] = np.cos(2 * np.pi * df[&quot;hour&quot;] / 24)<br><br>    df[&quot;day_sin&quot;] = np.sin(2 * np.pi * df[&quot;dayofweek&quot;] / 7)<br>    df[&quot;day_cos&quot;] = np.cos(2 * np.pi * df[&quot;dayofweek&quot;] / 7)<br><br>    df[&quot;month_sin&quot;] = np.sin(2 * np.pi * df[&quot;month&quot;] / 12)<br>    df[&quot;month_cos&quot;] = np.cos(2 * np.pi * df[&quot;month&quot;] / 12)<br><br>    df.drop(columns=[&quot;hour&quot;, &quot;dayofweek&quot;, &quot;month&quot;], inplace=True)<br>    return df<br>df=preprocess_weather_data(df)</pre><p>This function, preprocess_weather_data, takes a DataFrame (df) containing weather data and enhances its datetime features for better analysis. First, it makes a copy of the original DataFrame to avoid modifying it directly. It then converts the &quot;Date_Time&quot; column to a datetime format and extracts key temporal components—hour, day of the week, and month. To improve the representation of cyclical time features (since hours, days, and months repeat cyclically), the function applies sine and cosine transformations, encoding each of these components in a way that preserves their periodicity.</p><p>Finally, the function removes the original extracted columns (hour, dayofweek, month) after encoding to streamline the dataset, making it ready for machine learning models or statistical analysis that benefit from cyclic feature representation. This transformation is particularly useful in time-series forecasting, where patterns repeat over time.</p><p><strong>Create a Torch dataset to do deep learning model</strong></p><pre>class WeatherDataset(Dataset):<br>    def __init__(self, df):<br>        self.features = df[[<br>            &quot;Humidity_pct&quot;, &quot;Precipitation_mm&quot;, &quot;Wind_Speed_kmh&quot;,<br>            &quot;hour_sin&quot;, &quot;hour_cos&quot;, &quot;day_sin&quot;, &quot;day_cos&quot;, &quot;month_sin&quot;, &quot;month_cos&quot;<br>        ]].values.astype(np.float32)<br>        self.targets = df[&quot;Temperature_C&quot;].values.astype(np.float32)<br><br>    def __len__(self):<br>        return len(self.features)<br><br>    def __getitem__(self, idx):<br>        return torch.tensor(self.features[idx]), torch.tensor(self.targets[idx])<br><br>dataset = WeatherDataset(df)<br>dataloader = DataLoader(dataset, batch_size=2, shuffle=True)</pre><p>This WeatherDataset class is designed as a custom PyTorch dataset for handling weather data. It takes a DataFrame (df) containing various weather features and prepares it for deep learning models. In the initialization method (__init__), the class extracts specific features such as humidity, precipitation, wind speed, and cyclically encoded time components, converting them to 32-bit floating point arrays. The target variable (temperature in Celsius) is similarly extracted and converted. The __len__ method returns the total number of samples in the dataset, allowing PyTorch to iterate efficiently. The __getitem__ method retrieves individual samples, returning both features and target values as PyTorch tensors. Finally, a DataLoader object is created with this dataset, enabling batch-wise data loading with shuffling for randomized training. This setup is ideal for training machine learning models, particularly neural networks that rely on structured and efficiently loaded data.</p><p><strong>Define a PyTorch Model for temperature prediction</strong></p><pre>class SimpleWeatherModel(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.model = nn.Sequential(<br>            nn.Linear(9, 16),<br>            nn.ReLU(),<br>            nn.Linear(16, 8),<br>            nn.ReLU(),<br>            nn.Linear(8, 1)<br>        )<br><br>    def forward(self, x):<br>        return self.model(x)</pre><p>This SimpleWeatherModel class defines a basic neural network using PyTorch&#39;s nn.Module. It consists of three fully connected (Linear) layers, progressively reducing the number of neurons from 9 (input features) to 16, then 8, and finally 1 (output prediction). Each intermediate layer uses the ReLU activation function to introduce non-linearity, helping the model learn complex relationships within the data. The forward method passes input data through the sequentially defined layers, producing a single output value—likely predicting temperature given the weather features. This structure makes for a lightweight yet effective regression model to learn patterns in weather data.</p><p><strong>Model Creation</strong></p><pre>model = SimpleWeatherModel()<br>loss_fn = nn.MSELoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.01)</pre><p>The loss_fn is defined as Mean Squared Error (MSE), a common loss function for regression tasks that measures the average squared difference between predicted and actual values. The optimizer is Adam, an adaptive optimization algorithm that efficiently updates model parameters to minimize the loss. The learning rate (lr=0.01) controls how quickly the model adjusts its weights during training. Together, these elements prepare the neural network for learning weather patterns by adjusting its weights to improve temperature predictions.</p><p><strong>Model Training</strong></p><pre>for epoch in range(10):<br>    for batch_x, batch_y in dataloader:<br>        pred = model(batch_x).squeeze()<br>        loss = loss_fn(pred, batch_y)<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br>    print(f&quot;Epoch {epoch+1}, Loss: {loss.item():.4f}&quot;)</pre><p>This code runs a training loop for the SimpleWeatherModel using the dataset and dataloader previously defined. It iterates through 10 epochs, where each epoch represents one complete pass over the dataset. Within each epoch, batches of input features (batch_x) and target temperature values (batch_y) are fed into the model to generate predictions. The mean squared error (MSE) loss is calculated between the predictions and actual values. The optimizer.zero_grad() clears any accumulated gradients from previous iterations, loss.backward() computes the gradients, and optimizer.step() updates the model parameters to minimize the loss. Finally, the loss value is printed at the end of each epoch, providing insights into how well the model is learning over time.</p><p><strong>Summary</strong></p><p>Cyclic feature encoding is a technique used to transform time-based variables, such as hour, day, or month, into sine and cosine components to reflect their natural periodicity. This method preserves the continuity of cyclical data (e.g., recognizing that hour 23 and hour 0 are adjacent), which traditional integer encoding fails to capture. When applied to deep learning models in PyTorch, cyclic encoding enhances the model’s ability to learn temporal patterns, leading to improved accuracy and generalization in time series prediction tasks like weather forecasting or energy demand modeling. The approach is simple to implement, model-agnostic, and highly effective for making neural networks more time-aware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0eebef307fc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bilevel Optimization in Deep Learning]]></title>
            <link>https://medium.com/@dhanyahari07/bilevel-optimization-in-deep-learning-7bf591ed00ef?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf591ed00ef</guid>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 15:09:18 GMT</pubDate>
            <atom:updated>2025-06-02T15:09:18.906Z</atom:updated>
            <content:encoded><![CDATA[<p>The article will talk about the introduction and implementation of bilevel optimization in PyTorch</p><h3><strong>Introduction</strong></h3><p><strong>Bilevel optimization</strong> is a type of optimization problem where one optimization task (the <em>outer problem</em>) is constrained by the solution to another (the <em>inner problem</em>). It’s like having a “problem within a problem.” The solution to the outer problem relies on how the inner problem is solved.</p><p>The following is the general form of a bilevel optimization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*_69AR1WoapJOe4431OUgjg.png" /><figcaption>The bilevel function</figcaption></figure><p>𝜃 : outer-level variable (e.g., hyperparameters, architecture)</p><p>𝑤: inner-level variable (e.g., model parameters)</p><p>𝐿 inner : objective minimized during the inner loop (e.g., training loss)</p><p>𝐿 outer : objective for the outer loop (e.g., validation loss)</p><ul><li>The <strong>inner problem</strong> finds the best model parameters w for a given configuration θ.</li><li>The <strong>outer problem</strong> tunes θ so that the trained model generalizes well (e.g., performs best on validation data).</li></ul><h3><strong>Applications of bilevel optimization</strong></h3><p>There are various applications for bilevel optimization, such as hyperparameter tuning, game theory, security, etc. The following are a few applications.</p><p>Hyperparameter Optimization (HPO)</p><ul><li><strong>Inner problem</strong>: Train the model with a set of hyperparameters.</li><li><strong>Outer problem</strong>: Choose hyperparameters that minimize the validation loss.</li></ul><p>Meta-Learning / Learning-to-Learn</p><ul><li><strong>Inner problem</strong>: Adapt model parameters to a specific task.</li><li><strong>Outer problem</strong>: Learn initial parameters or a learning strategy that generalizes well across tasks.</li></ul><p>Adversarial Learning &amp; Fairness</p><ul><li><strong>Inner problem</strong>: Train a classifier.</li><li><strong>Outer problem</strong>: Train an adversary to enforce fairness or domain invariance.</li></ul><p>Data Poisoning and Robust Learning</p><ul><li><strong>Inner problem</strong>: Train a model on given (possibly poisoned) data.</li><li><strong>Outer problem</strong>: An attacker chooses poisoned data to maximize test error.</li></ul><p>Computer Vision</p><ul><li><strong>Inner problem</strong>: Train a vision model (e.g., for segmentation).</li><li><strong>Outer problem</strong>: Optimize a parameter that controls labeling quality or supervision strength.</li></ul><h3>PyTorch Example</h3><p>The following is a PyTorch example of bilevel optimization for hyperparameter tuning.</p><p>Import packages</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from torch.utils.data import DataLoader, random_split<br>import copy</pre><p>The imports are used for the pytorch deep learning models</p><p><strong>Load MNIST data</strong></p><pre>transform = transforms.ToTensor()<br>dataset = datasets.MNIST(root=&#39;./data&#39;, train=True, transform=transform, download=True)<br>train_data, val_data = random_split(dataset, [50000, 10000])<br>train_loader = DataLoader(train_data, batch_size=64, shuffle=True)<br>val_loader = DataLoader(val_data, batch_size=64)</pre><p>This downloads the <strong>training split</strong> (60,000 images) of the MNIST dataset to ./data directory and applies the ToTensor transform each image and randomly split the data into training(50000) and testing(10000). Then, creates data loaders for both sets with a batch size 64.</p><p><strong>A simple MLP model</strong></p><pre>class MLP(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.fc1 = nn.Linear(28*28, 128)<br>        self.fc2 = nn.Linear(128, 10)<br><br>    def forward(self, x):<br>        x = x.view(-1, 28*28)<br>        x = F.relu(self.fc1(x))<br>        return self.fc2(x)</pre><p>This will create a simple MLP model for 10 class classification with the 28 X 28 images from the dataset.</p><p><strong>Training and Validation Steps</strong></p><pre>def train_model(model, train_loader, lambda_reg, steps=5):<br>    model_copy = copy.deepcopy(model)<br>    optimizer = torch.optim.SGD(model_copy.parameters(), lr=0.1)<br><br>    for i, (x, y) in enumerate(train_loader):<br>        if i &gt;= steps:<br>            break<br>        optimizer.zero_grad()<br>        out = model_copy(x)<br>        loss = F.cross_entropy(out, y)<br>        l2 = sum(torch.norm(p)**2 for p in model_copy.parameters())<br>        total_loss = loss + lambda_reg * l2<br>        total_loss.backward(create_graph=True)<br>        optimizer.step()<br><br>    return model_copy<br><br>def validation_loss(model, val_loader):<br>    model.eval()<br>    total_loss = 0<br>    with torch.no_grad():<br>        for x, y in val_loader:<br>            out = model(x)<br>            loss = F.cross_entropy(out, y)<br>            total_loss += loss.item() * x.size(0)<br>    return total_loss / len(val_loader.dataset)</pre><p>The train_model function creates a copy of the model and updates its parameters using stochastic gradient descent (SGD) while incorporating L2 regularization to prevent overfitting. It runs for a specified number of steps, computing the cross-entropy loss and adjusting weights accordingly. The validation_loss function evaluates the trained model on a validation dataset, computing the average loss without updating the model parameters. It ensures efficient evaluation by disabling gradient tracking (torch.no_grad()). Overall, the implementation provides a basic framework for model training and validation, with room for optimizations such as adaptive training steps and dynamic device selection.</p><p><strong>Bilevel optimization loop</strong></p><pre>device = &quot;cpu&quot;<br><br>model = MLP().to(device)<br>lambda_reg = torch.tensor(0.01, requires_grad=True, device=device)  # hyperparameter<br>outer_optimizer = torch.optim.Adam([lambda_reg], lr=1e-2)<br><br>for epoch in range(20):<br>    model.train()<br><br>    # Inner optimization: train on training set<br>    updated_model = train_model(model, train_loader, lambda_reg, steps=5)<br><br>    # Outer optimization: evaluate on validation set<br>    val_loss = validation_loss(updated_model, val_loader)<br><br>    outer_optimizer.zero_grad()<br>    val_loss_tensor = torch.tensor(val_loss, requires_grad=True, device=device)<br>    val_loss_tensor.backward()<br>    outer_optimizer.step()<br><br>    print(f&quot;Epoch {epoch}: Val Loss = {val_loss:.4f}, Lambda = {lambda_reg.item():.4f}&quot;)</pre><p>This code implements a <strong>bi-level optimization</strong> framework where an inner loop trains a neural network model (MLP) using a regularized loss function, and an outer loop optimizes the regularization strength (lambda_reg). The model is trained iteratively for 20 epochs, with train_model updating its parameters for a few steps while incorporating L2 regularization. After each inner optimization, the validation loss is computed and lambda_reg is adjusted using Adam optimization based on its impact on validation performance. The validation loss and the dynamically updated lambda_reg value are printed at each epoch. This approach allows the model to not only learn its parameters but also refine the regularization strength to achieve better generalization.</p><h3>Conclusion</h3><p>This implementation of <strong>bi-level optimization</strong> demonstrates a sophisticated approach to refining both model parameters and the regularization strength (lambda_reg). By iterating through inner and outer loops, the model not only learns to classify effectively but also adapts its regularization dynamically to improve generalization. The inner loop ensures the model is trained with L2 regularization, while the outer loop optimizes lambda_reg based on its effect on validation loss. This approach balances <strong>learning stability</strong> and <strong>adaptive regularization</strong>, making it particularly useful when tuning hyperparameters automatically. Bi-level optimization techniques are powerful for meta-learning, hyperparameter tuning, and optimizing models for robustness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf591ed00ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of various regression models — From simple Linear Regression to CatBoost]]></title>
            <link>https://medium.com/@dhanyahari07/comparison-of-various-regression-models-from-simple-linear-regression-to-catboost-dbfb3435ee76?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbfb3435ee76</guid>
            <category><![CDATA[decision-tree-regressor]]></category>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 11:23:57 GMT</pubDate>
            <atom:updated>2024-04-13T11:23:57.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparison of various regression models — From simple Linear Regression to CatBoost</h3><p>This article compares various regression models on a dataset.</p><p>This article compares a few regression algorithms. The dataset is the crop_yield dataset, which can be downloaded from the below link.</p><p><a href="https://www.kaggle.com/datasets/akshatgupta7/crop-yield-in-indian-states-dataset">Agricultural Crop Yield in Indian States Dataset</a></p><p>The models which we are going to compare are</p><ul><li>Linear Regression</li><li>Decision Tree Regressor</li><li>Random Forest Regressor</li><li>Gradient Boosting Regressor</li><li>XG Boost Regressor</li><li>Bagging Regressor</li><li>K Nearest Neighbor Regressor</li><li>CatBoost Regressor</li></ul><p>Step — 1 — Import DataSet</p><pre>import pandas as pd<br>df=pd.read_csv(&#39;crop_yield.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*1IE0JzY6IR5UWKLzuNTqTA.png" /><figcaption>The sample dataset</figcaption></figure><p>From the dataset we are going to predict the Yiel from other fields.</p><p>Step — 2 — Split the data into dependent and independent variables</p><pre>X,y=df.drop(labels=&#39;Yield&#39;,axis=1),df[&#39;Yield&#39;]</pre><p>Step — 3 — Convert categorical variables</p><pre>X=pd.get_dummies(X)</pre><p>The pd.get_dummies(X) function in pandas is used to convert categorical variables in a DataFrame into dummy variables. Categorical variables are those that contain discrete labels or text values, such as crop, state, and season in our dataset. After this conversion, the dataset will look like the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QsMCqJrrdEDvtzTzB04KA.png" /><figcaption>dataset after conversion</figcaption></figure><p>Step — 4 — Splitting the data into training and testing</p><pre>from sklearn.model_selection import train_test_split<br>x_train,x_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=1)</pre><p>LINEAR REGRESSION MODEL</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score<br>lr=LinearRegression()<br>lr_model=lr.fit(x_train,y_train)<br>y_pred=lr.predict(x_test)<br>accuracy=lr_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(lr_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of LR model train is {acc_train:.2f}&#39;)<br><br>acc_test=(lr_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of LR model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*c29nD5R8SH-4snfiyIPMlg.png" /><figcaption>Result of Linear Regression</figcaption></figure><ol><li>from sklearn.linear_model import LinearRegression: This line imports the LinearRegression class from the scikit-learn library. This class is used to create and fit a linear regression model.</li><li>from sklearn.metrics import mean_squared_error, r2_score: This line imports two functions from the scikit-learn metrics module: mean_squared_error and r2_score. These functions are used to evaluate the performance of a regression model.</li><li>lr = LinearRegression(): This line creates an instance of the LinearRegression class, which represents the linear regression model.</li><li>lr_model = lr.fit(x_train, y_train): This line fits the linear regression model to the training data. Here, x_train is the training data features, and y_train is the target variable (what you&#39;re trying to predict) for the training data. The fit method trains the model by learning the coefficients of the linear equation that best fits the data.</li><li>y_pred = lr.predict(x_test): This line uses the fitted model (lr_model) to make predictions on the test data (x_test). The predict method takes the features of the test data as input and returns the predicted target values.</li><li>accuracy = lr_model.score(x_test, y_test): This line calculates the R-squared value, which is a measure of how well the model fits the test data. It represents the proportion of variance in the dependent variable that&#39;s explained by the independent variables. Here, a higher R-squared value indicates a better fit.</li><li>MSE = mean_squared_error(y_test, y_pred): This line calculates the mean squared error (MSE) between the predicted values (y_pred) and the actual target values (y_test) on the test data. MSE is another way to measure the quality of the model&#39;s predictions. A lower MSE value indicates a better fit.</li><li>R2_score = r2_score(y_test, y_pred): This line calculates the R-squared score using the r2_score function from sklearn.metrics. It gives the same result as lr_model.score(x_test, y_test).</li><li>acc_train = (lr_model.score(x_train, y_train) * 100): This line calculates the R-squared value (accuracy) of the model on the training data and multiplies it by 100 to express it as a percentage.</li><li>print(f&#39;Accuracy of LR model train is {acc_train:.2f}&#39;): This line prints a message that shows the training accuracy of the linear regression model, formatted to display two decimal places.</li></ol><p>DECISION TREE REGRESSOR</p><pre>from sklearn.tree import DecisionTreeRegressor<br>dt=DecisionTreeRegressor(random_state=1)<br>dt_model=dt.fit(x_train,y_train)<br>y_pred=dt.predict(x_test)<br>accuracy=dt_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(dt_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of Decision Tree model train is {acc_train:.2f}&#39;)<br><br>acc_test=(dt_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of Decision Tree model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*o-FnDzm1LYtLgLFrAMCEmg.png" /><figcaption>Result of Decision Tree Regressor</figcaption></figure><ol><li>from sklearn.tree import DecisionTreeRegressor: This line imports the DecisionTreeRegressor class from the tree submodule of the scikit-learn library. This class is used to create and fit a decision tree model for regression tasks.</li><li>dt = DecisionTreeRegressor(random_state=1): This line creates an instance of the DecisionTreeRegressor class and stores it in the variable dt. The random_state parameter is set to 1 here. This is a seed for the random number generator used by the decision tree algorithm. Setting a seed ensures that the model produces the same results each time you fit it with the same data, which helps with reproducibility.</li></ol><p>RANDOM FOREST REGRESSOR</p><pre>from sklearn.ensemble import RandomForestRegressor<br>rf=RandomForestRegressor(random_state=1)<br>rf_model=rf.fit(x_train,y_train)<br>y_pred=rf.predict(x_test)<br>accuracy=rf_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(rf_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of Random Forest model train is {acc_train:.2f}&#39;)<br><br>acc_test=(rf_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of Random Forest model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*eTAVtcNRJ6Qm6SUzxRH5ow.png" /><figcaption>Result of Random Forest Regressor</figcaption></figure><ol><li>from sklearn.ensemble import RandomForestRegressor: This line imports the RandomForestRegressor class from the ensemble submodule of the scikit-learn library. This class is used to create and fit a random forest model, which is an ensemble learning technique for regression tasks.</li><li>rf = RandomForestRegressor(random_state=1): This line creates an instance of the RandomForestRegressor class and stores it in the variable rf. The random_state parameter is set to 1 here. This is a seed for the random number generator used by the random forest algorithm. Setting a seed ensures that the model produces the same results each time you fit it with the same data, which helps with reproducibility.</li></ol><p>GRADIENT BOOST REGRESSOR</p><pre>from sklearn.ensemble import GradientBoostingRegressor<br>gb=GradientBoostingRegressor(n_estimators=100,learning_rate=0.1,max_depth=3,random_state=1)<br>gb_model=gb.fit(x_train,y_train)<br>y_pred=gb.predict(x_test)<br>accuracy=gb_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(gb_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of gradient Boosting model train is {acc_train:.2f}&#39;)<br><br>acc_test=(gb_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of gradient Boosting model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*hKyfj408eTOWnrMxNw2drg.png" /><figcaption>Result of Gradient Boosting Model</figcaption></figure><ul><li>gb = GradientBoostingRegressor(...): This line creates an instance of the GradientBoostingRegressor class and stores it in the variable gb.</li><li>n_estimators=100: This parameter specifies the number of boosting stages to be performed. Each stage adds a new decision tree to the model. Here, 100 trees will be used.</li><li>learning_rate=0.1: This parameter controls the contribution of each new tree to the overall model. A lower learning rate (like 0.1 here) helps prevent overfitting but may require more boosting stages (trees) for good performance.</li><li>max_depth=3: This parameter specifies the maximum depth of each decision tree used in the boosting process. A value of 3 limits the trees to a maximum of 3 splits, reducing complexity.</li><li>random_state=1: This parameter sets the seed for the random number generator used by the algorithm. Setting a seed ensures reproducibility of the model.</li></ul><p>XG BOOST REGRESSOR</p><pre>from xgboost import XGBRegressor<br>xgb=XGBRegressor(random_state=1)<br>xgb_model=xgb.fit(x_train,y_train)<br>y_pred=xgb.predict(x_test)<br>accuracy=xgb_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(xgb_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of XG Boosting model train is {acc_train:.2f}&#39;)<br><br>acc_test=(xgb_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of XG Boosting model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*D-NC2Oz29duLJlQIEyioZA.png" /><figcaption>Result of XG Boost Regressor</figcaption></figure><ul><li>xgb = XGBRegressor(random_state=1): This line creates an instance of the XGBRegressor class and stores it in the variable xgb. The random_state parameter is set to 1 here. This sets a seed for the random number generator used by the algorithm, ensuring reproducibility of the model&#39;s results when you fit it with the same data multiple times.</li></ul><p>BAGGING REGRESSOR</p><pre>from sklearn.ensemble import BaggingRegressor<br>br=BaggingRegressor(n_estimators=100,random_state=1)<br>br_model=br.fit(x_train,y_train)<br>y_pred=br.predict(x_test)<br>accuracy=br_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(br_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of Bagging Regressor model train is {acc_train:.2f}&#39;)<br><br>acc_test=(br_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of Bagging Regressor model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*8e3H1HZtLD5P_tJKkzIgvQ.png" /><figcaption>Result of Bagging Regressor</figcaption></figure><ul><li>br = BaggingRegressor(...): This line creates an instance of the BaggingRegressor class and stores it in the variable br.</li><li>n_estimators=100: This parameter specifies the number of base models (often decision trees) to be included in the ensemble. Here, 100 trees will be used.</li><li>random_state=1: This parameter sets the seed for the random number generator used by the algorithm. Setting a seed ensures reproducibility of the model&#39;s results when you fit it with the same data multiple times.</li></ul><p>K — NEAREST NEIGHBOR REGRESSOR</p><pre>from sklearn.neighbors import KNeighborsRegressor<br>knn=KNeighborsRegressor(n_neighbors=10)<br>knn_model=knn.fit(x_train,y_train)<br>y_pred=knn.predict(x_test)<br>accuracy=knn_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(knn_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of K-Neighbor Regressor model train is {acc_train:.2f}&#39;)<br><br>acc_test=(knn_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of  K-Neighbor Regressor model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*vRJrLM2UW64QEBUaUDGYFA.png" /><figcaption>Result of K-Nearest Neighbor Regressor</figcaption></figure><ul><li>knn = KNeighborsRegressor(...): This line creates an instance of the KNeighborsRegressor class and stores it in the variable knn.</li><li>n_neighbors=10: This parameter specifies the number of nearest neighbors to consider when making a prediction. Here, the model will use the 10 closest data points in the training set to predict the target variable for a new data point.</li></ul><p>CATBOOST REGRESSOR</p><pre>from catboost import CatBoostRegressor<br>cat=CatBoostRegressor()<br>cat_model=cat.fit(x_train,y_train)<br>y_pred=cat.predict(x_test)<br>accuracy=cat_model.score(x_test,y_test)<br>MSE=mean_squared_error(y_test,y_pred)<br>R2_score=r2_score(y_test,y_pred)<br><br>acc_train=(cat_model.score(x_train,y_train)*100)<br>print(f&#39;Accuracy of Catboost Regressor model train is {acc_train:.2f}&#39;)<br><br>acc_test=(cat_model.score(x_test,y_test)*100)<br>print(f&#39;Accuracy of  Catboost Regressor model train is {acc_test:.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*0fxIFFCbHcWZxl0HNnRM_g.png" /><figcaption>Result of Catboost Regressor</figcaption></figure><p>This line creates an instance of the CatBoostRegressor class and stores it in the variable cat. By default, this creates a CatBoost regression model with the following characteristics:</p><ul><li><strong>Automatic Feature Handling:</strong> CatBoost can automatically handle both numerical and categorical features without any special preprocessing steps like one-hot encoding.</li><li><strong>Ordered Encoding:</strong> It uses a technique called ordered encoding for categorical features, which considers target variable statistics to improve predictions.</li><li><strong>Other Default Parameters:</strong> The model uses various other default parameters for learning rate, number of trees, and other hyperparameters that can be further tuned for optimal performance.</li></ul><p>COMBINING ALL TOGETHER</p><p>List all the methods in an array</p><pre>results=[]<br><br>models=[<br>    (&#39;Linear Regression&#39;,LinearRegression()),<br>    (&#39;Decision Tree&#39;,DecisionTreeRegressor(random_state=1)),<br>    (&#39;Random Forest&#39;,RandomForestRegressor(random_state=1)),<br>    (&#39;Gradient Boost&#39;,GradientBoostingRegressor(n_estimators=100,learning_rate=0.1,max_depth=3,random_state=1)),<br>    (&#39;XGBoost&#39;,XGBRegressor(random_state=1)),<br>    (&#39;Bagging Regressor&#39;,BaggingRegressor(n_estimators=100,random_state=1)),<br>    (&#39;KNN&#39;,KNeighborsRegressor(n_neighbors=100)),<br>    (&#39;CatBoost&#39;,CatBoostRegressor())<br>]</pre><p>Run all the models in a loop with test scores added in a list called results.</p><pre>for name, model in models :<br>  model.fit(x_train,y_train)<br>  y_pred=model.predict(x_test)<br>  accuracy=model.score(x_test,y_test)<br>  MSE=mean_squared_error(y_test,y_pred)<br>  R2_score=r2_score(y_test,y_pred)<br>  results.append((name,accuracy,MSE,R2_score))<br><br>  acc_train=(model.score(x_train,y_train)*100)<br>  print(f&#39;Accuracy of {name} model train is {acc_train:.2f}&#39;)<br><br>  acc_test=(model.score(x_test,y_test)*100)<br>  print(f&#39;Accuracy of  {name} model train is {acc_test:.2f}&#39;)</pre><p>Display the model results will highlight the best and worst models in terms of accuracy and R2 score.</p><pre>results_df=pd.DataFrame(results,columns=[&#39;Model&#39;,&#39;Accuracy&#39;,&#39;MSE&#39;,&#39;R2_score&#39;])<br>results_format_df=results_df.style.highlight_max(subset=[&#39;Accuracy&#39;,&#39;R2_score&#39;],color=&#39;green&#39;).highlight_min(subset=[&#39;Accuracy&#39;,&#39;R2_score&#39;],color=&#39;red&#39;)<br>display(results_format_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*wHBw3dNtTy2FbDxYZ8kAPQ.png" /><figcaption>All the model results — A comparison</figcaption></figure><p>CONCLUSION</p><p>In this article, we compared a few regression algorithms and their results. The gradient boost regressor was performing well and in general boosting algorithms like gradient boosting, XG boost, and Catboost outperform other algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbfb3435ee76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Imbalanced Dataset-Oversampling,Undersampling and SMOTE]]></title>
            <link>https://medium.com/@dhanyahari07/dealing-with-imbalanced-dataset-bf5c217e14b7?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf5c217e14b7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[smote]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[oversampling]]></category>
            <category><![CDATA[undersampling]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 08:24:21 GMT</pubDate>
            <atom:updated>2024-04-07T08:32:40.151Z</atom:updated>
            <content:encoded><![CDATA[<p>This article talks about how to deal with an imbalanced dataset with an example of a classification dataset.</p><p>Imbalanced datasets pose several challenges in machine learning, particularly for classification tasks. Here’s a breakdown of the main problems:</p><p><strong>Misleading Accuracy:</strong></p><ul><li>Traditional accuracy metric, which simply measures the portion of correctly classified instances, is skewed towards the majority class.</li><li>A model might achieve high accuracy by simply predicting the majority class all the time, even if it completely misses the minority class.</li></ul><p><strong>Difficulty Learning Minority Class:</strong></p><ul><li>With far fewer examples, models struggle to learn the intricacies of the minority class.</li><li>Features that differentiate the minority class from the majority class might be overlooked.</li></ul><p><strong>Challenges in Evaluation:</strong></p><ul><li>Standard evaluation metrics like accuracy become unreliable due to the class imbalance.</li><li>Different metrics are needed to assess a model’s ability to identify the minority class effectively.</li></ul><p><strong>Overall Poor Model Performance:</strong></p><ul><li>These factors combined lead to models that prioritize the majority class and perform poorly on the minority class, which can be critical in real-world applications.</li></ul><p>For instance, imagine a fraud detection system trained on imbalanced data with very few fraudulent transactions. The model might appear accurate because it correctly classifies most transactions as legitimate (the majority class). However, it might miss crucial patterns in fraudulent transactions due to their rarity.</p><p>Undersampling, Oversampling, and SMOTE (Synthetic Minority Oversampling Technique), are techniques used to address class imbalance in machine learning datasets.</p><p><strong>1. Undersampling:</strong></p><ul><li>This approach focuses on reducing the size of the majority class.</li><li>Random undersampling involves randomly removing examples from the majority class to match the size of the minority class.</li><li>This is a simple and fast technique, but it discards potentially valuable data from the majority class.</li></ul><p><strong>2. Oversampling:</strong></p><ul><li>This approach increases the size of the minority class.</li><li>Random oversampling involves simply duplicating existing minority class examples.</li><li>This is a straightforward method, but it can lead to overfitting as the model memorizes the duplicated examples.</li></ul><p><strong>3. SMOTE (Synthetic Minority Oversampling Technique):</strong></p><ul><li>This is a more advanced oversampling technique that creates synthetic minority class examples.</li><li>SMOTE identifies a minority class example and its nearest neighbors (other minority class examples close in feature space).</li><li>It then creates a new synthetic example along the line segment between the original example and one of its neighbors.</li><li>This approach helps to increase the diversity of the minority class data without simply copying existing examples.</li></ul><p><strong>Choosing the Right Technique:</strong></p><p>There’s no one-size-fits-all solution, and the best technique depends on the specific dataset and machine learning model. Here are some general considerations:</p><ul><li><strong>Undersampling</strong> might be suitable if the majority class data is noisy or if you have limited computational resources.</li><li><strong>Oversampling</strong> can be effective if you have enough data and want to avoid discarding potentially valuable information.</li><li><strong>SMOTE</strong> is a good option when you want to create more diverse synthetic minority class examples.</li></ul><p>The following is the code sample.</p><p><strong><em>Import the necessary packages</em></strong></p><pre>from collections import Counter<br>from sklearn.datasets import make_classification<br>from matplotlib import pyplot<br>from numpy import where<br>from imblearn.under_sampling import RandomUnderSampler<br>from imblearn.over_sampling import RandomOverSampler<br>from imblearn.over_sampling import SMOTE</pre><p><strong><em>Define a dummy dataset, which can be replaced by your actual dataset.</em></strong></p><pre>X, y = make_classification(n_samples=10000, n_features=2, n_redundant=0,<br> n_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=1)</pre><p>The code you provided utilizes the make_classification function from scikit-learn to generate a synthetic classification dataset. Let&#39;s break down what each argument does:</p><ul><li><strong>n_samples=10000:</strong> This defines the number of data points (samples) you want in your dataset. Here, it’s set to 10,000.</li><li><strong>n_features=2:</strong> This specifies the number of features (dimensions) each data point will have. In this case, each sample will have two features.</li><li><strong>n_redundant=0:</strong> This parameter controls the number of redundant features. Setting it to 0 ensures there are no redundant features, meaning all features contribute uniquely to the classification task.</li><li><strong>n_clusters_per_class=1:</strong> This defines the number of clusters for each class. Here, it’s set to 1, indicating each class will have a single, tight cluster of data points.</li><li><strong>weights=[0.99]:</strong> This argument controls the class distribution. Here, it’s set to a list containing only 0.99. Since weights are probabilities that sum to 1, this creates a highly imbalanced dataset where one class will have a proportion very close to 1 (almost all samples) and the other class will have a proportion close to 0 (very few samples).</li><li><strong>flip_y=0:</strong> This parameter controls the probability of randomly flipping labels. Setting it to 0 ensures no labels are flipped, resulting in a clean separation between the classes.</li><li><strong>random_state=1:</strong> This sets a seed for the random number generator. Using the same seed will produce the same dataset every time you run the code.</li></ul><p>When you run this code, it will generate a dataset with 10,000 samples, each having 2 features. There will be no redundant features, and each class will be tightly clustered. However, the dataset will be heavily imbalanced, with one class dominating the other (almost all samples belong to one class).</p><p><strong><em>Summarises the class distribution for understanding the dataset</em></strong></p><pre>counter = Counter(y)<br>print(counter)</pre><p>The result will be displayed in the below diagram, the count of the class labeled 0 is 9900, and the count of the class labeled 1 is 100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*0y7XJt0GvYegmJwaMef-Cg.png" /><figcaption>Dataset Summary</figcaption></figure><p><strong><em>The scatterplot of the dataset for further understanding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*mQ1wWkSyP3QR-QMAoCcp4Q.png" /><figcaption>Scatter plot of the original imbalanced dataset</figcaption></figure><p><strong><em>Random Undersampling</em></strong></p><pre># Define the under-sampler<br>rus = RandomUnderSampler(sampling_strategy=&#39;majority&#39;)<br><br># Resample the data<br>X_resampled, y_resampled = rus.fit_resample(X, y)</pre><ol><li><strong>Object Creation:</strong> This line creates an instance of the RandomUnderSampler class from the imbalanced-learn library and assigns it to the variable rus.</li><li><strong>Sampling Strategy:</strong> We specify the sampling_strategy argument as &quot;majority&quot;. This instructs the RandomUnderSampler to focus on reducing the size of the majority class in the dataset.</li><li><strong>Data Resampling:</strong> This line performs the actual random undersampling using the fit_resample method of the rus object.</li><li><strong>Input Data:</strong> The method takes two arguments:</li></ol><ul><li>X: This represents your original feature data (samples and their features).</li><li>y: This represents your original target labels (class labels for each sample).</li></ul><p><strong>5. Output Data:</strong> The fit_resample method returns two variables:</p><ul><li>X_resampled: This contains the resampled feature data after applying random undersampling to the majority class.</li><li>y_resampled: This contains the resampled target labels corresponding to the resampled features in X_resampled.</li></ul><p><strong><em>Summarises the class distribution after under-sampling</em></strong></p><pre>counter = Counter(y_resampled)<br>print(counter)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*h_Y2txkYbFRolhLEAZ6OyQ.png" /><figcaption>dataset summary after under-sampling</figcaption></figure><p>The result shows the count of label 0 is reduced to 100, which was the count of the minority class 1.</p><p><strong><em>The scatterplot of the dataset for further understanding</em></strong></p><pre>for label, _ in counter.items():<br> row_ix = where(y_resampled == label)[0]<br> pyplot.scatter(X_resampled[row_ix, 0], X_resampled[row_ix, 1], label=str(label))<br>pyplot.legend()<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*b-p0Xp9YLvCnlXfojslx7Q.png" /><figcaption>scatter plot for the under-sampled dataset</figcaption></figure><p><strong><em>Random Over-Sampler</em></strong></p><p>The method performs random oversampling on the minority class to achieve a more balanced class distribution. This is done by duplicating existing minority class samples with replacement.</p><pre># Define the under-sampler<br>rus = RandomUnderSampler(sampling_strategy=&#39;majority&#39;)<br><br># Resample the data<br>X_resampled, y_resampled = rus.fit_resample(X, y)</pre><ol><li><strong>Object Creation:</strong> This line creates an instance of the RandomOverSampler class from the imbalanced-learn library and assigns it to the variable ros.</li><li><strong>Sampling Strategy:</strong> We specify the sampling_strategy argument as &quot;minority&quot;. This instructs the RandomOverSampler to focus on increasing the size of the minority class in the dataset.</li><li><strong>Data Resampling:</strong> This line performs the actual random oversampling using the fit_resample method of the ros object.</li><li><strong>Input Data:</strong> The method takes two arguments:</li></ol><ul><li>X: This represents your original feature data (samples and their features).</li><li>y: This represents your original target labels (class labels for each sample).</li></ul><p><strong>5. Output Data:</strong> The fit_resample method returns two variables:</p><ul><li>X_resampled: This contains the resampled feature data after applying random oversampling to the minority class. The number of samples in the minority class will be increased.</li><li>y_resampled: This contains the resampled target labels corresponding to the features in X_resampled.</li></ul><p><strong><em>Summarises the class distribution after over-sampling</em></strong></p><pre>counter = Counter(y_resampled)<br>print(counter)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*bGBITvtIPhQJvY4IbEecvA.png" /><figcaption>dataset summary after over-sampling</figcaption></figure><p>The result shows the count of label 1 increased to 9900, which was the count of the majority class 0.</p><p><strong><em>The scatterplot of the dataset for further understanding</em></strong></p><pre>for label, _ in counter.items():<br> row_ix = where(y_resampled == label)[0]<br> pyplot.scatter(X_resampled[row_ix, 0], X_resampled[row_ix, 1], label=str(label))<br>pyplot.legend()<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*HNRr7m6yQvFpWEsJhHlwpw.png" /><figcaption>scatter plot for over-sampled dataset</figcaption></figure><p>The orange class 1 points are duplicated to make it to the count of 9900. You can observe this from the thick orange dots in the scatter plot.</p><p><strong><em>SMOTE</em></strong></p><ul><li>SMOTE identifies minority class examples.</li><li>For each minority class example, it finds its nearest neighbors (other minority class examples close in feature space).</li><li>It then creates a new synthetic example along the line segment between the original example and one of its neighbors. This creates new data points for the minority class that are similar to existing ones, but not identical copies.</li></ul><pre># Define the SMOTE over-sampler<br>smote = SMOTE(sampling_strategy=&#39;minority&#39;)<br><br># Resample the data<br>X_resampled, y_resampled = smote.fit_resample(X, y)</pre><ol><li><strong>Object Creation:</strong> This line creates an instance of the SMOTE class from the imbalanced-learn library and assigns it to the variable smote.</li><li><strong>Sampling Strategy:</strong> We specify the sampling_strategy argument as &quot;minority&quot;. This instructs SMOTE to focus on oversampling the minority class in the dataset.</li><li><strong>Data Resampling:</strong> This line performs the actual SMOTE oversampling using the fit_resample method of the smote object.</li><li><strong>Input Data:</strong> The method takes two arguments:</li></ol><ul><li>X: This represents your original feature data (samples and their features).</li><li>y: This represents your original target labels (class labels for each sample).</li></ul><p><strong>5. Output Data:</strong> The fit_resample method returns two variables:</p><ul><li>X_resampled: This contains the resampled feature data after applying SMOTE to the minority class. New synthetic minority class examples will be added.</li><li>y_resampled: This contains the resampled target labels corresponding to the features in X_resampled.</li></ul><p><strong><em>Summarises the class distribution after SMOTE</em></strong></p><pre>counter = Counter(y_resampled)<br>print(counter)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*fL8JN0OhRxQGuJ9IkLJWlA.png" /><figcaption>dataset summary after SMOTE</figcaption></figure><p><strong><em>The scatterplot of the dataset for further understanding</em></strong></p><pre>for label, _ in counter.items():<br> row_ix = where(y_resampled == label)[0]<br> pyplot.scatter(X_resampled[row_ix, 0], X_resampled[row_ix, 1], label=str(label))<br>pyplot.legend()<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*f7jQ0Gc_tyioVgqTwxHawQ.png" /><figcaption>Scatter plot for SMOTE dataset</figcaption></figure><h3><strong>Summary.</strong></h3><p>imbalanced-learn provides a comprehensive toolbox for handling imbalanced datasets in machine learning.</p><p><strong>Undersampling Techniques:</strong></p><ul><li><strong>RandomUnderSampler:</strong> This is a straightforward approach that randomly removes examples from the majority class to match the size of the minority class. It’s fast and easy to implement, but can discard potentially valuable data.</li></ul><p><strong>Oversampling Techniques:</strong></p><ul><li><strong>RandomOverSampler:</strong> This technique randomly duplicates existing minority class examples to increase their representation. It’s simple to implement, but can lead to overfitting as the model memorizes the duplicated examples.</li><li><strong>SMOTE (Synthetic Minority Oversampling Technique):</strong> SMOTE creates synthetic minority class examples by identifying a minority class instance and its nearest neighbors. It then generates a new data point along the line segment between them. This approach helps create more diverse data for the minority class compared to simple duplication.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf5c217e14b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Shot Learning for text classification]]></title>
            <link>https://medium.com/@dhanyahari07/zero-shot-learning-for-text-classification-d4acb1c89810?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4acb1c89810</guid>
            <category><![CDATA[zero-shot-learning]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 08:15:58 GMT</pubDate>
            <atom:updated>2024-02-01T08:15:58.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*vqhtTFi8Ctj8ysGmYFO_uQ.png" /><figcaption>image source — <a href="https://amitness.com/2020/05/zero-shot-text-classification/">https://amitness.com/2020/05/zero-shot-text-classification/</a></figcaption></figure><p>In this article we will learn about how to do zero shot learning for classifying a text.</p><h3><strong>Introduction</strong></h3><p>Zero-shot learning (ZSL) and learning with less training data are both areas of machine learning that aim to overcome the limitations of traditional approaches that require vast amounts of labeled data. In this sense, they have significant overlap and can be combined synergistically to make the most of limited resources.</p><p>Here’s how ZSL can be particularly helpful when you have less training data:</p><ul><li>Reduces reliance on large labeled datasets: Instead of needing extensive data for each class, ZSL leverages additional information like descriptions, attributes, or relationships between classes. This allows you to classify unseen classes even with limited labeled data for seen classes.</li><li>Improves performance with few-shot learning: Some ZSL approaches like few-shot learning are specifically designed to learn from just a few examples per class. This aligns well with scenarios where acquiring large datasets is difficult or expensive.</li><li>Leverages pre-trained models: Many ZSL methods utilize pre-trained models on large datasets, transferring knowledge to unseen classes even with scarce specific data.</li></ul><h3><strong>Zero Shot Learning using Keras</strong></h3><p>This section will explain the steps involved in the zero shot learning</p><p>Step — 1 Import the packages</p><pre>import numpy as np<br>from keras.models import Sequential<br>from keras.layers import Embedding, Flatten, Dense<br>from keras.preprocessing.text import Tokenizer<br>from keras.preprocessing.sequence import pad_sequences</pre><p>Step — 2 Example texts and their corresponding labels</p><pre>texts = [<br>    &quot;This is a positive review.&quot;,<br>    &quot;Negative sentiment detected in this text.&quot;,<br>    &quot;The product is excellent.&quot;,<br>    &quot;I don&#39;t recommend this at all.&quot;<br>]<br><br>labels = [<br>    &quot;Positive&quot;,<br>    &quot;Negative&quot;,<br>    &quot;Positive&quot;,<br>    &quot;Negative&quot;<br>]<br><br>label_values=[1,0,1,0]</pre><p>Step — 3 Tokenizing the text and converting to sequences</p><p>I’m ready to break down that code snippet step by step:</p><p>1. tokenizer = Tokenizer():</p><ul><li>This line initializes a new Tokenizer object from a suitable library (often Keras or TensorFlow).</li><li>The Tokenizer&#39;s primary role is to convert text data into numerical representations that machine learning models can understand.</li></ul><p>2. tokenizer.fit_on_texts(texts):</p><ul><li>This line builds the tokenizer’s vocabulary based on the provided texts data.</li><li>It analyzes the text corpus to:</li></ul><blockquote>Identify unique words or characters (depending on configuration).</blockquote><blockquote>Assign each unique token a unique numerical ID.</blockquote><blockquote>This vocabulary mapping is essential for numerical encoding.</blockquote><p>3. sequences = tokenizer.texts_to_sequences(texts):</p><ul><li>This line converts the texts data into sequences of numerical IDs using the learned vocabulary.</li><li>Each text element is transformed into a list of integers, where each integer represents the ID of a corresponding word or character in the vocabulary.</li><li>This process is crucial for preparing text data for input into machine learning models, as they can’t process raw text directly.</li></ul><pre>tokenizer = Tokenizer()<br>tokenizer.fit_on_texts(texts)<br>sequences = tokenizer.texts_to_sequences(texts)</pre><p>Step — 4 Padding sequences for a consistent input shape</p><p>1. max_len = max(len(seq) for seq in sequences):</p><ul><li>This line determines the maximum length among all sequences in the sequences list.</li><li>It calculates this by:</li></ul><blockquote>Iterating through each sequence in sequences.</blockquote><blockquote>Measuring the length of each sequence using len(seq).</blockquote><blockquote>Finding the maximum length using the max function.</blockquote><ul><li>This value is crucial for aligning sequences to a uniform length, ensuring compatibility with machine learning models that expect fixed-size inputs.</li></ul><p>2. padded_sequences = pad_sequences(sequences, maxlen=max_len, padding=&#39;post&#39;):</p><ul><li>This line performs padding on the sequences to ensure they all have the same length, max_len.</li><li>It utilizes the pad_sequences function, commonly found in libraries like Keras or TensorFlow.</li><li>Here’s how it works:</li></ul><blockquote>maxlen=max_len: Specifies the desired maximum length for all sequences.</blockquote><blockquote>padding=&#39;post&#39;: Indicates that padding will be added to the end of each sequence (appended).</blockquote><blockquote>Padding is typically done with zeros, but other values can be used depending on the context.</blockquote><pre>max_len = max(len(seq) for seq in sequences)<br>padded_sequences = pad_sequences(sequences, maxlen=max_len, padding=&#39;post&#39;)</pre><p>Step — 4 Creating word embeddings using GloVe</p><p>1. embedding_dim = 50:</p><ul><li>This line sets the desired dimensionality for word embeddings.</li><li>Think of embedding dimensions as representing the “semantic space” in which words are positioned.</li><li>Here, it’s set to 50, meaning each word will be represented by a 50-dimensional vector.</li><li>It’s common to adjust this value based on the specific pre-trained embeddings you’re using (GloVe in this case).</li></ul><p>2. embedding_matrix = np.zeros((len(tokenizer.word_index) + 1, embedding_dim)):</p><ul><li>This line creates a placeholder matrix to store the word embeddings for your vocabulary.</li><li>It’s initialized with zeros using NumPy’s np.zeros function.</li><li>Here’s the structure:</li></ul><blockquote>Number of rows: Equivalent to the number of words in your vocabulary (len(tokenizer.word_index) + 1), with an extra row for out-of-vocabulary (OOV) tokens.</blockquote><blockquote>Number of columns: Equals the embedding dimension (embedding_dim, set to 50 in this case).</blockquote><ul><li>This matrix will be populated with pre-trained embeddings in subsequent steps.</li></ul><pre>embedding_dim = 50  # Adjust based on your GloVe embedding dimension<br>embedding_matrix = np.zeros((len(tokenizer.word_index) + 1, embedding_dim))</pre><p>Step — 5 Load GloVe embeddings</p><p>The GloVe file can be downloaded from here</p><p><a href="https://www.kaggle.com/datasets/watts2/glove6b50dtxt">glove.6B.50d.txt</a></p><p>1. glove_file_path = &#39;glove.6B.50d.txt&#39;:</p><ul><li>This line specifies the location of the pre-trained GloVe word embeddings file.</li><li>It’s crucial to ensure you have the correct path to the file on your system.</li></ul><p>2. with open(glove_file_path, encoding=&#39;utf-8&#39;) as file::</p><ul><li>This line opens the GloVe file for reading, using appropriate encoding (UTF-8) to handle text data.</li><li>The with statement ensures proper file closure even if errors occur.</li></ul><p>3. for line in file::</p><ul><li>This line initiates a loop that iterates over each line in the GloVe file.</li></ul><p>4. values = line.split():</p><ul><li>This line splits each line into a list of values, typically containing:</li><li>The word at index 0.</li><li>Its corresponding embedding vector as numerical values in the remaining indices.</li></ul><p>5. word = values[0]:</p><ul><li>This line extracts the word from the first index of the values list.</li></ul><p>6. if word in tokenizer.word_index::</p><ul><li>This conditional statement checks if the current word is present in the vocabulary created by the tokenizer.</li></ul><p>7. embedding_matrix[tokenizer.word_index[word]] = np.array(values[1:], dtype=&#39;float32&#39;):</p><ul><li>If the word is in the vocabulary:</li><li>This line retrieves its corresponding index in the tokenizer’s word_index dictionary.</li><li>It then assigns the embedding vector (as a NumPy array) to the appropriate row in the embedding matrix.</li></ul><pre>glove_file_path = &#39;glove.6B.50d.txt&#39;  # Provide the path to your GloVe file<br>with open(glove_file_path, encoding=&#39;utf-8&#39;) as file:<br>    for line in file:<br>        values = line.split()<br>        word = values[0]<br>        if word in tokenizer.word_index:<br>            embedding_matrix[tokenizer.word_index[word]] = np.array(values[1:], dtype=&#39;float32&#39;)</pre><p>Step — 6 Define the model</p><p>1. model = Sequential():</p><ul><li>This line initializes a sequential model architecture using Keras, a common framework for building neural networks.</li><li>Sequential models stack layers linearly, creating a straightforward model flow.</li></ul><p>2. model.add(Embedding(...)):</p><ul><li>This line adds the first layer, an Embedding layer, responsible for representing words as dense vectors.</li><li>Key arguments for this layer:</li></ul><blockquote>input_dim: Matches the size of the vocabulary (len(tokenizer.word_index) + 1).</blockquote><blockquote>output_dim: Sets the desired embedding dimension (embedding_dim, likely 50 based on previous code).</blockquote><blockquote>weights: Specifies the pre-trained embedding matrix (embedding_matrix) to leverage external knowledge.</blockquote><blockquote>input_length: Determines the maximum length of input sequences (max_len) for padding consistency.</blockquote><blockquote>trainable=False: Prevents the embedding weights from being updated during training, preserving pre-trained knowledge.</blockquote><p>3. model.add(Flatten()):</p><ul><li>This line adds a Flatten layer, which reshapes the 3D output of the Embedding layer (samples, sequence length, embedding dimension) into a 2D array (samples, flattened embeddings).</li><li>This flattening is often necessary before feeding data into dense layers.</li></ul><p>4. model.add(Dense(1, activation=&#39;sigmoid&#39;)):</p><ul><li>This line adds the final layer, a dense layer with 1 unit and a sigmoid activation function.</li><li>This structure suggests a binary classification task, where the model outputs a probability between 0 and 1 representing the likelihood of belonging to one class.</li></ul><pre>model = Sequential()<br>model.add(Embedding(input_dim=len(tokenizer.word_index) + 1,<br>                    output_dim=embedding_dim,<br>                    weights=[embedding_matrix],<br>                    input_length=max_len,<br>                    trainable=False))  <br>model.add(Flatten())<br>model.add(Dense(1, activation=&#39;sigmoid&#39;))  </pre><p>Step — 7 Compile and train the model</p><p>1. model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;]):</p><ul><li>This line configures the model’s training process by specifying essential elements:</li></ul><blockquote>Optimizer: &#39;adam&#39; is a popular optimization algorithm that efficiently updates model weights during training.</blockquote><blockquote>Loss Function: &#39;binary_crossentropy&#39; is a suitable loss function for binary classification tasks, measuring how well the model&#39;s predictions align with the true labels.</blockquote><blockquote>Metrics: metrics=[&#39;accuracy&#39;] indicates that model performance will be evaluated using accuracy, a common metric for classification.</blockquote><p>2. model.fit(padded_sequences, np.array(label_values), epochs=50, batch_size=1, verbose=1):</p><ul><li>This line initiates the model’s training process, using the following arguments:</li></ul><blockquote>Training Data: padded_sequences provides the model with prepared text sequences as input.</blockquote><blockquote>Target Labels: np.array(label_values) supplies the corresponding true labels for each text sequence.</blockquote><blockquote>Epochs: epochs=50 determines the number of times the model will process the entire dataset during training.</blockquote><blockquote>Batch Size: batch_size=1 specifies that one text sequence will be processed at a time (adjust based on memory constraints and model complexity).</blockquote><blockquote>Verbosity: verbose=1</blockquote><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br>model.fit(padded_sequences,np.array(label_values), epochs=50, batch_size=1, verbose=1)</pre><p>Step — 7 Example of zero-shot prediction on a new text</p><p>1. new_text = &quot;I&#39;m really impressed with this product.&quot;:</p><ul><li>This line creates a new text string to be evaluated by the trained model.</li><li>It contains a positive sentiment towards the product.</li><li>The commented-out line below it offers an alternative text with negative sentiment.</li></ul><p>2. new_sequence = tokenizer.texts_to_sequences([new_text]):</p><ul><li>This line converts the new_text into a sequence of numerical IDs using the previously trained tokenizer.</li><li>It’s crucial to use the same tokenizer to ensure consistency with model training.</li><li>The [new_text] syntax creates a list containing a single text element for processing.</li></ul><p>3. new_padded_sequence = pad_sequences(new_sequence, maxlen=max_len, padding=&#39;post&#39;):</p><ul><li>This line pads the new_sequence to match the maximum length (max_len) used during model training.</li><li>Padding ensures compatibility with the model’s input layer.</li><li>padding=&#39;post&#39; specifies that padding will be added to the end of the sequence.</li></ul><pre>new_text = &quot;I&#39;m really impressed with this product.&quot;<br>#new_text = &quot;I hate this product.&quot;<br>new_sequence = tokenizer.texts_to_sequences([new_text])<br>new_padded_sequence = pad_sequences(new_sequence, maxlen=max_len, padding=&#39;post&#39;)</pre><p>Step — 8 Make predictions</p><p>1. prediction = model.predict(new_padded_sequence):</p><ul><li>This line uses the trained model to generate a prediction for the new_padded_sequence.</li><li>The model processes the numerical representation of the text and produces a probability value indicating the likelihood of belonging to each class (positive or negative in this case).</li></ul><p>2. predicted_label = &quot;Positive&quot; if prediction[0][0] &gt; 0.5 else &quot;Negative&quot;:</p><ul><li>This line interprets the prediction and assigns a label based on the probability threshold:</li><li>If the first value (index 0, 0) in the prediction array is greater than 0.5, it’s considered “Positive”.</li><li>Otherwise, it’s considered “Negative”.</li><li>The threshold of 0.5 is common for binary classification tasks.</li></ul><p>3. print(f&quot;The model predicts the label for the new text as: {predicted_label}&quot;):</p><ul><li>This line prints a formatted string that displays the model’s predicted label for the new text.</li></ul><pre>prediction = model.predict(new_padded_sequence)<br>predicted_label = &quot;Positive&quot; if prediction[0][0] &gt; 0.5 else &quot;Negative&quot;<br><br>print(f&quot;The model predicts the label for the new text as: {predicted_label}&quot;)</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*h7uErIoBTFEBfx0md-HByQ.png" /><figcaption>Output of the sample sentence</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4acb1c89810" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Selection using XGBoost]]></title>
            <link>https://medium.com/@dhanyahari07/feature-selection-using-xgboost-f0622fb70c4d?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0622fb70c4d</guid>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 09:33:22 GMT</pubDate>
            <atom:updated>2024-01-31T09:33:22.853Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will give you a detailed explanation of how to do feature selection using XGBoost with a practical example.</p><p>Feature selection is a crucial step in machine learning, especially when dealing with high-dimensional data.The following shows the ways to use XGBoost for feature selection.</p><h3><strong>1. Feature Importance Scores:</strong></h3><ul><li>XGBoost calculates three types of feature importance scores:</li></ul><blockquote>Gain: Average loss reduction gained when using a feature for splitting.</blockquote><blockquote>Cover: The number of times a feature is used to split data across trees weighted by training data points.</blockquote><blockquote>Weight: Total number of times a feature is used to split data across all trees.</blockquote><ul><li>You can access these scores through the booster.get_feature_importance() method after training your XGBoost model.</li><li>These scores indicate the relative importance of features in contributing to the model’s predictions. Higher score signifies greater importance.</li></ul><h3><strong>2. Thresholding Scores:</strong></h3><ul><li>You can choose a threshold for the importance scores and select features exceeding that threshold.</li><li>This can be a simple yet effective way to identify the most impactful features.</li><li>Scikit-learn’s SelectFromModel class can be used to apply this threshold-based selection directly.</li></ul><p>Now we will see how to code this and see the effect of the feature selection</p><p>The dataset is taken from the following link.</p><p><a href="https://www.kaggle.com/datasets/uciml/pima-indians-diabetes-database">Pima Indians Diabetes Database</a></p><p>The data is basically a classification problem, where we have 8 features such as number of pregnancies&#39;, glucose level, Blood pressure, Skin Thickness, etc. and the last column Outcome which is to be classified and is the dependent variable.</p><p>We will do the analysis in two steps. In the first step we will perform normal XGBoost classification and in the second step with feature selected XGBoost classifier and analyze the effect of feature selection.</p><p>We will do the fist part of the analysis now.</p><p>Step — 1 Import necessary packages</p><pre>import pandas as pd<br>from numpy import sort<br>from sklearn.feature_selection import SelectFromModel<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from xgboost import XGBClassifier<br>from sklearn.metrics import accuracy_score, classification_report</pre><p>Step — 2 Load the dataset</p><pre>df = pd.read_csv(&quot;diabetes.csv&quot;)</pre><p>Step — 3 Split the data into dependent and independent variables</p><pre>X = df.drop(&quot;Outcome&quot;, axis=1)<br>y = df[&quot;Outcome&quot;]</pre><p>Step — 4 Split the data into training and testing</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Step — 5 Standard Scalar to scale the data</p><pre>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><p>Step — 6 Define XGBoost Classifier and fit the model</p><pre><br>model = XGBClassifier(n_estimators=100, max_depth=6, learning_rate=0.1)<br><br><br>model.fit(X_train_scaled, y_train)</pre><p>Step — 7 Calculate the accuracy of the model</p><pre>y_pred = model.predict(X_test_scaled)<br>accuracy = accuracy_score(y_test, y_pred)<br><br>print(f&quot;Accuracy: {accuracy:.4f}&quot;)<br></pre><p>The accuracy of the model with this settings is <strong>74.02%.</strong></p><p>Now we will do the second part of analysis, where we will do feature importance using XGBoost and do the classification.</p><p>Step — 8 Sort the feature importance</p><p>That’s the first step in using individual feature importances as thresholds for feature selection with XGBoost! Sorting the model.feature_importances_ array ensures you iterate through them in descending order of importance.</p><pre>thresholds = sort(model.feature_importances_)</pre><p>The next step is, for each feature combination run the model and find the accuracy.</p><ol><li>Looping through thresholds:</li></ol><ul><li>for thresh in thresholds: iterates through each sorted feature importance value, using it as a threshold for feature selection.</li></ul><p>2. Feature selection:</p><ul><li>selection = SelectFromModel(model, threshold=thresh, prefit=True) creates a feature selector based on the pre-trained model and the current threshold.</li><li>select_X_train = selection.transform(X_train_scaled) applies the selector to the training data, keeping only features with importance above the threshold.</li></ul><p>3. Model training:</p><ul><li>selection_model = XGBClassifier(n_estimators=100, max_depth=6, learning_rate=0.1) creates a new XGBoost classifier.</li><li>selection_model.fit(select_X_train, y_train) trains the model using the selected features from the training set.</li></ul><p>4. Evaluation:</p><ul><li>select_X_test = selection.transform(X_test_scaled) applies the same feature selection to the test data.</li><li>predictions = selection_model.predict(select_X_test) makes predictions on the test set using the trained model.</li><li>accuracy = accuracy_score(y_test, predictions) calculates the accuracy of the predictions.</li><li>print(&quot;Thresh=%.3f, n=%d, Accuracy: %.2f%%&quot; % (thresh, select_X_train.shape[1], accuracy*100.0)) prints the threshold, number of selected features, and accuracy for each iteration.</li></ul><pre>for thresh in thresholds:<br> # select features using threshold<br> selection = SelectFromModel(model, threshold=thresh, prefit=True)<br> select_X_train = selection.transform(X_train_scaled)<br> # train model<br> selection_model = XGBClassifier(n_estimators=100, max_depth=6, learning_rate=0.1)<br> selection_model.fit(select_X_train, y_train)<br> # eval model<br> select_X_test = selection.transform(X_test_scaled)<br> predictions = selection_model.predict(select_X_test)<br> accuracy = accuracy_score(y_test, predictions)<br> print(&quot;Thresh=%.3f, n=%d, Accuracy: %.2f%%&quot; % (thresh, select_X_train.shape[1], accuracy*100.0))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*-a3SP_H3oL9HYI__3iVY_w.png" /><figcaption>Output</figcaption></figure><p>The above figure displays the accuracy of the model with the number of features. You can observe that, if we consider all the features we will be getting the same accuracy as the previous model without feature selection. Again the case where n=2, we are getting a slightly improved accuracy than n=8. This can be concluded as even with lesser number of features there is a scope of improving accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0622fb70c4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sarcasm Detection Using Deep Learning]]></title>
            <link>https://medium.com/@dhanyahari07/sarcasm-detection-using-deep-learning-4a28db93fc64?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a28db93fc64</guid>
            <category><![CDATA[sarcasm-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 09:02:25 GMT</pubDate>
            <atom:updated>2024-01-23T09:02:25.731Z</atom:updated>
            <content:encoded><![CDATA[<p>Sarcasm detection in deep learning involves using complex algorithms to automatically identify sarcastic text. It’s a challenging task because sarcasm often relies on subtle cues like context, tone, and unexpected word choices that can be difficult for machines to grasp. However, deep learning techniques have shown promising results in recent years.</p><p>We are going to use a simple LSTM model to detect sarcasm. The dataset is taken from the following link.</p><p><a href="https://www.kaggle.com/datasets/rmisra/news-headlines-dataset-for-sarcasm-detection/data">News Headlines Dataset For Sarcasm Detection</a></p><p>The dataset is in the form of a json file and we can use pandas library to export data into a data frame.</p><p>We will start the process by importing all required libraries</p><p>numpy and pandas are used for data exporting and processing. The regular expression package is very useful is pre-processing the text, where we can remove the unwanted characters. From sklearn we can import train and test split to divide the data into training and testing set.</p><p>The Tokenizer class from tensorflow.keras.preprocessing.text is used to vectorize text by turning each text into a sequence of integers.</p><p>The pad_sequences function from tensorflow.keras.preprocessing.sequence is often used in natural language processing tasks to ensure that all sequences in a dataset have the same length. This is necessary when working with neural networks, as they typically require fixed-size input.</p><p>We are going to create a sequential model and adding layers such as embedding, LSTM and Dense and hence imported all those.</p><pre>import numpy as np<br>import pandas as pd<br>import re<br>from sklearn.model_selection import train_test_split<br>from tensorflow.keras.preprocessing.text import Tokenizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Embedding, LSTM, Dense</pre><p>The next step is to import the data and see how the data appears. Here we are using pandas read_json function since the data is in the form of a json file. Head can be used to display the first few rows of the dataset. The dataset is having three columns. first one is the is_sarcastic column where 1 represents the headline is sarcastic and 0 represents it is not. Second column contains the actual news headline where we want to classify and third column is the article link, which we are not going to consider for analysis in this tutorial.</p><pre>df = pd.read_json(&quot;/Sarcasm_Headlines_Dataset_v2.json&quot;, lines=True)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*Koax6r5tyOloOHjGMCmSDg.png" /><figcaption>First 5 rows of the data</figcaption></figure><p>Next a small pre-processing should be done on the headline to remove all unnecessary data. Regular expression can be used for this</p><ul><li>[^a-zA-Z\s]+: This matches any character that is not an uppercase or lowercase letter, a whitespace character, or an underscore.</li><li>**[@\^&amp;\*&lt;span class=&quot;math-inline&quot;&gt;\]\: Matches any of the following special characters: `@`, `^`, `&amp;`, `*`, ``.</li><li>#\S+: Matches any hashtag (#) followed by one or more non-whitespace characters.</li><li>\S+[a-z0-9]\.(com|net|org): Matches any word (\S+) followed by a period (.), one or more alphanumeric characters ([a-z0-9]), and a common top-level domain (.com, .net, or .org).</li></ul><pre>df[&#39;headline&#39;] = df[&#39;headline&#39;].str.lower()<br>df[&#39;headline&#39;] = df[&#39;headline&#39;].apply(lambda x: re.sub(&#39;[^a-zA-Z\s]+&#39;, &#39;&#39;, x))<br>df[&#39;headline&#39;] = df[&#39;headline&#39;].apply(lambda x: re.sub(&quot;[@\^&amp;\*$]|#\S+|\S+[a-z0-9]\.(com|net|org)&quot;,&quot; &quot;,x))</pre><p>Now the data is pre-processed and since it is a classification problem, we have to see whether the classes are balanced. If it is not, we have to take necessary steps to balance the dataset using classes like <br>imbalanced-learn (imblearn) . But our dataset is almost balanced and doesn’t require any balancing.</p><pre>df[&quot;is_sarcastic&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*IF0VrIPE6ucBl_tc6EB-oQ.png" /><figcaption>classes are balanced</figcaption></figure><p>Next step is to set few hyperparameters for our model.</p><ul><li>training_size = 20000: This specifies the number of samples you’ll use to train your model. 20,000 is a reasonable size for many NLP tasks but may vary depending on the complexity of your data and model.</li><li>vocab_size = 10000: This defines the size of your vocabulary, which is the set of unique words used in your training data. Limiting the vocabulary to 10,000 words reduces model complexity and training time but can lead to information loss if important words are excluded.</li><li>max_length = 32: This sets the maximum length of each text sequence in your data. Sequences longer than 32 will be truncated, while shorter ones will be padded. The optimal length depends on the nature of your data and task.</li><li>embedding_dim = 16: This defines the dimensionality of the word embeddings used in your model. Embeddings map words to numerical vectors, capturing their semantic meaning. 16 dimensions is a relatively low embedding size, often suitable for smaller datasets or initial exploration.</li><li>trunc_type = ‘post’ and padding_type = ‘post’: These specify how you handle sequences exceeding or falling short of the maximum length (max_length = 32). Both options indicate that you&#39;ll truncate from the end of the sequence for overflow and pad with additional tokens (likely the oov_tok) at the end for underflow.</li><li>oov_tok = ‘&lt;OOV&gt;’: This defines the token used to represent out-of-vocabulary (OOV) words, those not included in the vocabulary (vocab_size). ‘&lt;OOV&gt;’ is a common choice for unknown words.</li></ul><pre>#Hyperparameters<br>training_size = 20000<br>vocab_size = 10000<br>max_length = 32<br>embedding_dim = 16<br>trunc_type = &#39;post&#39;<br>padding_type = &#39;post&#39;<br>oov_tok = &#39;&lt;OOV&gt;&#39;</pre><p>For creating a model we have to split the data into dependent and independant variable and traing and testing data thereafter. In this example the headline is the data we are going to give to our model and predicting whether it is sarcastic or not. Train_test_split is a function used to split the data into training and testing.</p><pre>X = df.headline<br>Y = df.is_sarcastic<br><br>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=42)</pre><p>Now some essential text processing steps are to be followed to prepare the data ready for machine learning model</p><p>1. Tokenizer Initialization:</p><ul><li>tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok):</li><li>Creates a Tokenizer object to handle text preprocessing.</li><li>num_words=vocab_size: Limits the vocabulary to the 10,000 most frequent words.</li><li>oov_token=oov_tok: Sets &#39;&lt;OOV&gt;&#39; as the token for out-of-vocabulary words.</li></ul><p>2. Word Index Creation:</p><ul><li>tokenizer.fit_on_texts(X_train):</li><li>Fits the tokenizer on the training data (X_train) to learn the vocabulary.</li><li>Builds the word-index dictionary, assigning a unique integer to each word.</li><li>word_index = tokenizer.word_index:</li><li>Stores the word-index dictionary for later reference.</li></ul><p>3. Transforming Training Data:</p><ul><li>training_sequences = tokenizer.texts_to_sequences(X_train):</li><li>Converts the training text data (X_train) into sequences of integer word indices.</li><li>training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type):</li><li>Pads or truncates the sequences to a uniform length (max_length = 32) for model compatibility.</li><li>padding=&#39;post&#39; adds padding to the end of sequences.</li><li>truncating=&#39;post&#39; truncates sequences from the end if they exceed the maximum length.</li></ul><p>4. Transforming Test Data:</p><ul><li>testing_sequences = tokenizer.texts_to_sequences(X_test):</li><li>Converts the test text data (X_test) into sequences of integer word indices using the same tokenizer.</li><li>testing_padded = pad_sequences(...):</li><li>Pads or truncates the test sequences in the same way as the training data.</li></ul><p>5. Converting Labels to NumPy Arrays:</p><ul><li>training_labels = np.array(y_train):</li><li>Converts the training labels (y_train, likely a list) into a NumPy array for model input.</li><li>testing_labels = np.array(y_test):</li><li>Converts the test labels (y_test) into a NumPy array.</li></ul><pre>#initialize the tokinizer class<br>tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)<br><br>#generate the word index dictionary<br>tokenizer.fit_on_texts(X_train)<br>word_index = tokenizer.word_index<br><br>#generate and pad the training sequence<br>training_sequences = tokenizer.texts_to_sequences(X_train)<br>training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)<br><br>#generate and pad the test sequences<br>testing_sequences = tokenizer.texts_to_sequences(X_test)<br>testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)<br><br>#convert the labels lists into numpy arrays<br>training_labels = np.array(y_train)<br>testing_labels = np.array(y_test)</pre><p>The model creation and running the model is the next step.</p><p>1. Model Architecture:</p><ul><li>model = Sequential(): Creates a sequential model, meaning layers are added in a linear stack.</li><li>model.add(Embedding(...)): Adds an embedding layer:</li><li>input_dim=vocab_size: Number of unique words in the vocabulary (10,000).</li><li>output_dim=100: Dimensionality of the word embeddings (each word represented by a 100-dimensional vector).</li><li>input_length=max_length: Maximum length of input sequences (32).</li><li>model.add(LSTM(units=100)): Adds an LSTM layer with 100 units to capture long-term dependencies in the sequences.</li><li>model.add(Dense(units=1, activation=&#39;sigmoid&#39;)): Adds a dense (fully connected) layer with a single unit and a sigmoid activation for binary classification.</li></ul><p>2. Model Compilation:</p><ul><li>model.compile(...): Configures the model for training:</li><li>optimizer=&#39;adam&#39;: Uses the Adam optimizer for efficient learning.</li><li>loss=&#39;binary_crossentropy&#39;: Uses binary crossentropy loss, suitable for binary classification problems.</li><li>metrics=[&#39;accuracy&#39;]: Tracks accuracy during training and evaluation.</li></ul><p>3. Model Training:</p><ul><li>num_epochs = 30: Sets the number of training epochs (iterations over the entire dataset) to 30.</li><li>history = model.fit(...): Trains the model:</li><li>training_padded: Preprocessed training data.</li><li>training_labels: Corresponding training labels.</li><li>epochs=num_epochs: Number of epochs.</li><li>validation_data: Validation data used to monitor performance during training.</li><li>verbose=2: Displays progress bar and metrics during training.</li></ul><p>4. Model Fitting:</p><ul><li>The model.fit method starts the training process, iteratively adjusting the model&#39;s weights to minimize the loss on the training data and improve performance on the validation data.</li><li>The history object stores training and validation metrics for each epoch, enabling analysis of the learning process.</li></ul><pre># Build the model<br>model = Sequential()<br>model.add(Embedding(input_dim=vocab_size, output_dim=100, input_length=max_length))<br>model.add(LSTM(units=100))<br>model.add(Dense(units=1, activation=&#39;sigmoid&#39;))<br><br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br><br>num_epochs = 30<br>history = model.fit(training_padded, training_labels, epochs=num_epochs, validation_data=(testing_padded, testing_labels), verbose=2)<br><br></pre><p>The last step is to evaluate the model. Since it is a classification problem we are displaying the accuracy of the model</p><pre># Evaluate the model<br>loss, accuracy = model.evaluate(testing_padded, testing_labels)<br>print(f&#39;Test Loss: {loss}, Test Accuracy: {accuracy}&#39;)</pre><p>With all these steps we will be getting around 83% accuracy score.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a28db93fc64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis — A numerical approach]]></title>
            <link>https://medium.com/@dhanyahari07/principal-component-analysis-a-numerical-approach-88a8296dc2dc?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a8296dc2dc</guid>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 13:02:43 GMT</pubDate>
            <atom:updated>2023-09-25T05:28:58.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Principal Component Analysis — A numerical approach</h3><p>In this blog, we are going to see how PCA works with a numerical example. Principal Component Analysis (PCA) is a dimensionality reduction technique commonly used in machine learning and data analysis to reduce the number of features while preserving as much information as possible. It achieves this by finding the principal components of the data, which are orthogonal vectors that capture the most significant variations in the data.</p><p><strong><em>Note: In this example, all values are rounded to 2 decimal points.</em></strong></p><p><strong>Steps for PCA</strong></p><ol><li><strong>Data Preparation:</strong></li></ol><ul><li>Collect and preprocess your data.</li></ul><p>2. <strong>Covariance Matrix Computation:</strong></p><ul><li>Compute the covariance matrix of your centered data. The covariance matrix describes the relationships between the different features in your dataset.</li></ul><p>3. <strong>Eigenvalue and Eigenvector Computation:</strong></p><ul><li>Calculate the eigenvalues and eigenvectors of the covariance matrix. These represent the magnitude and direction of the principal components.</li><li>The eigenvalues indicate the variance explained by each principal component, and the eigenvectors define the direction of these components.</li></ul><p>4. <strong>Sort Eigenvalues:</strong></p><ul><li>Sort the eigenvalues in descending order. The largest eigenvalues correspond to the most significant principal components.</li></ul><p>5. <strong>Select Principal Components:</strong></p><ul><li>Decide how many principal components to keep. You can select a specific number or choose based on the explained variance (e.g., keep components that explain 95% of the variance).</li></ul><p>6.<strong> Projection onto Principal Components:</strong></p><ul><li>Project your original data onto the selected principal components to obtain a new set of features (variables) that are linear combinations of the original features.</li></ul><h3>Step — 1 Collect the data</h3><p>The following are the data points or features given. Let us start with 4 data points</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*9ERCr1sfYJd-YZNM1W3--Q.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*_DV7ozVX48Wh8QnwX5WKUQ.gif" /></figure><h3>Step — 6 Projection onto Principal ComponentsStep — 2 <strong>Covariance Matrix Computation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*xa1ZSxLki_mhqlFe_Fy7yg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*9l-lXpfZe_eqv3mR9anwTQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*zkKCxVNeb-e2gSqPgPyNWg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*xLu0FoNGUiv4o1b_Jccn8Q.gif" /></figure><p>The final covariance matrix is the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*BjVjXDszh_3ovvbdGGoIrw.gif" /></figure><h3>Step — 3 Eigen values and Eigen vector Computation</h3><p>Next we will compute the eigen values of this covariance matrix. The characteristic equation of the covariance matrix is the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*dEG6fjOdH8iyPv65IBECIg.gif" /></figure><p>To find the roots of the quadratic equation we can apply the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*d-lhe4nPsIjEMmr5mFlBRA.jpeg" /></figure><p>By applying the formula, we will get two roots and these are the <strong><em>eigen values.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*Y6Uvs5xkKMWNHQEW5AEKHA.gif" /></figure><p>Next step is to calculate eigen vectors. To calculate this the initial step is to calculate the Characteristic Equation:</p><p>The characteristic equation for finding eigenvalues (λ) of a matrix C is given by:</p><p>det(S — λI) = 0</p><p>where:</p><ul><li>S is the covariance matrix.</li><li>λ (lambda) represents the eigenvalues.</li><li>I is the identity matrix of the same dimensions as C.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*Xex3r9m78MmvWb5mum45Gw.gif" /></figure><p>Equating the above to vector 0, we will get the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*ol017RFAoXXh6WfYTNC-LA.gif" /></figure><p>Taking the first equation into consideration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*i2HXl2e0E372uU-MD7BKOg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*94XErD6JnYX8BawlCDzrlg.gif" /></figure><p>Consider the value of t as 1, the U vector or eigen vector will become</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*-CzShZ_-1g-jKylE3UrE3w.gif" /></figure><h3>Step — 4 Sort Eigen Values</h3><p>Whenever we want to calculate the principal components we have to consider the largest eigen value. Here it is 8.37. To calculate the unit eigen vector , we have to calculate the length of U1.To obtain unit eigenvectors (eigenvectors with a magnitude of 1), we normalize the eigenvectors. To normalize a vector, divide each component by its magnitude (Euclidean norm).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*8dHK_GRQu-xT3PhyhN3f4w.gif" /></figure><p>The below represents the eigenvector corresponding to Principal component 2, if we are calculating PC2 we can consider the below eigenvector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*puBDwe3ig04g1MCMAXrXXw.gif" /></figure><h3>Step — 5 Select First Principal Component</h3><p>The equation to calculate the principal component is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*TmshpWeI8MSGIjQzDte9Jw.gif" /></figure><p>Applying the above equation on the first eigen vector we will get the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*8cESpS83EtAcjRTova2J-w.gif" /></figure><h3>Step — 6 Projection onto Principal Components</h3><p>Applying the equation on each data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*uCKjXJzxZHhiFxzEjJvVcA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*8DP8DE0JJ1iCCyu8cEh9tA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*kVbYXaVVxjT-BC8LyV3p9w.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*tjh5Y9FPIVIW2XsxLHPb_Q.gif" /></figure><p>The final answer ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*-xcOwmajZLdq6CVOxLhIRQ.gif" /></figure><p>The final result can be visualized approximately like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Vc8-5R5_GQsJ07hM3CV18A.png" /></figure><p>Blue points are the data points, the red point is the average point, the yellow circle is the eigen vector point (-0.45,-0.89) and the green line is the first principal component.</p><p>A few references which will help further understanding are given below</p><p><a href="https://towardsdatascience.com/a-step-by-step-introduction-to-pca-c0d78e26a0dd">A Step-By-Step Introduction to PCA</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFgakZw6K1QQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFgakZw6K1QQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFgakZw6K1QQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/88b9702d533c0df8e6e756a94c235e84/href">https://medium.com/media/88b9702d533c0df8e6e756a94c235e84/href</a></iframe><iframe src="https://drive.google.com/viewerng/viewer?url=http%3A//www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/543c397e8be7ac1f7d0ff79d8439816c/href">https://medium.com/media/543c397e8be7ac1f7d0ff79d8439816c/href</a></iframe><p><a href="https://towardsdatascience.com/the-mathematics-behind-principal-component-analysis-fff2d7f4b643">The Mathematics Behind Principal Component Analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a8296dc2dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[House Rent Prediction using Keras]]></title>
            <link>https://medium.com/@dhanyahari07/house-rent-prediction-using-keras-ee9e739e10b1?source=rss-ad0b01dc4651------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9e739e10b1</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Dr. Dhanya NM]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 12:38:55 GMT</pubDate>
            <atom:updated>2023-09-20T12:38:55.370Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will explain how to predict house rent using a simple Keras model. The dataset is collected from Kaggle and can be downloaded from the link below.</p><p><a href="https://www.kaggle.com/datasets/iamsouravbanerjee/house-rent-prediction-dataset">House Rent Prediction Dataset</a></p><h3>Step — 1 Import necessary Header Files</h3><pre>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>from tensorflow import keras<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>import matplotlib.pyplot as plt</pre><p>import pandas and numpy for data processing, Keras for deep learning model, sklearn for splitting the data into training and testing and for standardizing our dataset and finally matplotlib for visualizing the loss value changes during each epoch.</p><h3>Step — 2 Loading the dataset</h3><pre>data=pd.read_csv(&quot;/content/drive/MyDrive/Medium/House_Rent_Dataset.csv&quot;)<br>data.head()</pre><p>This will load the data from the csv file and display the first 5 rows of the dataset</p><h3>Step — 3 Basic Data Information</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*pyYoWJ7jvcIwe8gHfDgRjA.png" /></figure><p>data.info() command will display the basic information about the dataset. It will display the total number of rows in the dataset (4746) and the columns (features) in the dataset with the datatype of each column. As shown in the figure BHK, Rent, Size, and Bathroom are integer fields and the rest are string fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*CXpPVV-Elm1dZxLMkMCqpA.png" /></figure><p>data.isnull().sum() will give the total number of null values in each column. Here no null values are there in the dataset hence the value 0 for all columns.</p><h3>Step — 4 Basic Data PreProcessing</h3><pre>pd.set_option(&quot;display.max_rows&quot;, None)<br>data[&#39;Floor&#39;].value_counts()</pre><p>value_counts() command will display the unique items and the number of times each item is repeated in the dataset. set_option() is set to display all the elements in a sequence, otherwise, only the first 5 and last 5 items will be displayed. Observing the elements, we can see the following pattern, where number can be an integer number.</p><blockquote><strong><em>number</em> out of a <em>number</em></strong></blockquote><blockquote><strong><em>Ground </em>out of <em>number</em></strong></blockquote><blockquote><strong><em>Lower Basement</em> out of <em>number</em></strong></blockquote><blockquote><strong><em>Upper Basement</em> out of <em>number</em></strong></blockquote><p>Here we have to extract the floor number and the total number of floors and make these as separate columns and give the ground, Lower Basement, and Upper Basement a unique number. Here I am using 0 for the ground floor, -2 for the Lower Basement, and -1 for the Upper Basement.</p><pre>data = data.join(data[&#39;Floor&#39;].str.split(&#39; out of &#39;, 1, expand=True).rename(columns={0:&#39;Floor Level&#39;, 1:&#39;Total Floors&#39;}))</pre><p>The above code splits the Floor column with “<strong><em>out of” </em></strong>location and splits the column to two columns namely Floor Level and Total Floors.</p><pre>data[&#39;Floor Level&#39;] = data.apply(lambda x: 0 if x[&#39;Floor Level&#39;] ==&#39;Ground&#39; \<br>                                 else ( -1 if x[&#39;Floor Level&#39;] ==&#39;Upper Basement&#39; \<br>                                 else ( -2 if x[&#39;Floor Level&#39;] ==&#39;Lower Basement&#39; \<br>                                 else (x[&#39;Floor Level&#39;]) ) ), axis=1)</pre><p>The above lambda function does the change of Ground to zero, Upper Basement to -1 and Lower Basement to -2.</p><p>Now Check for the datatype and null values of newly created columns with dtypes and isnull().sum() command we can observe the following</p><blockquote>Floor Level and Total Floors are columns of datatype String,</blockquote><blockquote>There are few null values created in Total Floors columns</blockquote><blockquote>Floor column still exists which is not required anymore</blockquote><pre>data.drop(&#39;Floor&#39;, axis=1, inplace=True)<br>data = data.dropna()<br>data[&#39;Floor Level&#39;] = data[&#39;Floor Level&#39;].astype(int)<br>data[&#39;Total Floors&#39;] = data[&#39;Total Floors&#39;].astype(int)</pre><p>The above three changes are done using the above code snippet. Drop command for dropping the Floor column, dropna to delete the rows with null values, and change Floor Level and Total Floors column to integer datatype.</p><p>Check for the rest of the column with String datatype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*tKDwMtkYdo1rxCb90PurDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*DDC89UVWBon2qAUGIwxj4w.png" /></figure><p>The columns such as “Point of Contact”, “Area Type”, “City”, “Furnishing Status”, and “Tenant Preferred” contains string data with few categories, and we have to deal with those columns and convert them to numerical values.</p><pre>def one_hot_encode_column(dataframe, column_name):<br>    <br>    # Use the pandas get_dummies function to one-hot encode the column<br>    one_hot_encoded = pd.get_dummies(dataframe[column_name], prefix=column_name, drop_first=True)<br>    <br>    # Drop the original column from the DataFrame<br>    dataframe = dataframe.drop(column_name, axis=1)<br>    <br>    # Concatenate the one-hot encoded column(s) with the original DataFrame<br>    dataframe = pd.concat([dataframe, one_hot_encoded], axis=1)<br>    <br>    return dataframe</pre><p>The above function uses get_dummies() function to do one-hot encoding and then drop the original column and finally concatenate the newly created one-hot columns to the original dataframe.</p><pre>columns = [&#39;Area Type&#39;, &#39;City&#39;, &#39;Furnishing Status&#39;, &#39;Tenant Preferred&#39;, &#39;Point of Contact&#39;]<br>for col in columns:<br>    data = one_hot_encode_column(data, col)</pre><p>one_hot_encode_column() function can be used to convert all the above-mentioned columns to one-hoe encoded vectors.</p><p>Drop the unnecessary column called “Area Locality”</p><pre>data = data.drop(&#39;Area Locality&#39;, axis= 1)</pre><p>The last pre-processing step is to convert the “Posted On “ column to date time, which is a string datatype now. Then split it into “month posted”, “day posted”, “day of week posted”, and “quarter posted” and delete the original column. We can use the DateTime function to extract the same.</p><pre>data[&#39;Posted On&#39;] = pd.to_datetime(data[&#39;Posted On&#39;])<br>data[&#39;month posted&#39;] = data[&#39;Posted On&#39;].dt.month<br>data[&#39;day posted&#39;] = data[&#39;Posted On&#39;].dt.day<br>data[&#39;day of week posted&#39;] = data[&#39;Posted On&#39;].dt.dayofweek<br>data[&#39;quarter posted&#39;] = data[&#39;Posted On&#39;].dt.quarter<br>data.drop(&#39;Posted On&#39;, axis=1, inplace=True)</pre><h3>Step — 5 Model Creation and Evaluation</h3><p>For creating the model split the data to dependant variable and independent variable.</p><pre>X = data.drop(&#39;Rent&#39;, axis= 1)<br>y = data[&#39;Rent&#39;]</pre><p>In scikit-learn (sklearn), the train_test_split function is commonly used to split a dataset into training and testing subsets. This function helps you create two separate sets of data—one for training your machine-learning model and another for testing its performance. For training and testing, we are using 80% of the data is used for training and the rest 20% is used for testing.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state = 42)</pre><p>Since our data is in different scales, there should be a conversion mechanism to standardize the data. The StandardScaler in scikit-learn (sklearn) is a preprocessing technique used to scale (normalize) features or variables in your dataset. Standardization rescales features so that they have a mean of 0 and a standard deviation of 1.</p><pre>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>A Sequential model in Keras is a linear stack of layers where you can add one layer at a time, starting from the input layer and proceeding through hidden layers to the output layer. It’s a simple way to create neural networks for various machine-learning tasks.The initial layer the input_shape parameters specifies the number of columns in the X variable after all the pre-processing and transformation. This can be identified using the X.shape command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*Lw15TOCbUXXKu3M7TG8u4w.png" /></figure><p>The first hidden layer is created with 10 neurons followed by a layer with 5 neurons and finally, a dense layer with 1 unit, since it is a Linear Regression Problem.</p><pre># Create a Keras Sequential model<br>model = keras.Sequential([<br>    keras.layers.Dense(units=10, input_shape=(22,), activation=&#39;relu&#39;),  # Hidden layer with 10 units and ReLU activation<br>    keras.layers.Dense(units=5, activation=&#39;relu&#39;),  # Hidden layer with 5 units and ReLU activation<br>    keras.layers.Dense(units=1, activation=&#39;linear&#39;)  # Output layer with 1 unit and linear activation<br>])</pre><p>Compile the model using model.compile(...). You specify the optimizer, loss function, and metrics for evaluation. In this example, we use the Stochastic Gradient Descent optimizer and mean_squared_logarithmic_error loss for regression. After defining and compiling the model, you can use it for training and evaluation. For example, you can use the fit method to train the model on your data.</p><p>The MSLE is useful in regression tasks where the target values span multiple orders of magnitude, and you want to penalize underestimations and overestimations equally. It can be a more suitable metric than the Mean Squared Error (MSE) in such scenarios.</p><pre>model.compile(optimizer=&#39;sgd&#39;, loss=&#39;mean_squared_logarithmic_error&#39;)<br>history = model.fit(X_train, y_train, epochs=100, batch_size=10, verbose=1)</pre><p>In Keras, the model.evaluate() method is used to evaluate the performance of a trained model on a given dataset. This method computes one or more evaluation metrics (e.g., loss and accuracy) on the provided data. The model.evaluate() method returns a list of evaluation metrics. In this example, we print the mean square logarithmic error. The specific metrics returned depend on the metrics you specified when compiling the model.</p><pre>msle = model.evaluate(X_test, y_test, verbose=0)<br>print(&quot;Mean Squared Error on Test Data:&quot;, msle)</pre><p>In Keras, you can use the model.predict() method to make predictions using a trained neural network model. This method takes input data and returns the model&#39;s predictions for that data.</p><pre>predictions = model.predict(X_test)</pre><p>Finally, we will create a loss plot to observe the changes in the loss value after each iteration. Loss value decreases after each epoch and we are running this for 100 epochs.</p><pre># Extract actual and predicted values from the testing set<br>actual_values = y_test<br>predicted_values = predictions<br><br># Plot training loss history<br>plt.figure(figsize=(10, 5))<br>plt.plot(history.history[&#39;loss&#39;], color=&#39;red&#39;, label=&#39;Training Loss&#39;)<br>plt.xlabel(&#39;Epochs&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.title(&#39;Training Loss Over Time&#39;)<br>plt.grid(True)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*-RwMIL_7dUR8LdE3myXuyg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9e739e10b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>