0% found this document useful (0 votes)
10 views17 pages

Water Quality Analysis Using ML Model

The document discusses a water quality analysis project utilizing machine learning (ML) models to assess the safety of drinking water. It outlines the methodology for collecting and testing water samples, including various tests for turbidity, pH, hardness, and nitrate levels, as well as the implementation of a kNN model for predicting water potability. Results indicate the effectiveness of the ML model in evaluating water quality, with plans for further testing and analysis outlined for future phases.

Uploaded by

f20221074
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)
10 views17 pages

Water Quality Analysis Using ML Model

The document discusses a water quality analysis project utilizing machine learning (ML) models to assess the safety of drinking water. It outlines the methodology for collecting and testing water samples, including various tests for turbidity, pH, hardness, and nitrate levels, as well as the implementation of a kNN model for predicting water potability. Results indicate the effectiveness of the ML model in evaluating water quality, with plans for further testing and analysis outlined for future phases.

Uploaded by

f20221074
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

Water Quality Analysis using ML Model

BY

ABHINAND MANOJ

2022B1A11589P

VIBHOR SAXENA ​

2022B4A11074P

TO

Prof Bansri Roy

BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE, PILANI

(6th October, 2025)


Table of contents

Introduction
Methodology
Results
Post Midsem Plan
References
Introduction
Healthy people, thriving economies, plus a stable environment all depend on readily available,
untainted water. Yet, both nature itself alongside what humans do - like factory discharge, farm
chemicals, or poor trash disposal - often pollute this resource. This pollution can lead to sickness
from contaminated water, immediate harm from poisons within it, or lasting damage caused by
dangerous substances. Checking water quality usually means sending samples to a lab for
detailed tests - a process that, though precise, can drain resources, take forever, and struggle to
keep up with large areas. This makes finding quicker ways to track and foresee potential
problems essential.

These days, computers are getting quite good at checking how clean our water is. They use
clever methods to spot connections in lots of information - things like acidity levels, mineral
content, sulfates, or dissolved stuff. This helps them guess if water is safe to drink. One way they
do this? A system called kNN looks at similar water samples to decide whether any particular
batch passes muster or doesn’t. Predictive tools help quickly evaluate water quality at a large
scale, saving money on decisions. Consequently, they empower officials, environmental groups,
likewise health services to focus efforts, spend funds wisely, then protect people from unsafe
water.

To check water quality, people gather samples - maybe from wells, streams, reservoirs, or city
pipes - carefully, sticking to established rules so results are trustworthy, avoiding any mishaps.
Then labs run tests on these samples utilizing specialized equipment. For instance, they gauge
how murky the water is with a device called a turbidimeter, determining if there are bits floating
around. A pH meter reveals whether a water sample leans toward acidic or alkaline - a key piece
of info when considering what’s happening chemically and biologically. Alongside that, a
spectrophotometer figures out how much of things like nitrates, sulfates, alongside chlorides are
present; it does this by seeing how light passes through. Ultimately, these findings help judge if
the water is good enough to drink.

Researchers gathered water from spots across the BITS campus - the cafeteria, Vijay Restaurant,
a local temple, a cooler by Shankar Hostel, also Dhruv Food Corner just beyond campus
grounds. Each location offered a different view into how people use water, alongside possible
impacts from surroundings. They took great care collecting samples, aiming for dependable
outcomes while preventing any spoiling of the tests.

Researchers examined the gathered samples with typical lab tools. A device gauged how cloudy
each one appeared – this showed if there were bits floating around that dimmed the water. We
checked how acidic or alkaline the water was with a pH meter - a key sign of whether it’s
chemically stable and good for living things. Moreover, we used a spectrophotometer; by
measuring how much light passes through the sample, we figured out how much stuff like
sulfate, chloride, moreover nitrate is dissolved in it
Methodology

To check Turbidity
1.​ Wavelength​

○​ For microbial/culture turbidity: 600 nm (OD600).​

○​ For water turbidity with minimal color interference: ~750–860 nm (pick your
instrument’s nearest fixed wavelength).​

2.​ Blank with deionized/distilled water in a clean 1 cm cuvette.​

3.​ Measure sample; keep OD in the linear range (OD ≤ 0.8–1.0). Dilute if higher; record
dilution.​

4.​ Report as OD at chosen wavelength and dilution (e.g., OD600 = 0.42; 1:5 dilution).​

Converting OD → NTU is not universal. If you need NTU-like values, make a


calibration curve with turbidity standards (e.g., formazin or AMCO): measure OD
of 0, 20, 40, 100, 400 NTU standards at your wavelength, fit a line/curve, then map
unknown samples.

Using a NanoDrop
●​ Works, but with caveats:​

1.​ The microvolume pedestal uses ultra-short, auto-ranging pathlengths and


Beer–Lambert scaling that assume true absorbance; highly scattering samples
(turbid) violate this, so readings can be less reliable and less comparable to 1
cm cuvette OD.​

2.​ If your NanoDrop has a cuvette holder, prefer the cuvette for turbidity/OD work.​

●​ Protocol (pedestal):​

1.​ Select an application that lets you pick a wavelength (e.g., 600 nm).​

2.​ Blank with water, measure sample; keep within the instrument’s linear range;
avoid bubbles/foaming.​

3.​ Use results comparatively (e.g., growth tracking), not as NTU.


ML Model

Features used in the Model


1.​ Water’s pH shows whether it leans toward acid or base. Ideally, pure water sits at 7;
however, the World Health Organization suggests keeping levels between 6.5 yet no more
than 8.5.
2.​ Water gets hard because it picks up minerals - calcium, magnesium mostly - as it moves
over rocks and soil. Consequently, these dissolved substances make water less effective
for things like cleaning.
3.​ Water dissolves things - minerals like potassium, calcium, also sodium bicarbonate. We
call these dissolved bits “solids.” They can give water a funny flavor, making it look pale.
Water boasting a tall TDS reading? That means lots of minerals are dissolved within. For
safe drinking, aim for under 500 milligrams per liter, though levels reaching 1000
milligrams per liter aren’t considered dangerous.
4.​ To keep our water clean, facilities typically use either chlorine or chloramine. Often,
chloramine arises from combining ammonia alongside chlorine during treatment. Water
remains potable - safe for consumption - with chlorine reaching as high as 4 mg/L, also
expressed as 4 ppm.
5.​ Sulfates exist in nature - you’ll find them within stones, earth, also minerals. Ocean water
holds roughly 2,700 milligrams per liter of sulfate. However, most fresh water contains
only 3 to 30 mg/L.
6.​ Total organic carbon gauges how much carbon exists within organic stuff dissolved in
water. It’s a complete count - all the carbon from things that once lived.
7.​ Chlorine treatment can lead to trihalomethanes - chemicals sometimes present in water.
Drinking water is generally okay if these chemicals stay below 80 parts per million.
8.​ Water cloudiness, or turbidity, stems from stuff floating around within it. Measurements
at Wondo Genet Campus averaged 0.98 NTU - well below the World Health
Organization’s guideline of 5.00 NTU.
9.​ Whether water can be drunk safely is shown here. A "1" signifies it’s good to drink; a "0"
means don't.

ML Code
# Import libraries

import numpy as np

import pandas as pd
import [Link] as plt

import seaborn as sns

import warnings

[Link]("ignore")

# 1. Load Dataset

water_df = pd.read_csv("/kaggle/input/water-potability/water_potability.csv")

# 2. Drop unwanted columns (Chloramines, Conductivity, Trihalomethanes)

water_df = water_df.drop(['Chloramines', 'Conductivity', 'Trihalomethanes'], axis=1)

# 3. Check dataset info (rows, columns, data types, missing values)

print(water_df.info())

# 4. Handle missing values (fill with median to avoid bias from outliers)

water_df["ph"].fillna(value = water_df["ph"].median(), inplace = True)

water_df["Sulfate"].fillna(value = water_df["Sulfate"].median(), inplace = True)

# 5. Check class distribution of target variable

print(water_df.Potability.value_counts())

# 6. EDA – Target class visualization

[Link](x=water_df['Potability'])

[Link]("Potability Class Distribution")


[Link]()

# 7. EDA – Boxplots for remaining features vs Potability

fig, axis = [Link](nrows=2, ncols=3, figsize=(16, 8), dpi=96, sharex=False)

count = 0

for i in range(0, 2):

for j in range(0, 3):

if count < (water_df.shape[1] - 1): # exclude target

column = water_df.iloc[:, count]

[Link](x='Potability', y=column, data=water_df, ax=axis[i, j])

count += 1

plt.tight_layout()

[Link]()

# 8. EDA – Distribution plots of features

fig, axis = [Link](nrows=2, ncols=3, figsize=(14, 8), dpi=96)

count = 0

for i in range(0, 2):

for j in range(0, 3):

if count < (water_df.shape[1] - 1):

column = water_df.iloc[:, count]

[Link](column, kde=True, ax=axis[i, j])

count += 1

plt.tight_layout()

[Link]()
# 9. Correlation heatmap

corr_df = water_df.corr()

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

[Link](corr_df, annot=True, cmap="coolwarm")

[Link]("Correlation Heatmap")

[Link]()

# 10. Split data into features (X) and target (y)

features_df = water_df.drop(['Potability'], axis=1)

target_df = water_df['Potability']

# 11. Normalize/scale features

from [Link] import StandardScaler

standard_scaler = StandardScaler()

scaled_features = standard_scaler.fit_transform(features_df)

X_scaled = [Link](scaled_features, columns=features_df.columns)

# 12. Train-test split

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(

X_scaled, target_df, test_size=0.3, random_state=42, stratify=target_df

print("Train shape:", X_train.shape, "Test shape:", X_test.shape)


# 13. kNN model (example: k=15)

from [Link] import KNeighborsClassifier

knn15 = KNeighborsClassifier(n_neighbors=15)

[Link](X_train, y_train)

print("Train Accuracy:", [Link](X_train, y_train))

print("Test Accuracy:", [Link](X_test, y_test))

# 14. Classification report

from [Link] import classification_report, confusion_matrix

print(classification_report(y_test, [Link](X_test)))

# 15. Confusion matrix heatmap

cm = confusion_matrix(y_test, [Link](X_test))

[Link](figsize=(6, 4))

[Link](cm, annot=True, fmt='d', cmap='Blues',

xticklabels=['Not Potable (0)', 'Potable (1)'],

yticklabels=['Not Potable (0)', 'Potable (1)'])

[Link]("Predicted")

[Link]("Actual")

[Link]("Confusion Matrix")

[Link]()

Step-by-step Summary
1.​ Loaded dataset from CSV.​

2.​ Dropped irrelevant columns (Chloramines, Conductivity, Trihalomethanes).​

3.​ Checked dataset info → found missing values.​

4.​ Handled missing values → replaced with median.​

5.​ Explored target class distribution (0 = Not Potable, 1 = Potable).​

6.​ Performed EDA → boxplots, histograms, correlation heatmap.​

7.​ Separated features (X) and target (y).​

8.​ Scaled features with StandardScaler.​

9.​ Split data into train/test (70/30 stratified split).​

10.​ Trained kNN model (example with k=15).​

11.​ Evaluated model using accuracy, precision, recall, F1-score, confusion matrix.
5. Results

S Samples OD570 Turbidity(NTU)


No.
1 Cnot 0.007 0.35
Restaurant
2 Hanuman 0.006 0.3
Mandir
3 Shankar Water 0.002 0.1
Cooler
4 Ram Tap Water 0.006 0.3
5 Milli Q water 0.000 0.0
(Control)

POST MIDSEM WORK

Phase 1: Upcoming Tests

1. pH Test

Objective: Determine acidity/alkalinity of water samples.

Equipment: pH meter / pH paper.

Procedure:

●​ Calibrate the pH meter using buffer solutions (pH 4, 7, 9).​

●​ Immerse the electrode in each sample.​

●​ Record pH values.​

Expected Output: pH values between 6.5–8.5 (as per BIS standards for drinking water).​
2. Nitrate Test

Objective: Measure nitrate ion concentration (NO₃⁻) to check contamination.

Method: Colorimetric method / UV spectrophotometer.

Procedure:

●​ Prepare nitrate standards for calibration.​

●​ Add reagents (e.g., phenoldisulfonic acid method or nitrate test kit).​

●​ Measure absorbance at 410 nm.​

●​ Compare it with the standard curve to find concentration.​



Expected Range: < 45 mg/L for safe drinking water (WHO standard).​

3. Hardness Test

1. Objective

To determine the total hardness of a given water sample (in mg/L as CaCO₃) by soap titration
method

2. Apparatus and Reagents

Apparatus

●​ Burette (50 mL)​

●​ Pipette (25 mL)​

●​ Conical flask (250 mL)​

●​ Measuring cylinder​

●​ Standard hardness solution bottle​

●​ Distilled water​

3. Reagents

1.​ Standard Hard Water (CaCO₃ solution):​


○​ Dissolve 1.0 g of pure CaCO₃ in minimum dilute HCl, neutralize with ammonia,
and dilute to 1 L with distilled water.​

○​ This gives 1000 mg/L as CaCO₃ hardness.​

○​ Dilute further to get 100 mg/L standard solution.​

2.​ Soap Solution:​

○​ Dissolve 10 g of pure soap (sodium stearate or sodium oleate) in 1 L of 95%


ethanol.​

○​ Add small amount of sodium carbonate to prevent acidification.​

○​ Filter and store in airtight bottle.​

3.​ Distilled Water: For preparation and rinsing.​

4. Procedure

A. Standardization of Soap Solution

1.​ Rinse the burette with soap solution and fill it.​

2.​ Pipette 25 mL of standard hard water (100 mg/L CaCO₃) into a conical flask.​

3.​ Add about 1 mL of distilled water to make total volume 50 mL (optional).​

4.​ Shake the flask and titrate with soap solution.​

5.​ After each addition, shake vigorously until a stable lather (1 cm thick) persists for 15
seconds.​

6.​ Note the burette reading (V₁ mL).​

7.​ Repeat titration for concordant readings.​

B. Determination of Total Hardness of Sample

1.​ Pipette 25 mL of the given water sample into a clean conical flask.​

2.​ Add about 1 mL of distilled water (if necessary) to maintain similar volume.​
3.​ Titrate with the standardized soap solution as above.​

4.​ Record the burette reading (V₂ mL) corresponding to the formation of permanent lather.​

5.​ Repeat for consistent readings.

[Link] Test

Objective:Determine the concentration of fluoride ions (F⁻) in water samples to assess their
suitability for drinking purposes.

Method:

Using a Spectrophotometric method (SPADNS method) or Ion-Selective Electrode (ISE)


method.

Expected Range:

0.6 – 1.5 mg/L (as per BIS IS 10500:2012 and WHO standards).

Procedure:

1.​ Preparation of Standard Solutions:​



Prepare a series of standard fluoride solutions (0.0 to 2.0 mg/L) using sodium fluoride
(NaF).​

2.​ Addition of Reagents:​



Add SPADNS reagent and Zirconyl acid reagent to each standard and sample.​

(The fluoride reacts with the zirconium dye complex to produce a color change.)​

3.​ Measurement:​

Measure the absorbance of the colored solution at 570 nm using a spectrophotometer.​

4.​ Calibration Curve:​



Plot absorbance vs. fluoride concentration for the standard solutions to obtain a
calibration curve.​
5.​ Sample Reading:​

Measure the absorbance of the water sample and determine its fluoride concentration
using the calibration curve.​

Phase 2: Data Analysis & Report

Tasks:

1.​ Tabulate all results (Turbidity, pH, Nitrate, Hardness, TDS).​

2.​ Compare results with BIS (IS 10500:2012) and WHO standards.​

3.​ Interpret whether each source is Safe / Unsafe / Needs Treatment.​

4.​ Discuss reasons for variations — industrial discharge, stagnation, pipe corrosion, etc.​

5.​ Prepare graphical comparison (bar charts for each parameter).​

6.​ Draft conclusion and recommendations.​

Phase 3: Modifications & Next Improvements in the ML Model

●​ Columns removed → fewer features, may reduce noise but also risk losing useful
information.​

●​ Try hyperparameter tuning for k and distance metric (GridSearchCV).​

●​ Apply oversampling again if class imbalance causes poor recall for potable water.​

●​ Try other classifiers (Logistic Regression, Random Forest, XGBoost) and compare
results.​

●​ Perform cross-validation instead of single train-test split for more reliable evaluation.
References
[Link]://[Link]/search?q=water+quality
[Link]
3.0019
[Link]​
[Link]​
[Link]
[Link]://[Link]/server/api/core/bitstreams/b437749a-43f7-472f-a6d9-42596e8ac0a
e/content​

You might also like