NumPy and Matplotlib Basics Guide
NumPy and Matplotlib Basics Guide
1
2. Array Operations
import numpy as np
# Creating arrays
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Element-wise addition
add_result = [Link](a, b)
print("Addition:", add_result)
# Element-wise subtraction
sub_result = [Link](a, b)
print("Subtraction:", sub_result)
# Element-wise multiplication
mul_result = [Link](a, b)
print("Multiplication:", mul_result)
# Element-wise division
div_result = [Link](a, b)
print("Division:", div_result)
Output
2
3. Array Reshaping
import numpy as np
# Creating a 1D array
array = [Link](12)
print("Original array:", array)
output
3
[Link] and Slicing
import numpy as np
# Creating a 2D array
array_2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D Array:\n", array_2d)
output
4
5. Statistical Operations
import numpy as np
# Creating an array
array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Calculating mean
mean = [Link](array)
print("Mean:", mean)
# Calculating median
median = [Link](array)
print("Median:", median)
5
PROGRAM 2:Create two 2D arrays using array object and
a. Add the 2 matrices and print it
b. Subtract 2 matrices
c. Multiply the individual elements of matrix
d. Divide the elements of the matrices
e. Perform matrix multiplication
f. Display transpose of the matrix
g. Sum of diagonal elements of a matrix
import numpy as np
matrix1 = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
matrix_sum = matrix1 + matrix2
matrix_diff = matrix1 - matrix2
matrix_product = matrix1 * matrix2
matrix_divide = matrix1 / matrix2
matrix_multiply = [Link](matrix1, matrix2)
matrix1_transpose = [Link](matrix1)
diagonal_sum = [Link](matrix1)
print("Matrix 1:\n", matrix1)
print("Matrix 2:\n", matrix2)
print("Matrix Sum:\n", matrix_sum)
print("Matrix Difference:\n", matrix_diff)
print("Matrix Element-wise Product:\n", matrix_product)
print("Matrix Element-wise Division:\n", matrix_divide)
print("Matrix Multiplication:\n", matrix_multiply)
print("Transpose of Matrix 1:\n", matrix1_transpose)
print("Sum of Diagonal Elements of Matrix 1:", diagonal_sum)
6
output
7
PROGRAM 3:
Write a program to display the elements of the matrix X to different powers and
identitymatrix of a given matrix .Also create another matrix Y with same dimensions
and display X 2+2Y
import numpy as np;
X = [Link]([[1, 2],
[3, 4]])
Y = [Link]([[5,6], [7,8]])
print("Matrix X is :\n ",X)
print("Matrix Y is : \n",Y)
a=[Link](X,2)
print("X^2=",a)
result = a + 2 * Y
print("X^2+2*Y is \n ",result)
output
8
PROGRAM 4:
Create a 2 Dimensional array with 4 rows and 4 columns.
a. Display all elements excluding the first row
b. Display all elements excluding the last column
c. Display the elements of 1stand 2nd column in 2ndand 3rdrow
d. Display the elements of 2 nd and 3 rd column
e. Display 2 nd and 3 rd element of 1 st row
f. Display the elements from indices 4 to 10 in descending order
import numpy as np
two_dimensional_array = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
excluding_first_row = two_dimensional_array[1:]
excluding_last_column = two_dimensional_array[:, :-1]
column_1_2_in_row_2_3 = two_dimensional_array[1:3, 0:2]
column_2_3 = two_dimensional_array[:, 1:3]
elements_2_3_in_first_row = two_dimensional_array[0, 1:3]
descending_order = two_dimensional_array.ravel()[::-1][4:11]
print("Original 2D array:\n", two_dimensional_array)
print("Elements excluding the first row:\n", excluding_first_row)
print("Elements excluding the last column:\n", excluding_last_column)
print("Elements of the 1st and 2nd column in the 2nd and 3rd row:\n",
column_1_2_in_row_2_3)
print("Elements of the 2nd and 3rd column:\n", column_2_3)
print("2nd and 3rd element of the 1st row:\n", elements_2_3_in_first_row)
print("Elements from indices 4 to 10 in descending order:\n", descending_order)
9
output
10
PROGRAM 5:
Given a matrix-vector equation AX=b. Write a program to find out the value of X using solve(), given
A and b as below
import numpy as np
A = [Link]([[2, 1,-2],[3,0,1],[1,1,-1]])
b = [Link]([-3,5,-2])
X = [Link](A, b)
print("Matrix A:")
print(A)
print("Vector b:")
print(b)
print("Solution for X:")
print(X)
Output
11
Matplotlib
Matplotlib is a low level graph plotting library in python that serves as a visualization utility.
2) Bar Plot
import [Link] as plt
categories = ['A', 'B', 'C', 'D', 'E']
values = [4, 7, 1, 8, 5]
[Link](categories, values) # Create a bar plot
# Add labels and title
[Link]('Categories')
[Link]('Values')
[Link]('Simple Bar Plot')
[Link]()
12
# Create bar plot
[Link]
categories = ['A', 'B', 'C', 'D']
values = [5, 7, 3, 8]
[Link](categories, values, color='purple')# Create bar plot
[Link]('Bar Plot')
[Link]('Categories')
[Link]('Values')
[Link]()
3) Histogram
import [Link] asplt
importnumpyas np
data = [Link](1000) #data=[Link](0,1,1000)
#[Link]() is a NumPy function that returns samples from the "standard
# normal" distribution. Mean (μ) = 0&Standard deviation (σ) = 1
[Link](data, bins=30, color='blue', edgecolor='black')
#bins=30: No: of bins (or bars) in the histogram.
#color='blue': Color of the bars
#edgecolor='black': Color of the edges (borders) of the bars to black
[Link]('Histogram')
[Link]('Value')
[Link]('Frequency')
[Link]()
13
4) Scatter Plot
import [Link] asplt
x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y = [99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86]
[Link](x, y, color='red')
[Link]('Scatter Plot')
[Link]('X-axis')
[Link]('Y-axis')
[Link]()
5) Pie Chart
import [Link] asplt
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True,
startangle=140)
[Link]('Pie Chart')
[Link]('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
[Link]()
14
6) Box Plot
import [Link] as plt
import numpy as np
# Sample data
data = [[Link](0, std, 100) for std in range(1, 4)]
# [Link](0, std, 100) - [Link](mean, std deviation,size)
# for std in range(1, 4) – list comprehension that iterates over a range of values ie, 1,2,3
15
7) Scatter Multiple
import [Link]
# Data for the first scatter plot
x1 = [1, 2, 3, 4, 5]
y1 = [2, 3, 4, 5, 6]
# Data for the second scatter plot
x2 = [2, 3, 4, 5, 6]
y2 = [3, 4, 5, 6, 7]
# Data for the third scatter plot
x3 = [1, 3, 4, 7, 8]
y3 = [5, 3, 8, 3, 5]
# Plotting the first scatter plot
[Link](x1, y1, color='red', label='Dataset 1')
# Plotting the second scatter plot
[Link](x2, y2, color='blue', label='Dataset 2')
# Plotting the third scatter plot
[Link](x3, y3, color='green', label='Dataset 3')
# Adding labels and title
[Link]('X-axis label')
[Link]('Y-axis label')
[Link]('Multiple Scatter Plots')
[Link]() # Adding a legend
[Link]()
8) Bubble Chart - A type of scatter plot where each point has an additional
third dimension represented by the size of the bubble
# Creating a bubble chart
import [Link]
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 8, 7]
sizes = [100, 200, 300, 400, 500] # Bubble sizes
[Link](x, y, s=sizes, alpha=0.5, c='blue')
# Adding labels and title
[Link]('X-axis Label')
[Link]('Y-axis Label')
[Link]('Bubble Chart Example')
[Link]()
16
#Bubble chart
import [Link] as plt
# Sample data with an additional dimension for colors
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 8, 7]
sizes = [100, 200, 300, 400, 500]
colors = [20, 30, 40, 50, 60] # Color dimension
# Creating a bubble chart with varying colors
[Link](x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')
[Link](label='Color scale')# Adding a color bar
[Link]('X-axis Label')
[Link]('Y-axis Label')
[Link]('Bubble Chart with Color Dimension')
[Link]()
17
9) Subplots
import [Link] as plt
import numpy as np
# Sample data
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)
# Create a figure with 2 subplots (vertically stacked)
fig, axs = [Link](2, 1, figsize=(8, 8))
# First subplot
axs[0].plot(x, y1, 'b')
axs[0].set_title('Sine Function')
axs[0].set_ylabel('sin(x)')
# Second subplot
axs[1].plot(x, y2, 'r')
axs[1].set_title('Cosine Function')
axs[1].set_ylabel('cos(x)')
axs[1].set_xlabel('x')
plt.tight_layout()# Adjust layout to prevent overlap
[Link]()
18
PROGRAM 7 : Sarah bought a new car in 2001 for $24000. The dollar value of her
car changed each year as shown in the table below.
represent the following information using a line graph with following style properties
• X-axis – year
• Y-axis – car value
• Title – value depreciation (left aligned)
• Line style dash dot & line color should be red
• Point using * symbol with green color & size 20
import [Link] as plt
years = [2001, 2002, 2003, 2004, 2005, 2006, 2007]
car_values = [24000, 22500, 19700, 17500, 14500, 10000, 5800]
[Link](figsize=(10, 6))
[Link](111)
[Link](years, car_values, linestyle='-', color='red', marker='*', markersize=20,
markerfacecolor='green')
[Link](" \nMCA 2023-2025", loc="right")
[Link]("Value Depreciation", loc="left")
[Link]("Year")
[Link]("Car Value")
[Link]()
19
PROGRAM 8: Create scatter plot for the below data (use scatter function)
Create scatter plot for each segment with following properties within one graph
20
PROGRAM 9: Following table gives the daily sales of the following items in a shop.
Use subplot function to draw the line graphs with grids (color as blue & line style dotted) for
the above information as 2 separate graphs in 2 rows
a) Properties for the graph1:
• X label – days of week
• Y label – Sale of drinks
• Title – sales data1 (right aligned)
• Line – dotted with cyan color
• Points – hexagon shape with color magenta & outline black
b) Properties for the graph2:
• X label – days of week
• Y label – Sale of food
• Title – sales data2 (center aligned)
• Line – dashed with yellow color
• Points – diamond shape with color green & outline red
import [Link] as plt
days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri']
drinks_sales = [300, 450, 150, 400, 650]
food_sales = [400, 500, 350, 300, 500]
fig, axs = [Link](2, 1, figsize=(8, 8))
axs[0].plot(days, drinks_sales, linestyle='--', color='cyan', marker='H',
markersize=8,markerfacecolor='magenta', markeredgecolor='black')
axs[0].set_xlabel('Days of Week')
axs[0].set_ylabel('Sale of Drinks')
axs[0].set_title('Sales Data1', loc='right')
axs[0].set_title('MCA 2023-2025', loc='left')
axs[0].grid(True, color='blue', linestyle='dotted')
axs[1].plot(days, food_sales, linestyle='-', color='yellow', marker='D', markersize=8,
markerfacecolor='green', markeredgecolor='red')
axs[1].set_xlabel('Days of Week')
axs[1].set_ylabel('Sale of Food')
axs[1].set_title('Sales Data2', loc='center')
axs[1].grid(True, color='blue', linestyle='dotted')
plt.tight_layout()
[Link]()
21
Pandas
Pandas is a Python library used for working with data [Link] has functions
for analyzing, cleaning, exploring, and manipulating data.
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
Pandas allow us to analyze big data and make conclusions based on
statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science
A Pandas DataFrame is a 2 dimensional data structure, like a 2
dimensional array, or a table with rows and columns.
PROGRAM 10: Write programs to perform basic operations using pandas
#Import necessary modules
import numpy as np
import pandas as pd
#Creating a dataframe using List: DataFrame can be created using
#a single list or a list of lists.
data = {'Name':['Tom', 'nick', 'krish', 'jack'],'Age':[20, 21, 19, 18]}
df = [Link](data) # Convert the dictionary into DataFram
print(df)
Name Age
0 Tom 20
1 nick 21
2 krish 19
3 jack 18
22
Name Qualification
0 Jai Msc
1 Princi MA
2 Gaurav MCA
3 AnujPhd
data = pd.read_csv("/content/[Link]")
[Link]()
<class '[Link]'>
RangeIndex: 33 entries, 0 to 32
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 EMPLOYEE_ID 22 non-null float64
1 NAME 22 non-null object
2 EMAIL 23 non-null object
3 PHONE_NUMBER 22 non-null object
4 HIRE_DATE 22 non-null object
5 DESIGNATION 22 non-null object
6 SALARY 22 non-null float64
7 MANAGER_ID 22 non-null object
8 DEPARTMENT_ID 22 non-null float64
dtypes: float64(3), object(6)
memory usage: 2.4+ KB
[Link]()
23
import pandas as pd
import numpy as np
arr=[Link]([10,15,18,22])
s = [Link](arr)
print(s)
0 10
1 15
2 18
3 22
dtype: int64
arr=[Link](['a','b','c','d'])
s=[Link](arr, index=['first','second','third','fourth'])
print(s)
first a
second b
third c
fourth d
dtype: object
s=[Link](50, index=[0, 1, 2, 3, 4])
print (s)
0 50
1 50
2 50
3 50
4 50
dtype: int64
#Creating a series from a Dictionary
d={'Name': 'Deepthi', 'Class' : 'MCA', 'year' : 2014}
s=[Link](d)
print(s)
Name Deepthi
Class MCA
year 2014
dtype: object
#To Add & Rename a column in data frame
s = [Link]([10,15,18,22])
df=[Link](s)
[Link]=['List1']
#To Rename the default column of Data Frame as List1
df['List2']=20
#To create a new column List2 with all values as 20
df['List3']=df['List1']+df['List2']
#Add Column1 and Column2 and store in New column List3
print(df)
24
import pandas as pd
import numpy as np
import [Link] as plt
[Link](0)
values = [Link](100)
s = [Link](values) # generate a pandas series
print("series\n",s)
[Link](kind='hist', title='Normally distributed random values')
[Link]()
series
0 1.764052
1 0.400157
2 0.978738
3 2.240893
4 1.867558
...
95 0.706573
96 0.010500
97 1.785870
98 0.126912
99 0.401989
Length: 100, dtype: float64
[Link]()
count 100.000000
mean 0.059808
std 1.012960
min -2.552990
25% -0.643857
50% 0.094096
75% 0.737077
max 2.269755
dtype: float64
25
df = [Link]({'A': [1, 2, 1, 4, 3],
'B': [12, 14, 11, 16, 18],
'C': ['a', 'a', 'b', 'a', 'b']})
df
[Link]()
26
9 10 4.9 3.1 1.5 0.1 Iris-
setosa
10 11 7.0 3.2 4.7 1.4 Iris-
versicolor
11 12 6.4 3.2 4.5 1.5 Iris-
versicolor
12 13 6.9 3.1 4.9 1.5 Iris-
versicolor
13 14 5.5 2.3 4.0 1.3 Iris-
versicolor
14 15 6.5 2.8 4.6 1.5 Iris-
versicolor
15 16 5.7 2.8 4.5 1.3 Iris-
versicolor
16 17 6.3 3.3 4.7 1.6 Iris-
versicolor
17 18 4.9 2.4 3.3 1.0 Iris-
versicolor
18 19 6.6 2.9 4.6 1.3 Iris-
versicolor
19 20 5.2 2.7 3.9 1.4 Iris-
versicolor
20 21 6.3 3.3 6.0 2.5 Iris-
virginica
21 22 5.8 2.7 5.1 1.9 Iris-
virginica
22 23 7.1 3.0 5.9 2.1 Iris-
virginica
23 24 6.3 2.9 5.6 1.8 Iris-
virginica
24 25 6.5 3.0 5.8 2.2 Iris-
virginica
25 26 7.6 3.0 6.6 2.1 Iris-
virginica
26 27 4.9 2.5 4.5 1.7 Iris-
virginica
27 28 7.3 2.9 6.3 1.8 Iris-
virginica
28 29 6.7 2.5 5.8 1.8 Iris-
virginica
29 30 7.2 3.6 6.1 2.5 Iris-
virginica
27
import pandas as pd
df = [Link](pd.read_csv("/content/Iris_new.csv"))
# create histogram for numeric data
[Link]()
Output
array([[<Axes: title={'center': 'Id'}>, <Axes: title={'center':
'SepalLength'}>], [<Axes: title={'center': 'SepalWidth'}>, <Axes:
title={'center': 'PetalLength'}>], [<Axes: title={'center':
'PetalWidth'}>, <Axes: >]], dtype=object)
iris['SepalLength'].hist()
import pandas as pd
import numpy as np
import [Link] as plt
# Load Housing Price dataset
data = pd.read_csv ('/content/sample_data/california_housing_test.csv')
# Exploratory Data Analysis
[Link]()
[Link]()
[Link]()
28
• matplotlib is a foundational plotting library for Python that provides extensive
control over the appearance of plots. It’s a general-purpose plotting library and is
widely used for creating static, animated, and interactive visualizations.
• seaborn is a statistical data visualization library built on top of matplotlib. It
provides a high-level interface for creating attractive and informative statistical graphics
with simpler syntax.
29
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
# Load Housing Price dataset
data = pd.read_csv ('/content/sample_data/
california_housing_test.csv')
# Scatter Plot
[Link](figsize=(10, 8))
[Link](x='median_house_value', y='housing_median_age',
data=data)
[Link]('Scatter Plot for Median House Value vs. Housing Median Age')
[Link]('Median House Value')
[Link]('Housing Median Age')
[Link]()
# Box Plot
[Link](figsize=(15, 10))
[Link](x='housing_median_age', y='median_house_value', data=data)
[Link]('Box Plot for Feature1 by Target')
[Link]()
30
Program 11: Dataset: <Breast_Cancer.csv>
a) Conduct exploratory data analysis on the given dataset and report the
details.
b) Visualize the analysis results using
(i) scatter plot (ii) histogram & (iii) box plot
c) Implement the k-NN classification algorithm using the dataset. Try with
different k values and show the accuracy.
#a) exploratory data analysis
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
from [Link] import load_breast_cancer
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from sklearn import metrics
# Load the Breast Cancer dataset
data = load_breast_cancer()
df = [Link]([Link], columns=data.feature_names)
df['target'] = [Link]
print([Link](5))
[Link]()
mean radius mean texture mean perimeter mean area mean smoothness \
0 17.99 10.38 122.80 1001.0 0.11840
1 20.57 17.77 132.90 1326.0 0.08474
2 19.69 21.25 130.00 1203.0 0.10960
3 11.42 20.38 77.58 386.1 0.14250
4 20.29 14.34 135.10 1297.0 0.10030
mean fractal dimension ... worst texture worst perimeter worst area \
0 0.07871 ... 17.33 184.60 2019.0
1 0.05667 ... 23.41 158.80 1956.0
2 0.05999 ... 25.53 152.50 1709.0
3 0.09744 ... 26.50 98.87 567.7
4 0.05883 ... 16.67 152.20 1575.0
31
[5 rows x 31 columns]
<class '[Link]'>
RangeIndex: 569 entries, 0 to 568
Data columns (total 31 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 mean radius 569 non-null float64
1 mean texture 569 non-null float64
2 mean perimeter 569 non-null float64
3 mean area 569 non-null float64
4 mean smoothness 569 non-null float64
5 mean compactness 569 non-null float64
6 mean concavity 569 non-null float64
7 mean concave points 569 non-null float64
8 mean symmetry 569 non-null float64
9 mean fractal dimension 569 non-null float64
10 radius error 569 non-null float64
11 texture error 569 non-null float64
12 perimeter error 569 non-null float64
13 area error 569 non-null float64
14 smoothness error 569 non-null float64
15 compactness error 569 non-null float64
16 concavity error 569 non-null float64
17 concave points error 569 non-null float64
18 symmetry error 569 non-null float64
19 fractal dimension error 569 non-null float64
20 worst radius 569 non-null float64
21 worst texture 569 non-null float64
22 worst perimeter 569 non-null float64
23 worst area 569 non-null float64
24 worst smoothness 569 non-null float64
25 worst compactness 569 non-null float64
26 worst concavity 569 non-null float64
27 worst concave points 569 non-null float64
28 worst symmetry 569 non-null float64
29 worst fractal dimension 569 non-null float64
30 target 569 non-null int64
dtypes: float64(30), int64(1)
memory usage: 137.9 KB
print([Link])
<bound method [Link] of mean radius mean texture mean perimeter mean area
mean smoothness \
0 17.99 10.38 122.80 1001.0 0.11840
1 20.57 17.77 132.90 1326.0 0.08474
2 19.69 21.25 130.00 1203.0 0.10960
3 11.42 20.38 77.58 386.1 0.14250
4 20.29 14.34 135.10 1297.0 0.10030
.. ... ... ... ... ...
564 21.56 22.39 142.00 1479.0 0.11100
565 20.13 28.25 131.20 1261.0 0.09780
566 16.60 28.08 108.30 858.1 0.08455
567 20.60 29.33 140.10 1265.0 0.11780
568 7.76 24.54 47.92 181.0 0.05263
32
567 0.27700 0.35140 0.15200 0.2397
568 0.04362 0.00000 0.00000 0.1587
mean fractal dimension ... worst texture worst perimeter worst area \
0 0.07871 ... 17.33 184.60 2019.0
1 0.05667 ... 23.41 158.80 1956.0
2 0.05999 ... 25.53 152.50 1709.0
3 0.09744 ... 26.50 98.87 567.7
4 0.05883 ... 16.67 152.20 1575.0
.. ... ... ... ... ...
564 0.05623 ... 26.40 166.10 2027.0
565 0.05533 ... 38.25 155.00 1731.0
566 0.05648 ... 34.12 126.70 1124.0
567 0.07016 ... 39.42 184.60 1821.0
568 0.05884 ... 30.37 59.16 268.6
33
worst area 0
worst smoothness 0
worst compactness 0
worst concavity 0
worst concave points 0
worst symmetry 0
worst fractal dimension 0
target 0
dtype: int64
mean radius mean texture mean perimeter mean area \
count 569.000000 569.000000 569.000000 569.000000
mean 14.127292 19.289649 91.969033 654.889104
std 3.524049 4.301036 24.298981 351.914129
min 6.981000 9.710000 43.790000 143.500000
25% 11.700000 16.170000 75.170000 420.300000
50% 13.370000 18.840000 86.240000 551.100000
75% 15.780000 21.800000 104.100000 782.700000
max 28.110000 39.280000 188.500000 2501.000000
34
max 0.207500 1.000000
[8 rows x 31 columns]
target
1 357
0 212
Name: count, dtype: int64
#b) Visualization
# (i) Scatter plot
[Link](figsize=(8, 6))
[Link](x='mean radius', y='mean texture', hue='target', data=df)
[Link]("Scatter plot of Mean Radius vs Mean Texture")
[Link]()
# (ii) Histogram
[Link](figsize=(8, 6))
df['mean radius'].hist(bins=30)
[Link]("Histogram of Mean Radius")
[Link]("Mean Radius")
[Link]("Frequency")
[Link]()
35
#c) Implementing k-NN Classification
# Splitting the dataset into training and testing sets
X = [Link]('target', axis=1) # Features
y = df['target'] # Target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)
# Testing k-NN with different values of k
k_values = [3, 5, 7, 9]
for k in k_values:
knn = KNeighborsClassifier(n_neighbors=k)
[Link](X_train, y_train)
y_pred = [Link](X_test)
accuracy = metrics.accuracy_score(y_test, y_pred)# Calculate accuracy
print(f"Accuracy with k={k}: {accuracy:.4f}")
Accuracy with k=3: 0.9415
Accuracy with k=5: 0.9591
Accuracy with k=7: 0.9649
Accuracy with k=9: 0.9708
36
Program 12: Dataset: <Wine_Quality.csv>
a) Conduct exploratory data analysis on the given dataset and
report the details.
b) Visualize the analysis results using (i) scatter plot (ii) histogram &
(iii) box plot.
c) Implement the k-NN classification algorithm using the dataset.
Try with different K values and show the accuracy.
# a) exploratory data analysis
import pandas as pd
# Load the Wine Quality dataset
df = pd.read_csv('/content/Wine_Quality.csv')
print([Link]()) # Check the first few rows
print([Link]().sum()) # Check for missing values
print([Link]()) # Summary statistics of the dataset
# Target variable distribution (if the dataset contains quality classes)
print(df['quality'].value_counts())
type fixed acidity volatile acidity citric acid residual sugar \
0 white 7.0 0.27 0.36 20.7
1 white 6.3 0.30 0.34 1.6
2 white 8.1 0.28 0.40 6.9
3 white 7.2 0.23 0.32 8.5
4 white 7.2 0.23 0.32 8.5
37
min 0.009000 1.000000 6.000000 0.987110
25% 0.038000 17.000000 77.000000 0.992340
50% 0.047000 29.000000 118.000000 0.994890
75% 0.065000 41.000000 156.000000 0.996990
max 0.611000 289.000000 440.000000 1.038980
# (ii) Histogram
[Link](figsize=(8, 6))
df['alcohol'].hist(bins=30)
[Link]("Histogram of Alcohol")
[Link]("Alcohol")
[Link]("Frequency")
[Link]()
38
# Box plot
[Link](figsize=(8, 6))
[Link](x='quality', y='alcohol', data=df)
[Link]("Box plot of Alcohol grouped by Quality")
[Link]()
39
Accuracy with k=3: 0.5538
Accuracy with k=5: 0.5584
Accuracy with k=7: 0.5313
Accuracy with k=9: 0.5445
Accuracy with k=11: 0.5491
Accuracy with k=13: 0.5483
Accuracy with k=15: 0.5429
k_values_input = input("Enter k values : ")# user to input k values from the console
# Convert the input string into a list of integers
k_values = [int ([Link]()) for k in k_values_input.split(',')]
for k in k_values:
knn = KNeighborsClassifier(n_neighbors=k)
[Link](X_train_scaled, y_train)
y_pred = [Link](X_test_scaled) # Predict on the test set
accuracy = accuracy_score(y_test, y_pred) # Calculate accuracy
print(f"Accuracy with k={k}: {accuracy:.4f}")
Enter k values separated by commas (e.g., 3,5,7): 3
Accuracy with k=3: 0.5538
40
Program 13: Dataset: <Breast_Cancer.csv>
41
mean 880.583128 0.132369 0.254265 0.272188
std 569.356993 0.022832 0.157336 0.208624
min 185.200000 0.071170 0.027290 0.000000
25% 515.300000 0.116600 0.147200 0.114500
50% 686.500000 0.131300 0.211900 0.226700
75% 1084.000000 0.146000 0.339100 0.382900
max 4254.000000 0.222600 1.058000 1.252000
42
(c): Implementing Naïve Bayes Classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from [Link] import classification_report, accuracy_score
# [Link]() - In Pandas to remove rows (or columns) that contain missing
# values from a DataFrame
df_cleaned = [Link]()
# Define features (X) and target (y)
X = df_cleaned.drop(['diagnosis'], axis=1) # Exclude 'diagnosis' for features
y = df_cleaned['diagnosis'] # 'diagnosis' is the target variable
# Split the data into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
nb = GaussianNB() # Initialize the Naïve Bayes classifier
[Link](X_train, y_train) # Train the model
y_pred = [Link](X_test) # Predict on the test set
# Display the classification report and accuracy
print("Classification Report:\n", classification_report(y_test, y_pred))
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f }")
Classification Report:
precision recall f1-score support
B 0.62 0.99 0.76 71
M 0.00 0.00 0.00 43
accuracy 0.61 114
macro avg 0.31 0.49 0.38 114
weighted avg 0.39 0.61 0.47 114
Accuracy: 0.6140
Program 14: Dataset: <Wine_Quality.csv>
43
a) Conduct exploratory data analysis on the given dataset and report
the details.
b) Visualize the analysis results using (i) histogram and (ii) box plot.
c) Implement the Naïve Bayes classification algorithm using the
dataset. Display the classification report with the accuracy.
# a) Conduct Exploratory Data Analysis (EDA)
import pandas as pd
df = pd.read_csv('/content/Wine_Quality.csv') # Load the Wine Quality dataset
print([Link]()) # Check the first few rows
print([Link]().sum()) # Check for missing values
print([Link]()) # Summary statistics of the dataset
print(df['quality'].value_counts()) # Distribution of the target variable 'quality'
type fixed acidity volatile acidity citric acid residual sugar \
0 white 7.0 0.27 0.36 20.7
1 white 6.3 0.30 0.34 1.6
2 white 8.1 0.28 0.40 6.9
3 white 7.2 0.23 0.32 8.5
4 white 7.2 0.23 0.32 8.5
44
chlorides free sulfur dioxide total sulfur dioxide density \
count 6495.000000 6497.000000 6497.000000 6497.000000
mean 0.056042 30.525319 115.744574 0.994697
std 0.035036 17.749400 56.521855 0.002999
min 0.009000 1.000000 6.000000 0.987110
25% 0.038000 17.000000 77.000000 0.992340
50% 0.047000 29.000000 118.000000 0.994890
75% 0.065000 41.000000 156.000000 0.996990
max 0.611000 289.000000 440.000000 1.038980
#b) Visualizations
import [Link] as plt
import seaborn as sns
# (i) Histogram for a feature like 'alcohol'
[Link](figsize=(8, 6))
df['alcohol'].hist(bins=30)
[Link]("Histogram of Alcohol")
[Link]("Alcohol")
[Link]("Frequency")
[Link]()
# (ii) Box plot for 'alcohol' grouped by 'quality'
[Link](figsize=(8, 6))
[Link](x='quality', y='alcohol', data=df)
[Link]("Box plot of Alcohol grouped by Quality")
[Link]()
45
c) Implement Naïve Bayes Classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from [Link] import classification_report, accuracy_score
from [Link] import SimpleImputer # import the imputer
# Step 1: Convert 'quality' into binary class (e.g., good quality = 1 if quality >= 7, otherwise bad quality = 0)
df['quality_label'] = df['quality'].apply(lambda x: 1 if x >= 7 else 0)
# Step 2: Prepare features (X) and target (y)
# drop 'type', 'quality', and the newly created 'quality_label' for the features
X = [Link](columns=['type', 'quality', 'quality_label'])
y = df['quality_label']
# Step 3: Split the dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Step 4: Impute missing values using SimpleImputer
imputer = SimpleImputer(strategy='mean') # create an imputer object with strategy 'mean'
X_train = imputer.fit_transform(X_train) # fit and transform on the training data
X_test = [Link](X_test) # transform the test data
# Step 5: Train the Naive Bayes classifier
nb_model = GaussianNB()
nb_model.fit(X_train, y_train)
# Step 6: Make predictions on the test set
y_pred = nb_model.predict(X_test)
# Step 7: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
classification_rep = classification_report(y_test, y_pred)
# Output the results
print("Accuracy: {:.2f}%".format(accuracy * 100))
print("\nClassification Report:\n", classification_rep)
Accuracy: 77.85%
Classification Report:
precision recall f1-score support
46
Program 15: Dataset: <Breast_Cancer.csv>
47
b) Visualize the analysis results using (i) scatter plot (ii) histogram & (iii)
box plot.
c) Implement the K-Means clustering algorithm using the dataset. Try
with different k values and plot the elbow graph for the k values.
48