Data Science Practical
Data Science Practical
Aim:- Study of Matplotlib library (charts, functions – bar chart, line chart, pie chart,
histogram, scatter plot with all specifications like labels, x–y functions).
Objective:- This report outlines the practical implementation of five fundamental plot types
in the Matplotlib library, demonstrating the use of their most critical customization
parameters for data visualization.
Aim
To visualize the relationship and trend between two continuous variables, showing the
progression of one variable (Y) as the other variable (X, often time) changes.
Theory
The [Link]() function connects sequential data points with line segments. It is best used for
time series data, frequency response, or any data where the order of points is meaningful.
Customization is handled by specifying attributes of the Line2D object, such as line color,
style, and data point markers.
Code
# Data
x = [Link](0, 10, 50)
y = [Link](x)
y2 = [Link](x)
[Link](figsize=(10, 5))
Conclusion
Line plots effectively convey trends over a continuous domain. Mastery of parameters like
linestyle, linewidth, and marker is crucial for distinguishing multiple data series and
enhancing plot readability.
Aim
To visualize the distribution of data points for two numerical variables and identify
correlations, clusters, or outliers.
Theory
The [Link]() function plots individual data points as markers. Unlike [Link], it does not
assume sequential connection between points. Its primary strength lies in its ability to map
additional variables to visual properties like marker size (s) and color (c), enabling
visualization in up to four dimensions (X, Y, Size, Color).
Code
import numpy as np
[Link](42)
N = 100
x = [Link](N) * 100
y = [Link](N) * 100
[Link](figsize=(8, 8))
scatter = [Link](
x, y,
cbar = [Link](scatter)
plt.tight_layout()
Conclusion
The scatter plot is indispensable for bivariate analysis, and its parameters (s, c, cmap) allow it
to become a powerful tool for visualizing higher-dimensional datasets through aesthetic
mapping.
3. Bar Plot ([Link])
Aim
Theory
The [Link]() function creates vertical rectangular bars, where the height of the bar is
proportional to the value it represents. It is ideal for showing frequency distributions or
comparing summary statistics across categories. Key parameters are used to control the visual
separation and stacking of the bars.
Code
# Data
categories = ['Q1', 'Q2', 'Q3', 'Q4']
sales_2023 = [350, 420, 390, 510]
errors = [20, 15, 25, 30] # Error data
[Link](figsize=(8, 6))
[Link](
categories,
sales_2023,
width=0.6, # Width of the bars (controlling spacing)
color=['#4C72B0', '#55A868', '#C44E52', '#8172B2'], # Custom colors
edgecolor='black', # Border color
linewidth=1.0, # Border width
alpha=0.9, # Transparency
align='center', # Alignment of bar with tick
# Parameter for error visualization
yerr=errors, # Error array
ecolor='darkred', # Error bar color
capsize=8 # Length of the error bar caps
)
Conclusion
Bar plots offer a quick comparative overview of categorical data. The inclusion of width and
yerr/xerr (for error bars) allows for precise control over the visual presentation and statistical
rigor.
4. Histogram ([Link])
Aim
To display the underlying frequency distribution of a single numerical variable by grouping
data into bins and counting observations in each bin.
Theory
The [Link]() function calculates and draws a histogram. The shape of a histogram reveals
important information about the data's central tendency, spread, and modality. The most
critical parameter is bins, which determines the number or boundaries of the intervals (bins).
Code
import [Link] as plt
import numpy as np
[Link](figsize=(8, 6))
[Link](
data,
bins=30, # Number of bins
density=True, # Normalize to form a probability density
color='teal', # Color of the bars
alpha=0.6, # Transparency
histtype='stepfilled', # Type: 'bar', 'barstacked', 'step', 'stepfilled'
edgecolor='gray', # Border color
range=(50, 150), # The range of the data to consider
label='Distribution'
)
Histograms are the primary tool for understanding data distribution. The bins and density
parameters fundamentally change the plot's interpretation, making their appropriate use
essential for accurate statistical representation.
Aim
To represent data as slices of a pie, showing the proportion of each category relative to the
whole.
Theory
The [Link]() function draws a circular chart divided into proportional sectors. While often
criticized for poor quantitative comparison, it is effective for showcasing market share or
contribution to a total. Critical parameters include explode (to emphasize slices) and autopct
(to display percentages).
Code
# Data
sizes = [40, 30, 15, 15]
labels = ['North', 'South', 'East', 'West']
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
[Link](figsize=(7, 7))
[Link](
sizes,
explode=explode,
labels=labels,
autopct='%1.2f%%', # Format percentage string with 2 decimal places
shadow=True, # Add shadow for 3D effect
startangle=140, # Rotates the start of the plot
colors=colors, # Custom colors
pctdistance=0.7, # Distance of percentage labels from the center
labeldistance=1.1, # Distance of category labels from the center
wedgeprops={'linewidth': 2, 'edgecolor': 'darkgray'} # Customize the wedges
)
Conclusion
Pie plots are visually engaging for simple proportional data. The explode and autopct
parameters are key to making pie charts informative and aesthetically appealing by adding
emphasis and numerical context.
Experiment -2
Aim:-Study of Numpy Library
Objective:-
To understand the architecture and implement the 28 most extensively used functions and
concepts within the NumPy (Numerical Python) library, focusing on multi-dimensional array
creation, manipulation, advanced indexing, mathematical operations, and statistical
computations.
Theory
NumPy's core is the ndarray (N-dimensional array) object, which stores homogeneous data
and allows for fast, efficient vectorization of mathematical operations without explicit loops
(a process called vectorization). This report covers functions critical for data preprocessing
and numerical analysis, highlighting their essential parameters.
Key Parameters
Function Purpose
Covered
[Link]() Creates an array from a Python list/tuple. dtype, copy
[Link]() Creates an array with regularly spaced values. start, stop, step, dtype
Creates an array with a specified number of start, stop, num,
[Link]()
samples over an interval. endpoint, dtype
[Link]() /
Creates an array filled with zeros or ones. shape, dtype
[Link]()
Creates an array filled with a specific constant
[Link]() shape, fill_value, dtype
value.
import numpy as np
# 1. [Link]()
arr1 = [Link]([1, 2, 3], dtype='float64', copy=True)
print(f"1. [Link] (float64): {arr1}")
# 2. [Link]()
arr2 = [Link](start=0, stop=10, step=2, dtype=np.int32)
print(f"2. [Link]: {arr2}")
# 3. [Link]()
arr3 = [Link](start=0, stop=1, num=5, endpoint=True)
print(f"3. [Link] (5 points): {arr3}")
# 4. [Link]() / [Link]()
arr4_z = [Link](shape=(2, 3), dtype=int)
arr4_o = [Link](shape=(2, 3), dtype=int)
print(f"4. [Link] (2x3): \n{arr4_z}")
# 5. [Link]()
arr5 = [Link](shape=(3, 3), fill_value=42.5, dtype=float)
print(f"5. [Link] (3x3, value 42.5): \n{arr5}")
arr_base = [Link](12) # 0 to 11
# Attributes
print(f"Array: {arr_base}")
print(f"Shape: {arr_base.shape}, Dtype: {arr_base.dtype}, Ndim: {arr_base.ndim}")
# .reshape()
arr_reshaped = arr_base.reshape((3, 4), order='C') # 'C' is C-style (row-major)
print(f"Reshaped (3x4): \n{arr_reshaped}")
# .T (Transpose)
arr_transposed = arr_reshaped.T
print(f"Transposed (4x3): \n{arr_transposed}")
# [Link]()
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
arr_concat_row = [Link]((A, B), axis=0)
arr_concat_col = [Link]((A, B), axis=1)
print(f"Concatenate (axis=0, Row-wise): \n{arr_concat_row}")
print(f"Concatenate (axis=1, Col-wise): \n{arr_concat_col}")
# [Link]() / [Link]()
arr_v = [Link]((A, B))
print(f"VStack (Vertical Stack): \n{arr_v}")
# [Link]()
arr_split = [Link](arr_concat_row, 2, axis=0) # Split into 2 equal parts
print(f"Split (into 2 parts, axis=0): {arr_split[0].shape}, {arr_split[1].shape}")
III. Mathematical and Linear Algebra Operations (6 Functions/Concepts)
Key Parameters
Function/Concept Purpose
Covered
Universal functions (ufuncs) for element-wise (Element-wise
[Link]() / [Link]()
addition/subtraction. operations)
Calculates the dot product (matrix multiplication
[Link]() / @ N/A
or inner product).
Calculates matrix product (preferred over [Link]
[Link]() N/A
for matrices).
Computes the (multiplicative) inverse of a
[Link]() (Input matrix)
matrix.
[Link]() Computes the determinant of a square matrix. (Input matrix)
[Link]() / [Link]() / Ufuncs for common element-wise operations
(Input array)
[Link]() (e.g., square root, exponential, log).
Code: Mathematical Operations
# Data
M1 = [Link]([[1, 2], [3, 4]])
M2 = [Link]([[5, 6], [7, 8]])
# [Link]()
det_M1 = [Link](M1)
print(f"Determinant of M1: {det_M1:.2f}")
# [Link]()
inv_M1 = [Link](M1)
print(f"Inverse of M1: \n{inv_M1.round(2)}")
# [Link]()
arr_sqrt = [Link](M1)
print(f"Element-wise sqrt(M1): \n{arr_sqrt.round(2)}")
# [Link]() / [Link]()
arr_exp = [Link](M1)
print(f"Element-wise exp(M1, first row): {arr_exp[0].round(2)}")
IV. Statistical Operations (6 Functions)
Key Parameters
Function Purpose
Covered
[Link]() Computes the arithmetic mean. axis, dtype, keepdims
[Link]() Computes the median. axis, keepdims
[Link]() Computes the standard deviation. axis, ddof, keepdims
[Link]() / [Link]() Finds the maximum or minimum value. axis, keepdims
[Link]() /
Returns the indices of the max/min elements. axis
[Link]()
Returns elements chosen from x or y based
[Link]() condition, x, y
on condition.
# [Link]() / [Link]()
max_val = [Link](stats_arr)
print(f"Global Maximum: {max_val}")
# [Link]() / [Link]()
argmax_row = [Link](stats_arr, axis=1)
print(f"Index of Max element per row: {argmax_row}") # e.g., 2 means 3rd element is max in
each row
# [Link]()
condition = stats_arr > 30
result = [Link](condition, 'High', 'Low') # Replace values based on condition
print(f"[Link] (Conditional Replacement): \n{result}")
V. Indexing and Broadcasting (5 Concepts)
Key Parameters
Concept Purpose
Covered
Slicing [::] Accessing a subset of the array based on ranges. start, stop, step
Boolean
Selecting elements based on a logical condition array. (Boolean mask)
Indexing
Selecting non-contiguous elements using a list/array of
Fancy Indexing (Array of indices)
indices.
Broadcasting Defines how NumPy handles arrays with different (Shape alignment
Concept shapes during arithmetic operations. rules)
Used to increase the dimension of an existing array
[Link] N/A
(e.g., turning a 1D array into a column/row vector).
# Data
index_arr = [Link](27).reshape(3, 3, 3)
print(f"3D Array (3x3x3): \n{index_arr[0]}") # Showing only first slice
# Slicing [::]
slice1 = index_arr[1, 0:2, ::2] # Slice 1, rows 0-1, columns 0 and 2
print(f"Slicing [1, 0:2, ::2]: {slice1}")
# Boolean Indexing
bool_arr = index_arr[0]
mask = bool_arr % 2 == 0 # True for even numbers
even_numbers = bool_arr[mask]
print(f"Boolean Indexing (Even numbers from slice 0): {even_numbers}")
# Fancy Indexing
row_indices = [0, 2, 1]
col_indices = [1, 0, 2]
fancy_selection = index_arr[0, row_indices, col_indices]
print(f"Fancy Indexing (Specific elements): {fancy_selection}")
# [Link]
A_col_vector = A[:, [Link], 1] # Selects column 1, adds a new axis
print(f"[Link] shape: {A_col_vector.shape} (Makes it a column vector)")
Conclusion
Objective:-
To study and practically implement the 28 most critical functions and methods in the Pandas
library, focusing on efficient data loading, cleaning, manipulation, aggregation, and analysis
using DataFrame and Series objects.
Theory
Pandas is built on NumPy and provides high-level data structures and tools designed to make
data analysis fast, easy, and expressive. The primary data structures are the DataFrame (a
2D labeled array with potentially heterogeneous columns) and the Series (a 1D labeled
array). Mastery of its methods is essential for data wrangling and preprocessing.
import pandas as pd
import numpy as np
# 2. df.sort_values()
sorted_df = df.sort_values(by=['YearsExp', 'Salary'], ascending=[False, True])
print(f"2. Sort Values (Top 3 by Exp):\n{sorted_df[['YearsExp', 'Salary']].head(3)}")
# 3. [Link]()
def bonus_calc(row):
return row['Salary'] * 0.10 if row['YearsExp'] >= 5 else 0
# 5. df.pivot_table()
pivot_table = pd.pivot_table(
df,
values='Salary',
index='Department',
aggfunc='mean'
)
print(f"5. df.pivot_table (Avg Salary):\n{pivot_table}")
# 6. df['col'].unique()
unique_depts = df['Department'].unique()
print(f"6. Unique Departments: {unique_depts}")
Conclusion
The Pandas library provides essential tools for the initial stages of the data science workflow.
Proficiency in using methods like loc and iloc for precision indexing, understanding the
power of groupby and agg for summarization, and knowing how to handle data imperfections
using fillna and dropna are foundational. The parameters covered (e.g., axis, how, inplace,
by) are crucial for controlling the execution and output of these methods effectively.
Experiment -4
Aim:-Write a programme in Python to predict the class of the flower based on
available attributes
Outcome:
Must be able to predict the class (species) of a flower when unseen attribute values are
given.
Objectives:
Nomenclature:
Symbol Description
A Bias term
Solution:
How it works:
Logistic Regression models the probability that a given input point belongs to a particular
class using the logistic (sigmoid) function. For multiple classes, multinomial logistic
regression is used. The decision boundary is found that best separates the classes.
Scatterplots and pair plots help visualize class separability. Evaluation is done using
accuracy, confusion matrix, and classification reports.
Assumptions:
Data should have minimal multicollinearity.
Dependencies:
Numpy
Pandas
Matplotlib
Seaborn
Scikit-learn
Code/Pseudo Code
import numpy as np
import pandas as pd
iris = datasets.load_iris()
X = [Link]
y = [Link]
# Train model
[Link](X_train, y_train)
y_pred = [Link](X_test)
# Evaluation
Results
Test Case:
Sepal Length Sepal Width Petal Length Petal Width Predicted Class
References:
Fisher, R.A. (1936). “The use of multiple measurements in taxonomic problems.”
Viva:
• What is classification?
• What is the difference between regression and classification?
• What is logistic regression used for?
• How do you interpret the confusion matrix?
Experiment -5
Aim:- Write a programme in Python to Loan Approval Prediction Using Logistic
Regression
Outcome
Must be able to predict whether a loan application will be approved or rejected based on
applicant data such as income, credit score, employment status, etc.
Objectives
Understand the relationship between applicant attributes (independent variables) and
the loan approval decision (response variable).
Learn how to apply Logistic Regression for binary classification.
Nomenclature
Symbol Description
b₀ Bias/intercept
Solution
Logistic Regression is a statistical method used to model a binary outcome. Unlike Linear
Regression, Logistic Regression predicts the probability that a given input point belongs to a
particular class.
The logistic regression equation is:
# --- 1. Data Setup (Using Synthetic Data for a self-contained example) ---
[Link](42)
n_samples = 300
data = [Link]({
'Gender': [Link](['Male', 'Female', [Link]], n_samples, p=[0.45, 0.45,
0.1]),
'Married': [Link](['Yes', 'No'], n_samples),
'Credit_History': [Link]([1.0, 0.0, [Link]], n_samples, p=[0.7, 0.2, 0.1]),
'ApplicantIncome': [Link](1500, 60000, n_samples),
'LoanAmount': [Link](100, 700, n_samples),
'Loan_Status': [Link](['Y', 'N'], n_samples, p=[0.7, 0.3]) # Target
})
[Link](X_train, y_train)
print("Training Complete.")
print("\n**Classification Report:**")
print(classification_report(y_test, y_pred, target_names=['N', 'Y']))
Results
Test Cases
Input (Income, Credit_Score, Employment_Status) Output (Loan Approved)
50,000, 750, 1 1
20,000, 600, 0 0
Result Analysis
Advantages:
Simple to implement and interpret.
Good baseline for binary classification tasks.
Issues:
May underperform if data is not linearly separable.
Sensitive to outliers and multicollinearity.
References
Scikit-learn Logistic Regression Documentation
Machine Learning Mastery by Jason Brownlee
Coursera: Machine Learning by Andrew Ng