Monday, 10 March 2025

Using the Interquartile Range (IQR) to Identify Outliers

 

IQR stands for interquartile range, it is a measure of variability that is used to describe the middle 50% of a data set.

 

How IQR is calculated?

IQR is calculated by taking the difference between the third quartile (Q3) and the first quartile (Q1).

 

Q1 = Element at position (n + 1)/4

Q3 = Element at position 3(n + 1)/4

 

‘n’ stands for number of elements in the data set.

 

For example, let's say we have the following data set (data set to be ordered)

 

10, 20, 30, 40, 50, 60, 70, 80, 90, 100

 

Let’s find Q1 for above dataset

The position of the first quartile is (n + 1)/4. Since, there are 10 data points in the data set, then the position of the first quartile is (10 + 1)/4 = 2.75. That means we can consider the element at the position 3 (taking 3 as nearest position to 2.75 here) as the value for Q1, which is 30.

 

Another simple way to find Q1 is, arrange your data in ascending order and then find the median (middle) of the lower half of the data.

 

In the above example, lower half of the data is [10, 20, 30, 40, 50] and the median is 30

 

Let’s find Q3 for above dataset

The position of the third quartile is 3(n + 1)/4. Since, there are 10 data points in the data set, then the position of the third quartile is 3(10 + 1)/4 = 33/4 = 8.2 This means that the third quartile is the eighth value in the data set. So 80 is the Q3 value.

 

Another simple way to find Q3, arrange your data in ascending order and then find the median (middle) of the upper half of the data.

 

In the above example, upper half of the data is [60, 70, 80, 90, 100] and the median is 80.

 

So, the IQR for this data set is 80 - 30 = 50.

 

Find the below working application.

 

iqr.py

import numpy as np

data_points = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

# Calculate Q1
q1 = np.percentile(data_points, 25)

# Calculate Q3
q3 = np.percentile(data_points, 75)

# Calculate IQR
iqr = q3 - q1

print('Q1:', q1)
print('Q3:', q3)
print('IQR:', iqr)

 

Output

Q1: 32.5
Q3: 77.5
IQR: 45.0

As IQR focuses on the central portion of the data distribution, it is not affected by outliers.

 

iqr_box_plot.py

import numpy as np
import matplotlib.pyplot as plt

# Generate some random data with a mean of 0 and standard deviation of 1
house_prices = [50000, 300000, 950000, 500000, 750000, 100000, 325000, 650000, 25000, 200000, 35000]

# Calculate quartiles
q1 = np.percentile(house_prices, 25)  # Q1 (First Quartile)
q3 = np.percentile(house_prices, 75)  # Q3 (Third Quartile)

# Create the box plot
plt.boxplot(house_prices)

# Label the quartiles
plt.text(0.85, q1, f'Q1: {q1}', va='center', ha='left', bbox=dict(facecolor='white', edgecolor='black'))
plt.text(0.85, q3, f'Q3: {q3}', va='center', ha='left', bbox=dict(facecolor='white', edgecolor='black'))

# Set labels and title
plt.ylabel('Exam Scores')
plt.title('Box Plot with Q1 and Q3 Quartiles')

# Show the plot
plt.show()

Output

 

Previous                                                    Next                                                    Home

Variance: A Measure of Data Spread

Variance is used to calculate how much individual data points differ from the mean (average) of the dataset. It is interpreted as the average squared distance from the mean.

Formula

 


where:

 

  1. x is a value in the data set
  2. μ is the mean of the data set
  3. n is the number of values in the data set

 

A larger variance indicates that the data points are more spread out from the mean, while a smaller variance indicates that the data points are closer to the mean.

 

For example, consider below house prices.

house_prices = [100000, 110000, 125000, 95000, 115000, 118000, 123000, 105000]

 

To determine whether the data is widely spread from the mean, we can compare the variance to the original data values by considering the magnitude of the standard deviation. Standard deviation is the square root of the variance.

 

Mean, variance and standard deviation values for the above data set is given below.

 

mean : 111375.0

variance : 102234375.0

standard_deviation : 10111.101572034573

 

 

Now when we compare the standard deviation (10111.101572034573)  to the mean (: 111375.0 dollars). In this case, the standard deviation is smaller than the mean, which indicates that the data is not extremely widely spread from the mean.

 

Find the below working application.

 

variance.py

import numpy as np
import matplotlib.pyplot as plt

house_prices = [100000, 110000, 125000, 95000, 115000, 118000, 123000, 105000]

# Calculate the standard deviation of the data
mean = np.mean(house_prices)
variance = np.var(house_prices)
standard_deviation = np.sqrt(variance)

print(f'mean : {mean}')
print(f'variance : {variance}')
print(f'standard_deviation : {standard_deviation}')

# Create a scatter plot of data points
plt.scatter(house_prices, range(len(house_prices)), label='House prices', color='green', marker='o')

plt.axvline(standard_deviation, color='r', linestyle='dashed', linewidth=2, label=f'Standard Deviation: {standard_deviation:.2f}')
plt.axvline(mean, color='blue', linestyle='dashed', linewidth=2, label=f'Mean: {mean:.2f}')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.legend()
plt.title('Scatter plot  with Variance')
plt.show()

Output

mean : 111375.0
variance : 102234375.0
standard_deviation : 10111.101572034573



Note

  1. In practice, the primary measure used to assess the spread or variability of data is the standard deviation. There is no mandatory need to calculate the variance unless you specifically require it for a particular statistical analysis.


 

Previous                                                    Next                                                    Home

Standard Deviation: A Measure of Variability

Standard deviation quantifies the amount of variation in the data set.

Formula 


Where

  1. N : Represents number of data points in the population.
  2. Xi : Represents each data point.
  3. μ : Represents the mean of the population.
  4. σ : Represents the standard deviation

 

 

Low and high standard deviations

A low standard deviation indicates that the data points tend to be very close to the mean.

 

A high standard deviation indicates that the data points are spread out over a wider range of values.

 

How to know whether standard deviation is low or high?

There is no fixed threshold that universally defines whether a standard deviation is considered as low or high, it depends on the context of the data and the specific field of study.

 

In general, a standard deviation that is two or three times larger than the mean is considered to be high, or you can go with below kind of rules too.

 

If the standard deviation is small compared to the mean, it is considered low. This means that the data points are relatively close to the mean.

 

If the standard deviation is large compared to the mean, it is considered high. This indicates that the data points are more spread out and less concentrated around the mean.

 

Real world use cases

  1. If there is a a higher standard deviation in a company stock prices change, it indicates greater price fluctuation which is considered riskier.
  2. We can use standard deviation in evaluation the prices of houses in a neighbourhood. A low standard deviation indicates that the houses are all of similar price and a high standard deviation indicates that there is a wider range of prices.

 

 

Low standard deviation example

house_prices = [100000, 110000, 125000, 95000, 115000, 118000, 123000, 105000]

 

Mean and standard deviation for the above data points is given below.

 

mean : 111375.0

std_deviation : 10111.101572034573

 

Given the range of house prices, which spans from $95,000 to $125,000, a standard deviation of approximately 10111.101572034573 can be considered relatively low. This suggests that the house prices are relatively close to the mean of $111375.0.

 

low_standard_deviation.py

import numpy as np
import matplotlib.pyplot as plt

# Generate some random data with a mean of 0 and standard deviation of 1
house_prices = [100000, 110000, 125000, 95000, 115000, 118000, 123000, 105000]

# Calculate the standard deviation of the data
mean = np.mean(house_prices)
std_deviation = np.std(house_prices)

print(f'mean : {mean}')
print(f'std_deviation : {std_deviation}')

# Create a scatter plot of data points
plt.scatter(house_prices, range(len(house_prices)), label='House prices', color='green', marker='o')

plt.axvline(std_deviation, color='r', linestyle='dashed', linewidth=2, label=f'Standard Deviation: {std_deviation:.2f}')
plt.axvline(mean, color='blue', linestyle='dashed', linewidth=2, label=f'Mean: {mean:.2f}')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.legend()
plt.title('Scatter plot  with Standard Deviation')
plt.show()

Output

mean : 111375.0
std_deviation : 10111.101572034573

 


 

High standard deviation example

house_prices = [50000, 300000, 950000, 500000, 750000, 100000, 325000, 650000, 25000, 200000, 35000]

 

Mean and standard deviation for the above data points is given below.

 

mean : 353181.8181818182

std_deviation : 303818.67145382444

 

Given the wide range of values, which span from $25,000 to $950,000, a standard deviation of approximately 303818.67145382444 can be considered relatively high. This indicates that the data points are spread out over a significant range from the mean of approximately $353181.8181818182.

 

Find the below working application.

 

high_standard_deviation.py 

import numpy as np
import matplotlib.pyplot as plt

# Generate some random data with a mean of 0 and standard deviation of 1
house_prices = [50000, 300000, 950000, 500000, 750000, 100000, 325000, 650000, 25000, 200000, 35000]

# Calculate the standard deviation of the data
mean = np.mean(house_prices)
std_deviation = np.std(house_prices)

print(f'mean : {mean}')
print(f'std_deviation : {std_deviation}')

# Create a scatter plot of data points
plt.scatter(house_prices, range(len(house_prices)), label='House prices', color='green', marker='o')

plt.axvline(std_deviation, color='r', linestyle='dashed', linewidth=2, label=f'Standard Deviation: {std_deviation:.2f}')
plt.axvline(mean, color='blue', linestyle='dashed', linewidth=2, label=f'Mean: {mean:.2f}')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.legend()
plt.title('Scatter plot with Standard Deviation')
plt.show()

Output

mean : 353181.8181818182
std_deviation : 303818.67145382444

 


 

 

Previous                                                    Next                                                    Home

Understanding animation-timing-function in CSS

The animation-timing-function property in CSS defines the speed curve of an animation. This property specifies how the intermediate states of the animation are calculated. In other words, it controls how the animation progresses through its duration, whether it moves at a constant speed, accelerates, decelerates, or follows a custom speed pattern.

 

Common Values of animation-timing-function:

1.   linear: The animation progresses at a constant speed from start to finish.

2.   ease: This is the default value. The animation starts slow, speeds up in the middle, and then slows down again before ending.

3.   ease-in: The animation starts slow and gradually speeds up.

4.   ease-out: The animation starts fast and then slows down towards the end.

5.   ease-in-out: The animation starts slow, speeds up in the middle, and then slows down again before ending.

6.   cubic-bezier(n, n, n, n): This allows for a custom cubic Bézier curve to define the animation's speed curve. The values are numbers between 0 and 1.

7.   steps(n, [start | end]): This divides the animation into a specific number of equal steps. The start and end keywords define when the steps take effect.

 

animation-timing-function.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animation Timing Function Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }

        .container {
            width: 80%;
            max-width: 800px;
            margin: 20px;
        }

        .box {
            width: 100px;
            height: 100px;
            margin: 20px 0;
            background-color: #4CAF50;
            animation: moveRight 5s infinite;
        }

        .linear {
            animation-timing-function: linear;
        }

        .ease {
            animation-timing-function: ease;
        }

        .ease-in {
            animation-timing-function: ease-in;
        }

        .ease-out {
            animation-timing-function: ease-out;
        }

        .ease-in-out {
            animation-timing-function: ease-in-out;
        }

        .cubic-bezier {
            animation-timing-function: cubic-bezier(0.68, -0.55, 0.27, 1.55); /* Custom bounce effect */
        }

        @keyframes moveRight {
            from {
                transform: translateX(0);
            }
            to {
                transform: translateX(500px);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box linear">linear</div>
        <div class="box ease">ease</div>
        <div class="box ease-in">ease-in</div>
        <div class="box ease-out">ease-out</div>
        <div class="box ease-in-out">ease-in-out</div>
        <div class="box cubic-bezier">cubic-bezier</div>
    </div>
</body>
</html>

 


Previous                                                    Next                                                    Home

Mastering CSS Animations: Understanding animation-name and animation-duration

animation-name Property

The animation-name property specifies the name of the keyframes animation that you want to apply to an element. In CSS, keyframes are defined using the @keyframes rule, which outlines the animation's behavior and style changes at specific points throughout its duration.

 

Syntax

animation-name: animation1;

 

Example

@keyframes moveAndChangeColor {

}

.box {
	animation-name: moveAndChangeColor;
}

In this example, the moveAndChangeColor keyframes animation is assigned to the .box using the animation-name property.

 

animation-duration Property

The animation-duration property defines the length of time it takes for one cycle of the animation to complete. It is specified in seconds (s) or milliseconds (ms).

 

Example

animation-duration: 2s;

 

Example

.box {
	animation-name: moveAndChangeColor;
	animation-duration: 5s;
}

 

Here, the animation assigned to .box will complete one cycle in 5 seconds.

 

animation-name-duration.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Animation Example</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            animation-name: moveAndChangeColor;
            animation-duration: 5s;
        }

        /* Defining keyframes */
        @keyframes moveAndChangeColor {
            0% {
                transform: translateX(0);
                background-color: red;
            }
            50% {
                transform: translateX(150px);
                background-color: green;
            }
            100% {
                transform: translateX(300px);
                background-color: blue;
            }
        }


    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

 

Previous                                                    Next                                                    Home