0% found this document useful (0 votes)
65 views9 pages

Rainfall Prediction with ML in Python

Well project report

Uploaded by

ladduyadav63076
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views9 pages

Rainfall Prediction with ML in Python

Well project report

Uploaded by

ladduyadav63076
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Rainfall Prediction using Machine Learning – Python

Last Updated : 20 Dec, 2024

Today there are no certain methods by using which we can predict whether there will be rainfall today or not. Even
the meteorological department’s prediction fails sometimes. In this article, we will learn how to build a machine-
learning model which can predict whether there will be rainfall today or not based on some atmospheric factors. This
problem is related to Rainfall Prediction using Machine Learning because machine learning models tend to perform
better on the previously known task which needed highly skilled individuals to do so.

Importing Libraries and Dataset


Python libraries make it easy for us to handle the data and perform typical and complex tasks with a single line of
code.

 Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform
analysis tasks in one go.

 Numpy – Numpy arrays are very fast and can perform large computations in a very short time.

 Matplotlib/Seaborn – This library is used to draw visualizations.

 Sklearn – This module contains multiple libraries are having pre-implemented functions to perform tasks
from data preprocessing to model development and evaluation.

 XGBoost – This contains the eXtreme Gradient Boosting machine learning algorithm which is one of the
algorithms which helps us to achieve high accuracy on predictions.

 Imblearn – This module contains a function that can be used for handling problems related to data
imbalance.

 Code:-

import numpy as np

import pandas as pd

import [Link] as plt

import seaborn as sb

from sklearn.model_selection import train_test_split

from [Link] import StandardScaler

from sklearn import metrics

from [Link] import SVC

from xgboost import XGBClassifier

from sklearn.linear_model import LogisticRegression

from imblearn.over_sampling import RandomOverSampler

import warnings

[Link]('ignore')

Now let’s load the dataset into the panda’s data frame and print its first five rows.
Python
 Code:-
 df = pd.read_csv('[Link]')
 [Link]()
 Output :-

Now let’s check the size of the dataset.

Python Code :-

[Link]

Output:- (366, 12)

Let’s check which column of the dataset contains which type of data.

Python Code:-

[Link]()

Output:-

As per the above information regarding the data in each column, we can observe that there are no null values.

Python Code:-

[Link]().T
Data Cleaning

The data which is obtained from the primary sources is termed the raw data and required a lot of preprocessing
before we can derive any conclusions from it or do some modeling on it. Those preprocessing steps are known
as data cleaning and it includes, outliers removal, null value imputation, and removing discrepancies of any sort in
the data inputs.

Python Code:- [Link]().sum()

Output:-

So there is one null value in the ‘winddirection’ as well as the ‘windspeed’ column. But what’s up with the column
name wind direction?

Python Code:- [Link]

Output:-
Index(['day', 'pressure ', 'maxtemp', 'temperature', 'mintemp', 'dewpoint', 'humidity ', 'cloud ',
'rainfall', 'sunshine', ' winddirection', 'windspeed'], dtype='object')

Here we can observe that there are unnecessary spaces in the names of the columns let’s remove that.

Python Code:-

[Link]([Link],

axis='columns',

inplace=True)

[Link]

for col in [Link]:

Python Code:-

# Checking if the column contains

# any null values

if df[col].isnull().sum() > 0:

val = df[col].mean()

df[col] = df[col].fillna(val)

[Link]().sum().sum()

Output: 0
Exploratory Data Analysis

EDA is an approach to analyzing the data using visual techniques. It is used to discover trends, and patterns, or to
check assumptions with the help of statistical summaries and graphical representations. Here we will see how to
check the data imbalance and skewness of the data.

Python Code:-

[Link](df['rainfall'].value_counts().values,

labels = df['rainfall'].value_counts().index,

autopct='%1.1f%%')

[Link]()

Output:--

Python Code:-

[Link]('rainfall').mean()

Output: Here we can clearly draw some observations:

 maxtemp is relatively lower on days of rainfall.

 dewpoint value is higher on days of rainfall.

 humidity is high on the days when rainfall is expected.

 Obviously, clouds must be there for rainfall.

 sunshine is also less on days of rainfall.

 windspeed is higher on days of rainfall.

The observations we have drawn from the above dataset are very much similar to what is observed in real life as
well.

features = list(df.select_dtypes(include = [Link]).columns)

[Link]('day')

print(features)

['pressure', 'maxtemp', 'temperature', 'mintemp', 'dewpoint', 'humidity', 'cloud', 'sunshine', 'winddirection',


'windspeed']

Let’s check the distribution of the continuous features given in the dataset.

Python Code:-

[Link](figsize=(15,8))

for i, col in enumerate(features):


Python Code:-

[Link](3,4, i + 1)

[Link](df[col])

plt.tight_layout()

[Link]()

Output:-

Let’s draw boxplots for the continuous variable to detect the outliers present in the data.

Python Code:-

[Link](figsize=(15,8))

for i, col in enumerate(features):

[Link](3,4, i + 1)

[Link](df[col])

plt.tight_layout()

[Link]()
There are outliers in the data but sadly we do not have much data so, we cannot remove this.

Python Code:-

[Link]({'yes':1, 'no':0}, inplace=True)

Sometimes there are highly correlated features that just increase the dimensionality of the feature space and do not
good for the model’s performance. So we must check whether there are highly correlated features in this dataset or
not.

Python Code:-

[Link](figsize=(10,10))

[Link]([Link]() > 0.8,

annot=True,

cbar=False)

[Link]()

Output:-

Now we will remove the highly correlated features ‘maxtemp’ and ‘mintemp’. But why not temp or dewpoint? This is
because temp and dewpoint provide distinct information regarding the weather and atmospheric conditions.

Python Code:-

[Link](['maxtemp', 'mintemp'], axis=1, inplace=True)

Model Training

Now we will separate the features and target variables and split them into training and testing data by using which
we will select the model which is performing best on the validation data.

Python Code:-

features = [Link](['day', 'rainfall'], axis=1)


target = [Link]
As we found earlier that the dataset we were using was imbalanced so, we will have to balance the training data
before feeding it to the model.

X_train, X_val, \

Y_train, Y_val = train_test_split(features,

target,

test_size=0.2,

stratify=target,

random_state=2)

# As the data was highly imbalanced we will

# balance it by adding repetitive rows of minority class.

ros = RandomOverSampler(sampling_strategy='minority',

random_state=22)

X, Y = ros.fit_resample(X_train, Y_train)

The features of the dataset were at different scales so, normalizing it before training will help us to obtain optimum
results faster along with stable training.

Python

# Normalizing the features for stable and fast training.

scaler = StandardScaler()

X = scaler.fit_transform(X)

X_val = [Link](X_val)

Now let’s train some state-of-the-art models for classification and train them on our training data.

 LogisticRegression

 XGBClassifier

 SV

models = [LogisticRegression(), XGBClassifier(), SVC(kernel='rbf', probability=True)]

for i in range(3):

models[i].fit(X, Y)

print(f'{models[i]} : ')

train_preds = models[i].predict_proba(X)

print('Training Accuracy : ', metrics.roc_auc_score(Y, train_preds[:,1]))

val_preds = models[i].predict_proba(X_val)

print('Validation Accuracy : ', metrics.roc_auc_score(Y_val, val_preds[:,1]))

print()
LogisticRegression() :

Training Accuracy : 0.8893967324057472

Validation Accuracy : 0.8966666666666667

XGBClassifier() :

Training Accuracy : 0.9903285270573975

Validation Accuracy : 0.8408333333333333

SVC(probability=True) :

Training Accuracy : 0.9026413474407211

Validation Accuracy : 0.8858333333333333

Model Evaluation

From the above accuracies, we can say that Logistic Regression and support vector classifier are satisfactory as the
gap between the training and the validation accuracy is low. Let’s plot the confusion matrix as well for the validation
data using the SVC model.

Python

import [Link] as plt

from [Link] import ConfusionMatrixDisplay

from sklearn import metrics

ConfusionMatrixDisplay.from_estimator(models[2], X_val, Y_val)

[Link]()

# This code is modified by Susobhan Akhuli

Let’s plot the classification report as well for the validation data using the SVC model.

Python Code:-

print(metrics.classification_report(Y_val,

models[2].predict(X_val)))
precision recall f1-score support

0 0.84 0.67 0.74 24

1 0.85 0.94 0.90 50

accuracy 0.85 74

macro avg 0.85 0.80 0.82 74

weighted avg 0.85 0.85 0.85 74

Common questions

Powered by AI

XGBoost is designed to enhance model predictions through scalability and improved performance using a boosting framework, which corrects misclassified records iteratively. Its ability to handle large datasets efficiently, combined with its built-in support for handling missing data and accommodating class imbalance, makes it particularly suitable for the complexities of rainfall prediction where datasets can be sparse and varied . XGBoost's performance, however, depends on careful tuning to avoid overfitting despite its tendency to achieve high training accuracy .

A confusion matrix provides insights into the specific types of errors the model makes, such as false positives and false negatives, which are critical in adjusting model thresholds and improving its reliability in predicting rain/no-rain. Classification reports augment this by providing a detailed account of precision, recall, and F1-score, which are critical for understanding the trade-offs between sensitivity and specificity within the model, essential for applications where misclassification has significant impacts .

Normalization of features can significantly affect the training process by ensuring that each feature contributes proportionately to the distance calculations and the gradient-based optimization procedures used during training. This helps in achieving faster convergence and more stable training, as different scales of input features do not disproportionately influence the model's predictions, leading to improved performance and accuracy in rainfall prediction .

EDA helps in preparing and understanding the dataset by allowing identification of key patterns, relationships, and anomalies within the data. Techniques such as plotting graphs enable visualization of trends and distributions that guide decisions on data cleaning methods, outlier treatment, and feature selection. In the rainfall prediction context, EDA reveals correlations like higher humidity and lower sunshine on rainy days, aiding in understanding how these features may impact predictions .

Handling data imbalance is crucial because imbalanced datasets can lead to biased models that favor the majority class, resulting in poor predictive performance on the minority class, which, in this case, might be the occurrence of rainfall. RandomOverSampler addresses this by duplicating samples in the minority class to balance the class distribution, which helps in training a model that is equally sensitive to predicting both rainy and non-rainy days .

Both Logistic Regression and SVC models are effective in this context as evidenced by their close training and validation accuracies, suggesting that these models generalize well to unseen data. Specifically, Logistic Regression showed a validation accuracy of 89.6%, whereas SVC had 88.5%, indicating strong performance without significant overfitting. This balance is crucial for reliable rainfall prediction models where the slight difference in metrics can imply robustness in real-world applications .

Pandas streamlines data manipulation and analysis through its data structure, allowing quick data cleaning, sorting, and complex dataset queries with minimal code, which facilitates a smoother workflow in model development. Numpy, with optimized array computations, enables efficient numerical operations and large data processing, essential for quick realization and testing of models during iterative development processes in rainfall prediction .

Machine learning models offer better performance on predictive tasks by identifying complex patterns in data more efficiently than traditional methods, which often depend on simpler statistical models and expert intuition. They are capable of handling large datasets, correcting for class imbalance, and providing robust predictions despite noise and missing data, all of which are challenges faced by traditional meteorological techniques . According to the article, traditional methods may fail to predict rainfall accurately due to the inherent unpredictability of weather patterns .

Examining feature correlations is necessary to avoid multicollinearity, which can inflate the variance of model estimates, misleading model interpretation and degrading performance. By identifying highly correlated features, such as 'maxtemp' and 'mintemp', and removing one, the model complexity is reduced, improving computational efficiency and reducing the risk of overfitting. It ensures that important and independent features contribute to prediction accuracy .

Data cleaning is crucial as it removes inconsistencies, missing values, and outliers that could otherwise lead to inaccurate predictions or model overfitting. By ensuring the data is clean, models are trained on high-quality inputs, which improves their ability to generalize to unseen data. In the context of rainfall prediction, removing unnecessary spaces and filling in missing values ensures the dataset accurately reflects real atmospheric conditions .

You might also like