Record DataScience
Record DataScience
College of Engineering
NAME :
DEGREE: B.E
BRANCH/SEMESTER: / SEMESTER
REGISTER NO:
Certificate
This is a bonafide record of Practical work done by the above-mentioned
candidate in OCS353/ DATA SCIENCE FUNDAMENTALS LABORATORY
at University V.O.C. College of Engineering, Thoothukudi during the period Jan
2026 - April 2026
STATION: THOOTHUKUDI-8.
DATE:
1
Syllabus:
1. Download, install and explore the features of Python for data analytics.
2. Working with Numpy arrays
3. Working with Pandas data frames
4. Basic plots using Matplotlib
5. Statistical and Probability measures
a) Frequency distributions
b) Mean, Mode, Standard Deviation
c) Variability
d) Normal curves
e) Correlation and scatter plots
f) Correlation coefficient
g) Regression
6. Use the standard benchmark data set for performing the following:
a) Univariate Analysis: Frequency, Mean, Median, Mode, Variance,
Standard Deviation,
Skewness and Kurtosis.
b) Bivariate Analysis: Linear and logistic regression modelling.
7. Apply supervised learning algorithms and unsupervised learning
algorithms on any data set.
8. Apply and explore various plotting functions on any data set.
Note: Example data sets like: UCI, Iris, Pima Indians Diabetes etc.
2
Index
[Link] [Link] Date Name of the Experiment Page No
1 [Link] Download, install and explore the
features of Python for data 4
analytics
2 [Link]:2a Working with Numpy arrays 6
3 [Link]:2b Multi Dimensional arrays – Numpy 19
4 [Link]:2c Examples of Numpy arrays 24
5 [Link]:3a Working with Pandas Data frames 35
6 Ex.No3b Examples using Pandas 45
7 [Link] Basic plots using matplotlib 55
8 [Link]:5a Statistical and Probability measures
- Frequency 64
Distributions
9 [Link]:5b Statistical and Probability measures 67
- Mean, Mode, Standard Deviation
10 [Link]:5c Statistical and Probability measures
- Variability 73
11 [Link]:5d Statistical and Probability 74
measures- Normal curves
12 [Link]:5e Statistical and Probability 76
measures- scatter plots
13 [Link]:5f Statistical and Probability 79
measures- Correlation and Scatter
plot
14 [Link]:5g Statistical and Probability measures 81
- Regression
15 [Link]:6a Mean, Median, Mode, Variance, 83
Standard Deviation, Skewness and
Kurtosis
16 [Link]:6b Bivariant Analysis- Logistic 94
Regression
17 [Link]:7a Supervised Learning 98
18 [Link]:7b Unsupervised Learning 105
19 [Link] Various Plotting functions 114
20 [Link] Reading Files 121
21 [Link] Bivariate Analysis- Multiple 122
Regression
22 [Link] Histogram plot, Density Plot , 125
Contour Plot, 3D plot, Normal plot
3
[Link] Download, install and explore the features of Python for data
analytics
Date:
Aim: To Download, install and explore the features of Python for data
analytics
Procedure:
4. To install pandas
a. pip install pandas
5. In pyscripter- Under Tools option click install packages with pip and
install
a. matplotlib
b. numpy
c. pandas
6. Now in pyscripter the user can work python scripts with matplotlib,
numpy and pandas
4
7. Downloading UCI data sets – iris data set
a. Go to [Link]
b. Type UCI Machine Learning Repository
c. Click on data sets
d. Click on iris image
e. Click on download option – iris data set will be downloaded
as zip file
f. Extract the zip file to particular folder for your use
8. Downloading UCI data sets – Diabetics data set
a. Go to [Link]
b. Type UCI Machine Learning Repository
c. Click on data sets
d. Click on Diabetics image
e. Click on download option – Diabetics data set will be
downloaded as zip file
f. Extract the zip file to particular folder for your use
g. Diabetics data will be in .tar format
h. Once again extract it to specific folder for your use
9. Installing Anaconda :
1. [Link]
2. After download run anaconda-3-2023.9-0-windows-x86_64
3. Follow the steps as displayed in your screen
4. Anaconda will be automatically installed in
C:\users\home\anoconda3
5. Install by selecting only “create start menu shortcuts”
6. Close the sign in / sign up dialog box
7. Close Anaconda navigator
8. Open start in windows- all apps- click anaconda – click anaconda
9. Now all applications like R, Jupyter… etc can be executed
Example – open Jupyter notebook- click new- ipython kernal and work
with the experiments
Result: Thus Download, install and explore the features of Python for data
Analytics is completed and the system is ready for further experiments.
5
[Link]:2a Working with Numpy arrays
Data:
Aim: To work with Numpy arrays in python
Theory:
List: Built in data type
Collection of different data types
Enclosed inside []
Separated by comma
Mutable – changeable
Eg: a=[1,2.3,’x’,’abc’,”abc”]
Positions are a[0]=1 a[1]=2.3 a[2]=’x’ a[3]=[‘abc’] a[4]=”abc”
Tuple: Built in data type
Collection of different data types
Enclosed inside ()
Separated by comma
Immutable – not changable
Eg: a=(1,2.3,’x’,’abc’)
Positions are a[0]=1 a[1]=2.3 a[2]=’x’ a[3]=[‘abc’]
Numpy array:
A numpy array is a set of values
All of the same type
Indexed by a tuple of nonnegative integers.
The number of dimensions is the rank of the array
U32 data type:
The u32 stands for 32-bit unsigned integer type.
It is an unsigned integer
It cannot contain a negative value like signed integers.
The range of u32 is 0 to 4294967295 .
csv file:
A CSV is a comma-separated values file
Data can be saved in a tabular format.
CSVs look like a spreadsheet but with a . csv extension.
CSV files can be used with most any spreadsheet program, such as
Microsoft Excel or Google Spreadsheets.
Programs:
Program1: 1D array using numpy
import numpy as np
arr=[Link]([1,2,3])
print(arr)
Output:
[1 2 3]
6
Program2: explore data type in numpy array
import numpy as np
arr=[Link]([1,2.,3.])
print(arr)
Output:
[1. 2. 3.]
import numpy as np
arr=[Link]([[2,3.,5.],[1,2,3]])
print(arr)
Output:
[[2. 3. 5.]
[1. 2. 3.]]
import numpy as np
arr=[Link]([[1,2.,3.],[2,.3,5]])
print(arr)
print([Link])
Output:
[[1. 2. 3. ]
[2. 0.3 5. ]]
2
import numpy as np
arr=[Link]([1,2.,3],dtype=complex)
print(arr)
arr1=[Link]([4,5j,6+8j],dtype=complex)
print(arr1)
Output:
7
[1.+0.j 2.+0.j 3.+0.j]
[4.+0.j 0.+5.j 6.+8.j]
import numpy as np
arr=[Link]([Link]('1.,2;3,4'))
print(arr)
Output:
[[1. 2.]
[3. 4.]]
import numpy as np
L1=[1,2,3.2,'a',"xyz",'qwe']
print(L1)
L1[0]=10.9
arr=[Link](L1)
print(L1)
print(arr)
Output:
import numpy as np
L1=(1,2,3.2,'a',"xyz",'qwe')
print(L1)
arr=[Link](L1)
print(L1)
print(arr,[Link])
Output:
8
(1, 2, 3.2, 'a', 'xyz', 'qwe')
(1, 2, 3.2, 'a', 'xyz', 'qwe')
['1' '2' '3.2' 'a' 'xyz' 'qwe'] <U32
import numpy as np
Nc=[Link](10)
Nf=[Link](10)
n=int(input("Enter Total Centigrade or Celsius values"))
for i in range(0,n):
e=int(input("Enter Centigrade"))
Nc[i]=e
Nf[i]=Nc[i]*9/5+32
print(Nc)
print(Nf)
for i in range(0,n):
print(Nf[i])
Output:
import numpy as np
Nc=[Link](10)
Nf=[Link](10)
n=int(input("Enter Total Fahrenheit values"))
for i in range(0,n):
e=float(input("Enter Fahrenheit"))
Nf[i]=e
Nc[i]=(Nf[i]-32)*5/9
print(Nc)
print(Nf)
9
for i in range(0,n):
print(Nf[i])
Output:
import numpy as np
NP=[Link](10)*1j
n=int(input("Enter Total values"))
for i in range(0,n):
r=float(input("Enter real part"))
im=float(input("Enter imaginary part"))
NP[i]=r+im*1j
for i in range(0,n):
print(NP[i].real,NP[i].imag)
NP=[Link]([1.+5*1j,2.3+6*1j],dtype="complex")
print(NP, [Link], [Link])
Output:
10
Program11a: find Real and imaginary parts of complex numbers
Output:
import numpy as np
a = [Link]([23,34,65,78,45,90])
print("The created array:",a)
csv_data = [Link]("[Link]",a,delimiter = ",")
print("array converted into csv file")
data_csv = [Link]("[Link]",delimiter = ",")
print("The data from the csv file:",data_csv)
11
Output:
import numpy as np
a = [Link]([5, 72, 13, 100])
b = [Link]([2, 5, 10, 30])
# Performing addition using arithmetic operator
add_ans = a+b
print(add_ans)
# Performing addition using numpy function
add_ans = [Link](a, b)
print(add_ans)
# this would work
c = [Link]([1, 2, 3, 4])
add_ans = a+b+c
print(add_ans)
# but here NumPy only considers the first two arrays (a and b) and ignores th
e third one (c).
add_ans = [Link](a, b, c)
print(add_ans)
Output:
[ 7 77 23 130]
[ 7 77 23 130]
[ 8 79 26 134]
[ 7 77 23 130]
import numpy as np
a = [Link]([5, 72, 13, 100])
b = [Link]([2, 5, 10, 30])
# Performing subtraction using arithmetic operator
sub_ans = a-b
print(sub_ans)
# Performing subtraction using numpy function
12
sub_ans = [Link](a, b)
print(sub_ans)
Output:
[ 3 67 3 70]
[ 3 67 3 70]
[ 2 66 2 69]
[ 2 66 2 69]
import numpy as np
Output:
import numpy as np
13
print(div_ans)
# Performing division using numpy functions
div_ans = [Link](a, b)
print(div_ans)
Output:
import numpy as np
Output:
[ 1 2 3 10]
[ 1 2 3 10]
import numpy as np
Output:
14
[ 25 1934917632 419538377 0]
[2.50000000e+01 1.93491763e+09 1.37858492e+11 1.00000000e+60]
import numpy as np
Output:
47.5
11.75
190
119.1875
import numpy as np
Output:
[[1 2]
[3 4]]
15
[[1 3]
[2 4]]
import pandas as pd
import numpy as np
# create a dummy array
arr = [Link](1,11).reshape(2,5)
# display the array
print(arr)
# convert array into dataframe
DF = [Link](arr)
# save the dataframe as a csv file
DF.to_csv("[Link]")
df=pd.read_csv("[Link]")
print(df)
df=pd.read_csv("D:\college misellaneous\Lab2023EvenSem\[Link]")
print(df)
Output:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
Unnamed: 0 0 1 2 3 4
0 0 1 2 3 4 5
1 1 6 7 8 9 10
5.1 3.5 1.4 0.2 Iris-setosa
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa
.. ... ... ... ... ...
144 6.7 3.0 5.2 2.3 Iris-virginica
145 6.3 2.5 5.0 1.9 Iris-virginica
146 6.5 3.0 5.2 2.0 Iris-virginica
147 6.2 3.4 5.4 2.3 Iris-virginica
148 5.9 3.0 5.1 1.8 Iris-virginica
16
import numpy as np
arr = [Link]([3, 2, 0, 1])
print([Link](arr))
Output:
[0 1 2 3]
import numpy as np
arr = [Link](['banana', 'cherry', 'apple'])
print([Link](arr))
Output:
import numpy as np
arr = [Link]([True, False, True])
print([Link](arr))
Output:
import numpy as np
arr = [Link]([[3, 2, 4], [5, 0, 1]])
print([Link](arr))
Output:
[[2 3 4]
[0 1 5]]
17
Program26: Sort array using numpy (using axis)
In a two-dimensional vector, the elements of axis 1 are rows and the elements
of axis 0 are columns.
# importing libraries
import numpy as np
# sort along the first axis (columnwise)
a = [Link]([[12, 15],
[10, 1]])
arr1 = [Link](a, axis = 0)
print ("Along first axis (columnwise) : \n", arr1)
# sort along the first axis (rowwise)
a = [Link]([[12, 15],
[10, 1]])
arr1 = [Link](a, axis = 1)
print ("Along first axis (rowwise) : \n", arr1)
a = [Link]([[12, 15], [10, 1]])
arr1 = [Link](a, axis = None)
print ("\nAlong none axis : \n", arr1)
Output:
Along first axis (columnwise) :
[[10 1]
[12 15]]
Along first axis (rowwise) :
[[12 15]
[ 1 10]]
Along none axis :
[ 1 10 12 15]
Result: Thus the python coding to perform basic arithmetic operations using
numpy , sorting using numpy are executed and the results are verified.
18
[Link]:2b Multi Dimensional arrays – Numpy
Date:
Theory:
NumPy arrays are called ndarray objects. The nd stands for "N-dimensional",
which is indicates that an array can have any numbers of dimensions. A 1D
array is like a list, because you need only a single coordinate (or index) to
indicate an element. A 2D array is like a spreadsheet, because you need two
coordinates (a row and a column, or an X and a Y coordinate) to indicate an
element. Higher-dimensional arrays are also possible, although arrays of more
than three dimensions are difficult to mentally picture. (But this is a limitation
of your brain, not of NumPy!)
Data types
A NumPy array has a single data type (its dtype), and all elements in the array
are of that type. This is different from a list object, which can contain elements
of different types. The most common data types for NumPy arrays
are bool, int, float, and str.
Creating an array
First, we're going to import numpy with the alias np . The np alias is by
convention, and has the advantage that it requires less typing than numpy.
import numpy as np
shape=(2,3,4,5,6)
fiveDarr=[Link](shape)
print(fiveDarr)
print("Array Dimension",[Link])
print("Total elements in array",[Link])
19
Output:
[[[[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]
[[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
20
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]
[[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]]
[[[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
21
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]
[[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]
[[[0. 0. 0. 0. 0. 0.]
22
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]]]]
Array Dimension 5
Total elements in array 720
Result:Thus the python program to create, display the 5D array, display the
dimension, display total number of elements is executed and the result is
verified.
23
[Link]:2c Examples of Numpy arrays
Date:
Output:
24
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Update sixth value to 11
[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]
import numpy as np
# Example NumPy array (integer)
integer_array = [Link]([100, 200, 300, 400, 500])
# In-place conversion to float
integer_array = integer_array.astype(float)
print("Converted Array (Float):", integer_array)
Output:
Program: NumPy program to create a 3x3 matrix with values ranging from 2 to
10
Program:
25
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'x' using arange() from 2 to 11 and reshaping it int
o a 3x3 matrix
x = [Link](2, 11).reshape(3, 3)
# Printing the resulting 3x3 matrix 'x'
print(x)
Output:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
Program:
26
# Creating a NumPy array 'a' from the Python list 'l'
a = [Link](L)
# Printing the one-dimensional NumPy array 'a'
print("One-dimensional NumPy array: ", a)
Output:
Code:
import numpy as np
Output1:
Output2:
To create a full NumPy array, you can use the [Link]() function.
The full() function in NumPy creates an array of a given shape and fills it with a
specified value. A full NumPy array is an array where all the elements have the
27
same predefined value. This is useful when you want to initialize an array with a
specific value.
Code:
import numpy as np
Output:
[[5 5 5 5]
[5 5 5 5]
[5 5 5 5]]
import numpy as np
tuple1=(3,5,6)
print(tuple1)
L1=list(tuple1)
print(L1)
n1=[Link](L1)
print(n1)
Output:
(3, 5, 6)
[3, 5, 6]
[3 5 6]
28
print("Original arrays:")
print(x)
print(y)
# Counting the number of instances where x equals 10 and y is greater than 0.5
result = [Link]((x == 10) & (y > 0.5))
Output:
Original arrays:
[ 10 -10 10 -10 -10 10]
[0.85 0.45 0.9 0.8 0.12 0.6 ]
Number of instances of a value occurring in one array on the condition of
another array:
3
Output:
29
[2 1 2]]
Type: <class '[Link]'>
Sequence: 1,2
Number of occurrences of the said sequence: 2
Output:
Original arrays:
[[0.93635602 0.15110479]
[0.04689042 0.45330315]]
[[0.5648459 0.62626609]
[0.94375379 0.78884622]]
[[0.13426734 0.34890327]
[0.79431519 0.77580322]]
After concatenate:
[[0.93635602 0.15110479 0.5648459 0.62626609 0.13426734 0.34890327]
[0.04689042 0.45330315 0.94375379 0.78884622 0.79431519 0.77580322]]
30
array1 = ['PHP', 'JS', 'C++']
array2 = ['Python', 'C#', 'NumPy']
# Printing the original arrays
print("Original arrays:")
print(array1)
print(array2)
# Combining the arrays using np.r_
result = np.r_[array1[:-1], [array1[-1] + array2[0]], array2[1:]]
# Printing the combined result
print("\nAfter Combining:")
print(result)
Output:
Original arrays:
['PHP', 'JS', 'C++']
['Python', 'C#', 'NumPy']
After Combining:
['PHP' 'JS' 'C++Python' 'C#' 'NumPy']
Output:
Original array:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
31
0 on the border and 1 inside in the array
[[0. 0. 0. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 0. 0. 0.]]
Output:
Original array:
[10, 20, 30]
After append values to the end of the array:
[10 20 30 40 50 60 70 80 90]
32
}"""
Output:
Original dictionary:
{'column0': {'a': 1, 'b': 0.0, 'c': 0.0, 'd': 2.0}, 'column1': {'a': 3.0, 'b': 1, 'c': 0.0, 'd':
-1.0}, 'column2': {'a': 4, 'b': 1, 'c': 5.0, 'd': -1.0}, 'column3': {'a': 3.0, 'b': -
1.0, 'c': -1.0, 'd': -1.0}}
Type: <class 'dict'>
ndarray:
[[ 1. 0. 0. 2.]
[ 3. 1. 0. -1.]
[ 4. 1. 5. -1.]
[ 3. -1. -1. -1.]]
Type: <class '[Link]'>
33
print(np_array)
print("Searched array:")
print(test_array)
# Finding the index of the searched array in the original array
# Using [Link]() to locate rows where all elements match the test_array
result = [Link]((np_array == test_array).all(1))[0]
# Printing the index of the searched array in the original array
print("Index of the searched array in the original array:")
print(result)
Output:
Result: Thus the Numpy example python codes are executed and the results are
verified.
34
[Link]:3a Working with Pandas Data frames
Date:
Theory:
35
Program1: Display csv file using pandas
import pandas as pd
df=pd.read_csv("D:\college misellaneous\Lab2023EvenSem\[Link]")
print(df)
Output:
import pandas as pd
df=pd.read_csv("D:\college misellaneous\Lab2023EvenSem\[Link]")
print(df)
#data[start:end]
#start is inclusive whereas end is exclusive
print(df[10:12])
# it will print the rows from 10 to 11.
36
Output:
37
108 7.2 3.6 6.1 2.5 Iris-virginica
109 6.5 3.2 5.1 2.0 Iris-virginica
110 6.4 2.7 5.3 1.9 Iris-virginica
111 6.8 3.0 5.5 2.1 Iris-virginica
112 5.7 2.5 5.0 2.0 Iris-virginica
113 5.8 2.8 5.1 2.4 Iris-virginica
114 6.4 3.2 5.3 2.3 Iris-virginica
115 6.5 3.0 5.5 1.8 Iris-virginica
116 7.7 3.8 6.7 2.2 Iris-virginica
117 7.7 2.6 6.9 2.3 Iris-virginica
118 6.0 2.2 5.0 1.5 Iris-virginica
119 6.9 3.2 5.7 2.3 Iris-virginica
120 5.6 2.8 4.9 2.0 Iris-virginica
121 7.7 2.8 6.7 2.0 Iris-virginica
122 6.3 2.7 4.9 1.8 Iris-virginica
123 6.7 3.3 5.7 2.1 Iris-virginica
124 7.2 3.2 6.0 1.8 Iris-virginica
125 6.2 2.8 4.8 1.8 Iris-virginica
126 6.1 3.0 4.9 1.8 Iris-virginica
127 6.4 2.8 5.6 2.1 Iris-virginica
128 7.2 3.0 5.8 1.6 Iris-virginica
129 7.4 2.8 6.1 1.9 Iris-virginica
130 7.9 3.8 6.4 2.0 Iris-virginica
131 6.4 2.8 5.6 2.2 Iris-virginica
132 6.3 2.8 5.1 1.5 Iris-virginica
133 6.1 2.6 5.6 1.4 Iris-virginica
134 7.7 3.0 6.1 2.3 Iris-virginica
135 6.3 3.4 5.6 2.4 Iris-virginica
136 6.4 3.1 5.5 1.8 Iris-virginica
137 6.0 3.0 4.8 1.8 Iris-virginica
138 6.9 3.1 5.4 2.1 Iris-virginica
139 6.7 3.1 5.6 2.4 Iris-virginica
140 6.9 3.1 5.1 2.3 Iris-virginica
141 5.8 2.7 5.1 1.9 Iris-virginica
142 6.8 3.2 5.9 2.3 Iris-virginica
143 6.7 3.3 5.7 2.5 Iris-virginica
144 6.7 3.0 5.2 2.3 Iris-virginica
145 6.3 2.5 5.0 1.9 Iris-virginica
146 6.5 3.0 5.2 2.0 Iris-virginica
147 6.2 3.4 5.4 2.3 Iris-virginica
148 5.9 3.0 5.1 1.8 Iris-virginica
38
Program2:
import pandas as pd
import numpy as np
info = [Link](['P','a','n','d','a','s'])
a = [Link](info)
print(a)
Output:
0 P
1 a
2 n
3 d
4 a
5 s
dtype: object
import pandas as pd
# a list of strings
x = ['Python', 'Pandas']
# Calling DataFrame constructor on list
df = [Link](x)
print(df)
Output:
0
0 Python
1 Pandas
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = [Link](data=d)
print(df)
print([Link])
Output:
39
col1 col2
0 1 3
1 2 4
col1 int64
col2 int64
dtype: object
import pandas as pd
d = {'col1': [0, 1, 2, 3], 'col2': [Link]([12, 13], index=[2, 3])}
d1=[Link](data=d, index=[0, 1, 2, 3])
print(d1)
print([Link])
Output:
col1 col2
0 0 NaN
1 1 NaN
2 2 12.0
3 3 13.0
col1 int64
col2 float64
dtype: object
Output:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
40
Program7: Constructing DataFrame from a numpy ndarray that has labelled
columns:
import pandas as pd
import numpy as np
data = [Link]([(1, 2, 3), (4, 5, 6), (7, 8, 9)],
dtype=[("a", "i4"), ("b", "i4"), ("c", "i8")])
df3 = [Link](data, columns=['c', 'a'])
print(df3)
print([Link])
Output:
c a
0 3 1
1 6 4
2 9 7
c int64
a int32
dtype: object
Output:
xy
0 0 0
1 0 3
2 2 3
41
Program9: Constructing Data Frame from Series/Data Frame:
import pandas as pd
ser = [Link]([1, 2, 3], index=["a", "b", "c"])
df = [Link](data=ser, index=["a", "c"])
print(df)
Output:
0
a 1
c 3
import pandas as pd
df1 = [Link]([1, 2, 3], index=["a", "b", "c"], columns=["x"])
df2 = [Link](data=df1, index=["a", "c"])
print(df2)
Output:
x
a 1
c 3
42
Output:
Original array:
[0 1 2 3 4 5 6]
First array elements raised to powers from second array, element-wise:
[ 0 1 8 27 64 125 216]
import pandas as pd
# dictionary of lists
name=['aparna', 'pankaj', 'sudhir', 'Geeku']
degree=['MBA','BCA', '[Link]', 'MBA']
score=[90, 40, 80, 98]
dict = {'name':name,
'degree':degree ,
'score':score}
df = [Link](dict,index=['Rollno1','Rollno2','Rollno3','Rollno4'])
print(df)
Output:
43
# return a new dataframe by dropping a
# row 'c' from dataframe
update_df = [Link]('c')
print(update_df)
Output:
Result: The python codes to understand data frames using pandas are executed
and the results are verified.
44
Ex.No3b Examples using Pandas
Date:
import pandas as pd
df = [Link]({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,
83]});
print(df)
print([Link](2))
Output:
X Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83
X Y Z
0 6084 7056 7396
1 7225 8836 9409
2 9216 7921 9216
3 6400 6889 5184
4 7396 7396 6889
import pandas as pd
import numpy as np
#dictionary exam_data
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael'
, 'Matthew', 'Laura', 'Kevin', 'Jonas'],'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, n
[Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'ye
s', 'no', 'no', 'yes']}
print(exam_data)
#convert dictionary into data frame
df_in = [Link](data=exam_data)
print(df_in)
45
print(df_in["score"])
print(df_in["score"].iloc[0])
Output:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael
', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
46
df = [Link](exam_data , index=labels)
total_rows=len([Link][0])
total_cols=len([Link][1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))
Output:
Number of Rows: 10
Number of Columns: 4
import pandas as pd
df = [Link]( {'col1':['C1','C1','C2','C2','C2','C3','C2'],
'col2':[1,2,3,3,4,6,5]})
print("Original DataFrame")
print(df)
df = [Link]('col1')['col2'].apply(list)
print("\nGroup on the col1:")
print(df)
Original DataFrame
col1 col2
0 C1 1
1 C1 2
2 C2 3
3 C2 3
4 C2 4
5 C3 6
6 C2 5
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
47
df = [Link](data=d)
print("Original DataFrame")
print(df)
if 'col4' in [Link]:
print("Col4 is present in DataFrame.")
else:
print("Col4 is not present in DataFrame.")
if 'col1' in [Link]:
print("Col1 is present in DataFrame.")
else:
print("Col1 is not present in DataFrame.")
Output:
Original DataFrame
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 12
3 4 9 1
4 7 5 11
Col4 is not present in DataFrame.
Col1 is present in DataFrame.
import pandas as pd
import numpy as np
Output:
48
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 yes
h Laura NaN 1 no
i Kevin 8.0 2 no
j Jonas 19.0 1 yes
import pandas as pd
import numpy as np
df = [Link](exam_data , index=labels)
print("Number of attempts in the examination is greater than 2:")
print(df[df['attempts'] > 2])
Output:
import pandas as pd
import numpy as np
49
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = [Link](exam_data , index=labels)
print("First three rows of the data frame:")
print([Link][:3])
Output:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael
', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = [Link](exam_data , index=labels)
print("Rows where score is missing:")
print(df[df['score'].isnull()])
Output:
import pandas as pd
df = [Link]({
'Name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino
Mcneill'],
'Date_Of_Birth ':
['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'Age': [18.5, 21.2, 22.5, 22, 23]
50
})
print("Original DataFrame:")
print(df)
label1, unique1 = [Link](df['Name'])
print("\nNumeric representation of an array by identifying distinct values:")
print(label1)
print(unique1)
Output:
Original DataFrame:
Name Date_Of_Birth Age
0 Alberto Franco 17/05/2002 18.5
1 Gino Mcneill 16/02/1999 21.2
2 Ryan Parkes 25/09/1998 22.5
3 Eesha Hinton 11/05/2002 22.0
4 Gino Mcneill 15/09/1997 23.0
import pandas as pd
df1 = [Link]({'W':[68,75,86,80,None],'X':[78,85,None,80,86], 'Y':[84,94
,89,83,86],'Z':[86,97,96,72,83]});
df2 = [Link]({'W':[78,75,86,80,None],'X':[78,85,96,80,76], 'Y':[84,84,8
9,83,86],'Z':[86,97,96,72,83]});
print("Original DataFrames:")
print(df1)
print(df2)
print("\nCheck for inequality of the said dataframes:")
print([Link](df2))
Output:
Original DataFrames:
W X Y Z
0 68.0 78.0 84 86
1 75.0 85.0 94 97
2 86.0 NaN 89 96
51
3 80.0 80.0 83 72
4 NaN 86.0 86 83
W X Y Z
0 78.0 78 84 86
1 75.0 85 84 97
2 86.0 96 89 96
3 80.0 80 83 72
4 NaN 76 86 83
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = [Link](data=d)
print("Original DataFrame")
print(df)
print("\nFirst 3 rows of the said DataFrame':")
df1 = [Link](3)
print(df1)
Output:
Original DataFrame
col1 col2 col3
0 1 4 7
1 2 5 5
2 3 6 8
3 4 9 12
4 7 5 1
5 11 0 11
52
1 2 5 5
2 3 6 8
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = [Link](data=d)
print("Original DataFrame")
print(df)
print("\nAll columns except 'col3':")
df = [Link][:, [Link] != 'col3']
print(df)
Output:
Original DataFrame
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 12
3 4 9 1
4 7 5 11
53
#slicing rows
print("Slicing")
df1=[Link][1:3]
print(df1)
print([Link][[1,4]])
#delete rows
print("delete rows")
df2=[Link]([1,2])
print(df2)
Output:
After Append
lib qty1 qty2
0 name0 6 2
1 name1 9 2
2 name2 6 5
3 name3 8 3
4 name4 5 9
After Append
lib qty1 qty2
0 name0 6 2
1 name1 9 2
2 name2 6 5
3 name3 8 3
4 name4 5 9
5 20 30 40
Slicing
lib qty1 qty2
1 name1 9 2
2 name2 6 5
3 name3 8 3
lib qty1 qty2
1 name1 9 2
4 name4 5 9
delete rows
lib qty1 qty2
0 name0 6 2
3 name3 8 3
4 name4 5 9
5 20 30 40
Result: Thus the example python codes using Pandas are executed and the
results are verified.
54
[Link] Basic plots using matplotlib
Date:
Output:
55
Program2: simple graph with numpy values – r: red line
Output:
56
Output:
Program4: Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1)
and finally to position (8, 10):
[Link](xpoints, ypoints)
[Link]()
57
Output:
Program5: Default X-Points -If we do not specify the points on the x-axis, they
will get the default values 0, 1, 2, 3 etc., depending on the length of the y-points.
[Link](ypoints)
[Link]()
Output:
58
Program 6: Draw only points with + symbol
Output:
x = [Link]([1, 2, 6, 8])
y = [Link]([3, 8, 1, 10])
[Link](x, y, color='green', marker='o', linestyle='dashed',linewidth=2, markersiz
e=12)
[Link]()
59
Output:
x1 = [Link]([1, 2, 6, 8])
y1 = [Link]([3, 8, 1, 10])
[Link](x1, y1, color='green', marker='o', linestyle='dashed',linewidth=2, marker
size=12)
x2 = [Link]([11, 12, 16, 18])
y2 = [Link]([3, 8, 1, 10])
[Link](x2, y2, color='brown', marker='o', linestyle='dashed',linewidth=2, marke
rsize=12)
[Link]()
Output:
60
Program9: x- 1D, y- 2D
import numpy as np
import [Link] as plt
x = [1, 2, 3]
y = [Link]([[1, 2], [3, 4], [5, 6]])
[Link](x, y)
[Link]()
Output:
61
Program10: Sin wave
Output:
Program11:
matplotlib basic plot
Program6: To save plot in default location
62
t = [Link](0.0, 2.0,0.01)
s = 1 + [Link](2 * [Link] * t)
fig,ax = [Link]()
[Link](t, s)
[Link](xlabel='time (s)', ylabel='voltage (mV)',
title='first plot')
[Link]()
[Link]("[Link]")
[Link]()
Output:
Result: Thus the basic plot is drawn using matplotlib is executed and the result
is verified.
63
[Link]:5a Statistical and Probability measures - Frequency
Distributions
Date:
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
[Link]()
Output:
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
df=data['Iris-setosa'].value_counts()
print(df)
Output:
Iris-setosa
Iris-versicolor 50
Iris-virginica 50
Iris-setosa 49
Name: count, dtype: int64
64
Program3: Frequency table using crosstab
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
freq_table=[Link](data['Iris-setosa'], 'no_of_Iris-setosa')
freq_table
Output:
Iris-setosa
Iris-versicolor 50
Iris-virginica 50
Iris-setosa 49
Name: count, dtype: int64
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
freq_table=[Link](data['Iris-setosa'], 'no_of_Iris-setosa')
print(freq_table)
freq_table/len(data)
Output:
col_0 no_of_Iris-setosa
Iris-setosa
Iris-setosa 49
Iris-versicolor 50
Iris-virginica 50
col_0 no_of_Iris-setosa
Iris-setosa
Iris-setosa 0.328859
Iris-versicolor 0.335570
Iris-virginica 0.335570
65
Program5: Two-way Frequency table- frequency table – relationship between 2
different variables
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
freq_table=[Link](data['Iris-setosa'], data['5.1'])
print(freq_table)
Output:
5.1 4.3 4.4 4.5 4.6 4.7 4.8 ... 7.2 7.3 7.4 7.6 7.7 7.9
Iris-setosa ...
Iris-setosa 1 3 1 4 2 5 ... 0 0 00 00
Iris-versicolor 0 0 0 0 0 0 ... 0 0 0 0 0 0
Iris-virginica 0 0 0 0 0 0 ... 3 1 1 1 4 1
[3 rows x 35 columns]
Result: Thus, the python codes for frequency distributions are executed and the
results are verified.
66
[Link]:5b Statistical and Probability measures - Mean, Mode, Standard
Deviation
Date:
Aim: To write Python code for Mean, Mode and standard Deviation.
import statistics
L = [1, 3, 8, 15]
print([Link](L))
Output:
6.75
L = [1, 3, 8, 15]
print(sum(L) / len(L))
Output:
6.75
Program3: median(), low(), high() - If the number of data points is odd, all three
functions return the middle value directly.
import statistics
L = [3, 1, 8]
print([Link](L))
print(statistics.median_low(L))
print(statistics.median_high(L))
Output:
3
3
3
67
values, statistics.median_low() returns the smaller value,
and statistics.median_high() returns the larger value.
import statistics
L = [3, 1, 8, 15]
print([Link](L))
print(statistics.median_low(L))
print(statistics.median_high(L))
Output:
5.5
3
8
import statistics
L = [3, 2, 3, 2, 1, 2]
print([Link](L))
print([Link](L))
Output:
2
[2]
import statistics
L = [3, 2, 3, 2, 1, 2, 3]
print([Link](L))
print([Link](L))
Output:
3
[3, 2]
68
Program7: [Link]() computes the population variance - The
population variance σ2 is calculated as follows for a population consisting of n
data points with mean µ.
69
import statistics
L= [10, 1, 3, 7, 1]
print([Link](L))
Output:
12.64
import statistics
L= [10, 1, 3, 7, 1]
mu = [Link](L)
print([Link](L, mu))
Output:
12.64
L= [10, 1, 3, 7, 1]
print(sum((x - sum(L) / len(L)) ** 2 for x in L) / len(L))
Output:
12.64
import statistics
L= [10, 1, 3, 7, 1]
print([Link](L))
Output:
15.8
70
Sample variance is given by
import statistics
L= [10, 1, 3, 7, 1]
xbar = [Link](L)
print([Link](L, xbar))
Output:
15.8
import statistics
L= [10, 1, 3, 7, 1]
print(sum((x - sum(L) / len(L)) ** 2 for x in L) / (len(L) - 1))
Output:
15.8
import statistics
L= [10, 1, 3, 7, 1]
print([Link](L))
Output:
3.5552777669262356
71
Program14: Population standard deviation -The population standard deviation is
the square root of the population variance.
The population standard deviation is the square root of the population variance.
import math
import statistics
L= [10, 1, 3, 7, 1]
print([Link]([Link](L)))
Output:
3.5552777669262356
Output:
3.9749213828703582
Program16: The sample standard deviation is the square root of the sample
variance.
import statistics
import math
L= [10, 1, 3, 7, 1]
print([Link]([Link](L)))
Output:
3.9749213828703582
Result: Thus the python code to calculate variance, standard deviation are
executed and the results are verified.
72
[Link]:5c Statistical and Probability measures - Variability
Date:
Program1: Range
L= [10, 1, 3, 7, 1]
range1=(max(L)-min(L))
print(range1)
Output:
9
Program2: IQR
The interquartile range, often denoted “IQR”, is a way to measure the spread
of the middle 50% of a dataset. It is calculated as the difference between the
first quartile* (the 25th percentile) and the third quartile (the 75th percentile) of
a dataset. It is calculated using the NumPy. Percentile() function.
import numpy as np
#define array of data
data = [Link]([14, 19, 20, 22, 24, 26, 27, 30, 30, 31, 36, 38, 44, 47])
#calculate interquartile range
q3, q1 = [Link](data, [75 ,25])
iqr = q3 - q1
#display interquartile range
print(iqr)
Output:
12.25
Result: Thus the python code to calculate range, IQR are executed and the
results are verified.
73
[Link]:5d Statistical and Probability measures- Normal curves
Date:
Modules Needed
Matplotlib is python’s data visualization library which is widely used for
the purpose of data visualization.
Numpy is a general-purpose array-processing package. It provides a high-
performance multidimensional array object, and tools for working with
these arrays. It is the fundamental package for scientific computing with
Python.
Scipy is a python library that is useful in solving many mathematical
equations and algorithms.
Statistics module provides functions for calculating mathematical
statistics of numeric data.
Functions used
To calculate mean of the data
Syntax:
mean(data)
To calculate standard deviation of the data
Syntax:
stdev(data)
To calculate normal probability density of the data [Link] is used, it
refers to the normal probability density function which is a module in
scipy library that uses the above probability density function to calculate
the value.
Syntax:
[Link](Data, loc, scale)
Here, loc parameter is also known as the mean and the scale parameter is also
known as standard deviation.
Approach
Import module
Create data
Calculate mean and deviation
74
Calculate normal probability density
Plot using above calculated values
Display plot
Program:
import numpy as np
import [Link] as plt
from [Link] import norm
import statistics
Output:
Result: Thus, the Python code to generate normal curves is executed and the
result is verified
75
[Link]: 5e Statistical and Probability measures- scatter plots
Date:
import pandas as pd
con = pd.read_csv('D:\college misellaneous\Lab2023EvenSem\[Link]')
con
Output:
import pandas as pd
con = pd.read_csv('D:\college misellaneous\Lab2023EvenSem\[Link]')
[Link](columns={'5.1': 'Col1', '3.5': "Col2",
'1.4': 'Col3', '0.2': 'Col4',
'Iris-setosa': 'Iris-variety'}, inplace=True)
[Link]()
Output:
76
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa
inplace=True means the table will be modified without returning a copy of the
data or the original data.
import pandas as pd
con = pd.read_csv('D:\college misellaneous\Lab2023EvenSem\[Link]')
[Link](columns={'5.1': 'Col1', '3.5': "Col2",
'1.4': 'Col3', '0.2': 'Col4',
'Iris-setosa': 'Iris-variety'},inplace=True)
print(list([Link]))
Output:
import pandas as pd
con = pd.read_csv('D:\college misellaneous\Lab2023EvenSem\[Link]')
[Link](columns={'5.1': 'Col1', '3.5': "Col2",
'1.4': 'Col3', '0.2': 'Col4',
'Iris-setosa': 'Iris-variety'},inplace=False)
print(list([Link]))
Output:
77
import pandas as pd
import seaborn as sns
Result: Thus, the Python code to generate scatter plots are executed and the
results are verified.
78
[Link]: 5f Statistical and Probability measures- Correlation and Scatter plot
Date:
2. Negative Correlation: When one variable increases and the other variable
decreases together and vice-versa. They are negatively correlated. For example,
If the distance between magnet increases their attraction decreases, and vice-
versa. Hence, a negative correlation. ‘-1’ is no correlation
79
3. Zero Correlation( No Correlation): When two variables don’t seem to be
linked at all. ‘0’ is a perfect negative correlation. For Example, the amount of
tea you take and level of intelligence.
Program:
import pandas as pd
import [Link] as plt
import numpy as np
y = [Link]([1, 2, 3, 4, 3, 5, 4])
x = [Link]([1, 2, 3, 4, 5, 6, 7])
correlation = [Link](x)
print(correlation)
[Link](x, y)
[Link]([Link](x), np.poly1d([Link](x, y, 1))
([Link](x)), color='red')
[Link]('Correlation')
[Link]('x axis')
[Link]('y axis')
[Link]()
Output:
0.8603090020146067 # Correlation coefficient nearing 1 hence +ive correlation
Result: Thus the Python code to generate the correlation is executed and the
result is verified.
80
[Link]:5g Statistical and Probability measures - Regression
Date:
Program
import numpy as np
import [Link] as plt
def estimate_coef(x, y):
# number of observations/points
n = [Link](x)
# mean of x and y vector
m_x = [Link](x)
m_y = [Link](y)
# calculating cross-deviation and deviation about x
SS_xy = [Link](y*x) - n*m_y*m_x
SS_xx = [Link](x*x) - n*m_x*m_x
# calculating regression coefficients
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return (b_0, b_1)
def plot_regression_line(x, y, b):
81
# plotting the actual points as scatter plot
[Link](x, y, color = "m",
marker = "o", s = 30)
# predicted response vector
y_pred = b[0] + b[1]*x
# plotting the regression line
[Link](x, y_pred, color = "g")
# putting labels
[Link]('x')
[Link]('y')
[Link]()
def main():
# observations / data
x = [Link]([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = [Link]([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
# estimating coefficients
b = estimate_coef(x, y)
print(b)
plot_regression_line(x,y,b)
main()
Output:
(1.2363636363636363, 1.1696969696969697)
Result: Thus the python code for linear regression is executed and the result is
verified.
82
[Link]: 6a Mean, Median, Mode, Variance, Standard Deviation,
Skewness and Kurtosis
Date:
Aim: Using the standard benchmark data set for performing the following:
Univariate Analysis: Mean, Median, Mode, Variance, Standard Deviation,
Skewness and Kurtosis.
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
[Link]()
import statistics
print(data["5.1"])
print([Link](data["3.5"]))
print([Link](data["5.1"]))
Output:
0 4.9
1 4.7
2 4.6
3 5.0
4 5.4
...
144 6.7
145 6.3
146 6.5
147 6.2
148 5.9
Name: 5.1, Length: 149, dtype: float64
3.051006711409396
5.8483221476510066
Program2-median()
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
83
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
[Link]()
import statistics
print(data["5.1"])
print([Link](data["5.1"]))
print(statistics.median_low(data["5.1"]))
print(statistics.median_high(data["5.1"]))
Output:
0 4.9
1 4.7
2 4.6
3 5.0
4 5.4
...
144 6.7
145 6.3
146 6.5
147 6.2
148 5.9
Name: 5.1, Length: 149, dtype: float64
5.8
5.8
5.8
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['5.1'].tolist()
print(L1)
print([Link](data["5.1"]))
print(statistics.median_low(data["5.1"]))
print(statistics.median_high(data["5.1"]))
Output:
[4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7,
5.1, 5.4, 5.1, 4.6, 5.1, 4.8, 5.0, 5.0, 5.2, 5.2, 4.7, 4.8, 5.4, 5.2, 5.5, 4.9, 5.0, 5.5, 4
84
.9, 4.4, 5.1, 5.0, 4.5, 4.4, 5.0, 5.1, 4.8, 5.1, 4.6, 5.3, 5.0, 7.0, 6.4, 6.9, 5.5, 6.5, 5.
7, 6.3, 4.9, 6.6, 5.2, 5.0, 5.9, 6.0, 6.1, 5.6, 6.7, 5.6, 5.8, 6.2, 5.6, 5.9, 6.1, 6.3, 6.1
, 6.4, 6.6, 6.8, 6.7, 6.0, 5.7, 5.5, 5.5, 5.8, 6.0, 5.4, 6.0, 6.7, 6.3, 5.6, 5.5, 5.5, 6.1,
5.8, 5.0, 5.6, 5.7, 5.7, 6.2, 5.1, 5.7, 6.3, 5.8, 7.1, 6.3, 6.5, 7.6, 4.9, 7.3, 6.7, 7.2, 6
.5, 6.4, 6.8, 5.7, 5.8, 6.4, 6.5, 7.7, 7.7, 6.0, 6.9, 5.6, 7.7, 6.3, 6.7, 7.2, 6.2, 6.1, 6.
4, 7.2, 7.4, 7.9, 6.4, 6.3, 6.1, 7.7, 6.3, 6.4, 6.0, 6.9, 6.7, 6.9, 5.8, 6.8, 6.7, 6.7, 6.3
, 6.5, 6.2, 5.9]
5.8
5.8
5.8
Program4: Variance
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['3.5'].tolist()
print(L1)
print([Link](L1))
print([Link](data['3.5']))
Output:
[3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8,
3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3
.1, 3.0, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3.0, 3.8, 3.2, 3.7, 3.3, 3.2, 3.2, 3.1, 2.3, 2.8, 2.
8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8
, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0,
2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8, 3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3
.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.
8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5
, 3.0, 3.4, 3.0]
0.18666006035764154
0.18666006035764154
import pandas as pd
import numpy as np
# reading csv file as pandas dataframe
85
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['1.4'].tolist()
print(L1)
print([Link](L1))
print([Link](data['1.4']))
Output:
[1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 1.2, 1.5, 1.3, 1.4, 1.7,
1.5, 1.7, 1.5, 1.0, 1.7, 1.9, 1.6, 1.6, 1.5, 1.4, 1.6, 1.6, 1.5, 1.5, 1.4, 1.5, 1.2, 1.3, 1
.5, 1.3, 1.5, 1.3, 1.3, 1.3, 1.6, 1.9, 1.4, 1.6, 1.4, 1.5, 1.4, 4.7, 4.5, 4.9, 4.0, 4.6, 4.
5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4.0, 4.7, 3.6, 4.4, 4.5, 4.1, 4.5, 3.9, 4.8, 4.0, 4.9, 4.7
, 4.3, 4.4, 4.8, 5.0, 4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5, 4.7, 4.4, 4.1, 4.0, 4.4, 4.6,
4.0, 3.3, 4.2, 4.2, 4.2, 4.3, 3.0, 4.1, 6.0, 5.1, 5.9, 5.6, 5.8, 6.6, 4.5, 6.3, 5.8, 6.1, 5
.1, 5.3, 5.5, 5.0, 5.1, 5.3, 5.5, 6.7, 6.9, 5.0, 5.7, 4.9, 6.7, 4.9, 5.7, 6.0, 4.8, 4.9, 5.
6, 5.8, 6.1, 6.4, 5.6, 5.1, 5.6, 6.1, 5.6, 5.5, 4.8, 5.4, 5.6, 5.1, 5.1, 5.9, 5.7, 5.2, 5.0
, 5.2, 5.4, 5.1]
1.75373635121875
1.75373635121875
86
Skewness = 0: Then normally distributed.
Skewness > 0: Then more weight in the left tail of the distribution.
Skewness < 0: Then more weight in the right tail of the distribution.
import pandas as pd
data = [[10, 18, 11], [13, 15, 8], [9, 20, 3]]
df = [Link](data)
print([Link]())
Output:
0 1.293343
1 -0.585583
2 -0.722109
dtype: float64
Program:
import pandas as pd
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['1.4'].tolist()
print(L1)
df = [Link](L1)
print([Link]())
Output:
87
[1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 1.2, 1.5, 1.3, 1.4, 1.7,
1.5, 1.7, 1.5, 1.0, 1.7, 1.9, 1.6, 1.6, 1.5, 1.4, 1.6, 1.6, 1.5, 1.5, 1.4, 1.5, 1.2, 1.3, 1
.5, 1.3, 1.5, 1.3, 1.3, 1.3, 1.6, 1.9, 1.4, 1.6, 1.4, 1.5, 1.4, 4.7, 4.5, 4.9, 4.0, 4.6, 4.
5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4.0, 4.7, 3.6, 4.4, 4.5, 4.1, 4.5, 3.9, 4.8, 4.0, 4.9, 4.7
, 4.3, 4.4, 4.8, 5.0, 4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5, 4.7, 4.4, 4.1, 4.0, 4.4, 4.6,
4.0, 3.3, 4.2, 4.2, 4.2, 4.3, 3.0, 4.1, 6.0, 5.1, 5.9, 5.6, 5.8, 6.6, 4.5, 6.3, 5.8, 6.1, 5
.1, 5.3, 5.5, 5.0, 5.1, 5.3, 5.5, 6.7, 6.9, 5.0, 5.7, 4.9, 6.7, 4.9, 5.7, 6.0, 4.8, 4.9, 5.
6, 5.8, 6.1, 6.4, 5.6, 5.1, 5.6, 6.1, 5.6, 5.5, 4.8, 5.4, 5.6, 5.1, 5.1, 5.9, 5.7, 5.2, 5.0
, 5.2, 5.4, 5.1]
0 -0.289459
dtype: float64
# Creating a dataset
dataset = [88, 85, 82, 97, 67, 77, 74, 86,
81, 95, 77, 88, 85, 76, 81]
88
# Calculate the kurtosis
print(kurtosis(dataset, axis=0, bias=True))
Output:
-0.29271198374234686
Output:
89
Program : Only in Anaconda
# Creating a dataset
import pandas as pd
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['1.4'].tolist()
Output:
-1.3789609562635352
90
import pandas as pd
data = pd.read_csv('d:\college misellaneous\Lab2023EvenSem\[Link]')
import statistics
L1=data['1.4'].tolist()
L2=data['3.5'].tolist()
[Link](L1, L2, '*')
Output:
91
Program: Perform Univariate analysis with the following pandas DataFrame
'points': [1, 1, 2, 3.5, 4, 4, 4, 5, 5, 6.5, 7, 7.4, 8, 13, 14.2]
'assists': [5, 7, 7, 9, 12, 9, 9, 4, 6, 8, 8, 9, 3, 2, 6]
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12, 6, 6, 7, 8, 7, 9, 15]
import pandas as pd
df=[Link]({'points': [1, 1, 2, 3.5, 4, 4, 4, 5, 5, 6.5, 7, 7.4, 8, 13, 14.2],
'assists': [5, 7, 7, 9, 12, 9, 9, 4, 6, 8, 8, 9, 3, 2, 6],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12, 6, 6, 7, 8, 7, 9, 15]})
print(df)
import statistics
print([Link](df["points"]))
print([Link](df["assists"]))
print([Link](df["rebounds"]))
print(statistics.median_low(df["rebounds"]))
print(statistics.median_high(df["rebounds"]))
print([Link](df['points']))
print([Link](df['assists']))
print([Link]())
import pylab as p
from [Link] import kurtosis
x1=[1, 1, 2, 3.5, 4, 4, 4, 5, 5, 6.5, 7, 7.4, 8, 13, 14.2]
y1=[5, 7, 7, 9, 12, 9, 9, 4, 6, 8, 8, 9, 3, 2, 6]
[Link](x1, y1, '*')
Output:
92
6 4.0 9 9
7 5.0 4 12
8 5.0 6 6
9 6.5 8 6
10 7.0 8 7
11 7.4 9 8
12 8.0 3 7
13 13.0 2 9
14 14.2 6 15
5.706666666666667
6.933333333333334
8
8
8
13.893955555555555
2.5681813712344295
points 1.053813
assists -0.207120
rebounds 1.106667
dtype: float64
Result: Thus, using the standard benchmark data set the Univariate Analysis:
Mean, Median, Mode, Variance, Standard Deviation, Skewness and Kurtosis is
executed and the result is verified.
93
[Link]: 6b Bivariant Analysis- Logistic Regression
Date:
Logistic Regression
Logistic regression aims to solve classification problems. It does this by
predicting categorical outcomes, unlike linear regression that predicts a
continuous outcome.
In the simplest case there are two outcomes, which is called binomial, an example
of which is predicting if a tumor is malignant or benign. Other cases have more
than two outcomes to classify, in this case it is called multinomial. A common
example for multinomial logistic regression would be predicting the class of an
iris flower between 3 different species.
Here we will be using basic logistic regression to predict a binomial variable. This
means it has only two possible outcomes.
94
Program:
import numpy
from sklearn import linear_model
logr = linear_model.LogisticRegression()
[Link](X,y)
Output:
We have predicted that a tumor with a size of 3.46mm will not be cancerous.
Program: Perform Bivariate analysis using the pandas DataFrame that contains
information about two variables: (1) Hours spent studying and (2) Exam score
received by 20 different
import pandas as pd
import [Link] as plt
#create DataFrame
df = [Link]({'hours': [1, 1, 1, 2, 2, 2, 3, 3, 3, 3,
3, 4, 4, 5, 5, 6, 6, 6, 7, 8],
'score': [75, 66, 68, 74, 78, 72, 85, 82, 90, 82,
80, 88, 85, 90, 92, 94, 94, 88, 91, 96]})
#view first five rows of DataFrame
#[Link]()
95
Output:
import pandas as pd
import [Link] as plt
import [Link] as sm
df = [Link]({'hours': [1, 1, 1, 2, 2, 2, 3, 3, 3, 3,
3, 4, 4, 5, 5, 6, 6, 6, 7, 8],
'score': [75, 66, 68, 74, 78, 72, 85, 82, 90, 82,
80, 88, 85, 90, 92, 94, 94, 88, 91, 96]})
print([Link]())
[Link]()
#define response variable
y = df['score']
#define explanatory variable
x = df[['hours']]
#add constant to predictor variables
x = sm.add_constant(x)
#fit linear regression model
96
model = [Link](y, x).fit()
#view model summary
print([Link]())
Output:
hours score
0 1 75
1 1 66
2 1 68
3 2 74
4 2 78
OLS Regression Results
Dep. Variable: score R-squared: 0.794
Model: OLS Adj. R-squared: 0.783
Method: Least Squares F-statistic: 69.56
Date: Mon, 29 Jan 2024 Prob (F-statistic): 1.35e-07
Time: 10:43:46 Log-Likelihood: -55.886
No. Observations: 20 AIC: 115.8
Df Residuals: 18 BIC: 117.8
Df Model: 1
Covariance Type: nonrobust
coef std err t P>|t| [0.025 0.975]
const 69.0734 1.965 35.149 0.000 64.945 73.202
hours 3.8471 0.461 8.340 0.000 2.878 4.816
Omnibus: 0.171 Durbin-Watson: 1.404
Prob(Omnibus): 0.918 Jarque-Bera (JB): 0.177
Skew: 0.165 Prob(JB): 0.915
Kurtosis: 2.679 Cond. No. 9.37
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly
specified.
Result: Thus the Python code for logistic regression is executed and the result is
verified.
Pima Diabetics Dataset
Use the below link:
[Link]
database?resource=download
sign in with any gmail accout and download
All code executed using iris data can be executed using Diabetics dataset
97
[Link]:7a Supervised Learning
Date:
The ultimate goal of the supervised learning algorithm is to predict Y with the
max accuracy for a given new input X.
In supervised learning, we start by importing a dataset containing training
attributes and the target attributes. The supervised learning algorithm will learn
the relation between training examples and their associated target variables, then
apply that learned relationship to classify entirely new inputs (without targets).
f will be the relation between the marks and number of hours the student
prepared for an exam.
X is the INPUT (Number of hours he prepared).
Y is the output (Marks the student scored in the exam).
C will be a random error.
The ultimate goal of the supervised learning algorithm is to predict Y with the
maximum accuracy for a given new input X. There are several ways to implement
supervised learning and we’ll explore some of the most commonly used
approaches.
Based on the given data sets, the machine learning problem is categorized into
two types: classification and regression. If the given data has both input
(training) values and output (target) values, then it is a classification problem. If
the dataset has continuous numerical values of attributes without any target labels,
then it is a regression problem.
98
Classification:
Consider the example of a medical researcher who wants to analyze breast cancer
data to predict one of three specific treatments a patient should receive. This data
analysis task is called classification, and a model or classifier is constructed to
predict class labels, such as “treatment A,” “treatment B” or “treatment C.”
Classification is a prediction problem that predicts the categorical class labels,
which are discrete and unordered. It is a two-step process, consisting of a learning
step and a classification step.
METHODS IN CLASSIFICATION AND CHOOSING THE BEST.
There are several classification techniques that one can choose based on the type
of dataset they're dealing with. Below is a list of a few widely used traditional
classification techniques:
1. K— nearest neighbor
2. Decision trees
3. Naïve Bayes
4. Support vector machines
In the first step, the classification model builds the classifier by analyzing the
training set. Next, the
In the first step, the classification model builds the classifier by analyzing the
training set. Next, the class labels for the given data are predicted. The dataset
tuples and their associated class labels under analysis are split into a training set
and test set. The individual tuples that make up the training set are randomly
sampled from the dataset under analysis. The remaining tuples form the test set
and are independent of the training tuples, meaning they will not be used to build
the classifier.
The test set is used to estimate the predictive accuracy of a classifier. The accuracy
of a classifier is the percentage of test tuples that are correctly classified by the
classifier. To achieve higher accuracy, the best way is to test out different
algorithms and try different parameters within each algorithm. The best one can
be selected by cross-validation.
To choose a good algorithm for a problem, parameters such as accuracy, training
time, linearity, number of parameters and special cases must be taken into
consideration for different algorithms.
IMPLEMENTING KNN IN SCIKIT-LEARN ON IRIS DATASET TO
CLASSIFY THE TYPE OF FLOWER BASED ON THE GIVEN INPUT
Program:
99
# Loading IRIS dataset from scikit-learn object into iris variable.
iris = datasets.load_iris()
Output:
<class '[Link]._bunch.Bunch'>
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names',
'filename', 'data_module'])
<class '[Link]'> <class '[Link]'>
(150, 4)
['setosa' 'versicolor' 'virginica']
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
100
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
Program:
# Declare an of the KNN classifier class with the value with neighbors.
knn = KNeighborsClassifier(n_neighbors=6)
101
print(X)
Output:
Here,
0 corresponds versicolor
1 corresponds virginica
2 corresponds setosa
102
regr = linear_model.LinearRegression()
# Input data
print('Input Values')
print(diabetes_X_test)
# Predicted Data
print("Predicted Output Values")
print(diabetes_y_pred)
# Plot outputs
[Link](diabetes_X_test, diabetes_y_test, color='black')
[Link](diabetes_X_test, diabetes_y_pred, color='red', linewidth=1)
[Link]()
Output:
Input Values
[[ 0.07786339]
[-0.03961813]
[ 0.01103904]
[-0.04069594]
[-0.03422907]
[ 0.00564998]
[ 0.08864151]
[-0.03315126]
[-0.05686312]
[-0.03099563]
[ 0.05522933]
[-0.06009656]
[ 0.00133873]
[-0.02345095]
[-0.07410811]
[ 0.01966154]
[-0.01590626]
[-0.01590626]
103
[ 0.03906215]
[-0.0730303 ]]
Predicted Output Values
[225.9732401 115.74763374 163.27610621 114.73638965 120.80385422
158.21988574 236.08568105 121.81509832 99.56772822 123.83758651
204.73711411 96.53399594 154.17490936 130.91629517 83.3878227
171.36605897 137.99500384 137.99500384 189.56845268 84.3990668 ]
Result: Thus the Python code for supervised learning is executed and the result is
verified.
104
[Link]:7b Unsupervised Learning
Date:
In supervised learning, the system tries to learn from the previous examples
given. In unsupervised learning, the system attempts to find the patterns directly
from the example given. So, if the dataset is labeled it is a supervised problem,
and if the dataset is unlabelled then it is an unsupervised problem.
Below is a simple pictorial representation of how supervised and unsupervised
learning can be viewed.
The left image an example of supervised learning (we use regression techniques
to find the best fit line between the features). In unsupervised learning the inputs
are segregated based on features and the prediction is based on which cluster it
belonged to.
105
Preparing Data for Unsupervised Learning
For our example, we'll use the Iris dataset to make predictions. The dataset
contains a set of 150 records under four attributes — petal length, petal width,
sepal length, sepal width, and three iris classes: setosa, virginica and versicolor.
We'll feed the four features of our flower to the unsupervised algorithm and it will
predict which class the iris belongs to.
We use the scikit-learn library in Python to load the Iris dataset and matplotlib for
data visualization. Below is the code snippet for exploring the dataset.
On GitHub: iris_dataset.py
Program:
# Loading dataset
iris_df = datasets.load_iris()
# Features
print(iris_df.feature_names)
# Targets
print(iris_df.target)
# Target Names
print(iris_df.target_names)
label = {0: 'red', 1: 'blue', 2: 'green'}
# Dataset Slicing
x_axis = iris_df.data[:, 0] # Sepal Length
y_axis = iris_df.data[:, 2] # Sepal Width
# Plotting
[Link](x_axis, y_axis, c=iris_df.target)
[Link]()
Output:
106
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0000000000000111111111111111111111111
1111111111111111111111111122222222222
2222222222222222222222222222222222222
2 2]
['setosa' 'versicolor' 'virginica']
Clustering
In clustering, the data is divided into several groups with similar traits.
107
In the image above, the left is raw data without classification, while the right is
clustered based on its features. When an input is given which is to be predicted
then it checks in the cluster it belongs to based on its features, and the prediction
is made.
K-MEANS CLUSTERING IN PYTHON
K-means clustering is an iterative unsupervised clustering algorithm that aims to
find local maxima in each iteration. Initially, desired number of clusters are
chosen. In our example, we know there are three classes involved, so we program
the algorithm to group the data into three classes by passing the parameter
“n_clusters” into our k-means model. Randomly, three points (inputs) are
assigned into three clusters. Based on the centroid distance between each point,
the next given inputs are segregated into respected clusters and the centroids are
re-computed for all the clusters.
Each centroid of a cluster is a collection of feature values which define the
resulting groups. Examining the centroid feature weights can be used to
qualitatively interpret what kind of group each cluster represent.
We import the k-means model from scikit-learn library, fit out features and
predict.
K-means implementation in Python on GitHub: clustering_iris.py
Program:
# Importing Modules
from sklearn import datasets
from [Link] import KMeans
# Loading dataset
iris_df = datasets.load_iris()
# Declaring Model
model = KMeans(n_clusters=3)
# Fitting Model
[Link](iris_df.data)
# Printing Predictions
print(predicted_label)
108
print(all_predictions)
Output:
[0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0000000000000112111111111111111111111
1112111111111111111111111121222212222
2211222212121221122222122221222122212
2 1]
HIERARCHICAL CLUSTERING
As its name implies, hierarchical clustering is an algorithm that builds a
hierarchy of clusters. This algorithm begins with all the data assigned to a
cluster, then the two closest clusters are joined into the same cluster. The
algorithm ends when only a single cluster is left.
The completion of hierarchical clustering can be shown using dendrogram. Now
let’s look at an example of hierarchical clustering using grain data.
Hierarchical clustering implementation in Python on GitHub: hierchical-
[Link]
Program:
# Importing Modules
from [Link] import linkage, dendrogram
import [Link] as plt
import pandas as pd
# Remove the grain species from the DataFrame, save for later
varieties = list(seeds_df.pop('grain_variety'))
"""
Perform hierarchical clustering on samples using the
linkage() function with the method='complete' keyword argument.
Assign the result to mergings.
109
"""
mergings = linkage(samples, method='complete')
"""
Plot a dendrogram using the dendrogram() function on mergings,
specifying the keyword arguments labels=varieties, leaf_rotation=90,
and leaf_font_size=6.
"""
dendrogram(mergings,
labels=varieties,
leaf_rotation=90,
leaf_font_size=6,
)
[Link]()
Output:
Hierarchical clustering can’t handle big data very well but k-means
clustering can. This is because the time complexity of k-means is linear
i.e. O(n) while that of hierarchical clustering is quadratic i.e. O(n2).
110
K-means clustering starts with an arbitrary choice of clusters, and the
results generated by running the algorithm multiple times might differ.
Results are reproducible in hierarchical clustering.
K-means is found to work well when the shape of the clusters is
hyperspherical (like a circle in 2D or a sphere in 3D).
K-means doesn't allow noisy data, while hierarchical clustering can
directly use the noisy dataset for clustering.
T-SNE CLUSTERING
One of the unsupervised learning methods for visualization is t-distributed
stochastic neighbor embedding, or t-SNE. It maps high-dimensional space
into a two or three-dimensional space which can then be visualized.
Specifically, it models each high-dimensional object by a two- or three-
dimensional point in such a way that similar objects are modeled by nearby
points and dissimilar objects are modeled by distant points with high
probability.
T-SNE Implementation in Python on Iris dataset: t_sne_clustering.py
Program:
# Importing Modules
from sklearn import datasets
from [Link] import TSNE
import [Link] as plt
# Loading dataset
iris_df = datasets.load_iris()
# Defining Model
model = TSNE(learning_rate=100)
# Fitting Model
transformed = model.fit_transform(iris_df.data)
# Plotting 2d t-Sne
x_axis = transformed[:, 0]
y_axis = transformed[:, 1]
Output:
111
Violet: Setosa, Green: Versicolor, Yellow: Virginica
Here, the Iris dataset has four features (4d) and is transformed and represented
in the two-dimensional figure. Similarly, t-SNE model can be applied to a
dataset which has n-features.
DBSCAN CLUSTERING
Density-based spatial clustering of applications with noise, or DBSCAN, is a
popular clustering algorithm used as a replacement for k-means in predictive
analytics. To run it doesn’t require an input for the number of clusters but it does
need to tune two other parameters.
The scikit-learn implementation provides a default for the eps and min_samples
parameters, but you’re generally expected to tune those. The eps parameter is
the maximum distance between two data points to be considered in the same
neighborhood. The min_samples parameter is the minimum amount of data
points in a neighborhood to be considered a cluster.
Program:
# Importing Modules
from [Link] import load_iris
import [Link] as plt
from [Link] import DBSCAN
from [Link] import PCA
112
# Load Dataset
iris = load_iris()
# Declaring Model
dbscan = DBSCAN()
# Fitting
[Link]([Link])
Result: Thus the Python code for unsupervised learning is executed and the
result is verified.
113
[Link] Various Plotting functions
Date:
114
Program: Line Plot
Output:
# Generate data
x = [Link](0, 2*[Link], 100)
y1, y2 = [Link](x), [Link](x)
115
# Plotting multiple lines on a single plot
[Link](x, y1, label='Sin(x)', color='b')
[Link](x, y2, label='Cos(x)', color='r', linestyle='--')
Output:
116
[Link](42)
x = [Link](50)
y = [Link](50)
# Plotting a scatter plot with custom markers
[Link](x, y, marker='o', linestyle='', markersize=8, color='r', label='Scatter Plot'
)
# Adding labels and title
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Scatter Plot Example')
# Displaying the legend
[Link]()
# Display the plot
[Link]()
Output:
117
[Link](19680801)
# create random data
xdata = [Link]([2, 10])
# split the data into two parts
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
# sort the data so it makes clean curves
[Link]()
[Link]()
# create some y data points
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
# plot the data
[Link](xdata1, ydata1, color ='tab:blue')
[Link](xdata2, ydata2, color ='tab:orange')
118
Download:
[Link]
from the above link download concrete strength data set. Extract the files to
required directory
Its extension will be xls. Use save as to convert it to xlxs file by choosing excel
workbook (in save as option)
Program:
import pandas as pd
Output:
119
Program: Scatter Plot - for the following Pandas DataFrame with Team name
and Rank Points as x and y axis
import pandas as pd
# Prepare data
data={'Team Name':["Australia", "Bangladesh", "England","India", "Srilanka"],
Output:
Result: Thus, the different plots in python are executed and the results are
verified.
120
[Link] Reading Files
Date:
Output:
Welcome
Good morning All
import pandas as pd
print(dataframe1)
Output:
Result: Thus the Python code to read txt file, excel files are executed and the
results are verified
121
[Link] Bivariate Analysis- Multiple Regression
Date:
linear regress only has one independent variable impacting the slope of the
relationship, multiple regression incorporates multiple independent variables.
Program: - 3D Plot
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import [Link] as plt
def generate_dataset(n):
x = []
y = []
random_x1 = [Link]()
random_x2 = [Link]()
for i in range(n):
x1 = i
x2 = i/2 + [Link]()*n
[Link]([1, x1, x2])
[Link](random_x1 * x1 + random_x2 * x2 + 1)
return [Link](x), [Link](y)
x, y = generate_dataset(200)
122
[Link]['[Link]'] = 12
fig = [Link]()
ax = fig.add_subplot(projection ='3d')
[Link]()
Output:
[Link]
Program:
import pandas
from sklearn import linear_model
123
df = pandas.read_csv("D:\college misellaneous\Lab2023EvenSem\[Link]")
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
[Link](X, y)
#predict the CO2 emission of a car where the weight is 2300kg, and the volume
is 1300cm3:
predictedCO2 = [Link]([[2300, 1300]])
print(predictedCO2)
Output:
[107.2087328]
Result: Thus the python code for multiple regression is executed and the result
is verified.
124
[Link] Histogram plot, Density Plot , Contour Plot, 3D plot, Normal plot
Date:
Aim: To write Python code for different plots like density plot, contour plot, 3D
plot, histogram plot, normal plot
Program:
Output:
125
Density Plot is a type of data visualization tool. It is a variation of the histogram
that uses ‘kernel smoothing’ while plotting the values. It is a continuous and
smooth version of a histogram inferred from a data.
Density plots uses Kernel Density Estimation (so they are also known as Kernel
density estimation plots or KDE) which is a probability density function. The
region of plot with a higher peak is the region with maximum data points
residing between those values.
Density plots can be made using pandas, seaborn, etc. In this article, we will
generate density plots using Pandas. We will be using two datasets of the
Seaborn Library namely – ‘car_crashes’ and ‘tips’.
Program:
import pandas as pd
import seaborn as sns
import [Link] as plt
[Link](color='green')
[Link]('Density plot for Speeding')
[Link]()
Output:
126
Contour plots also called level plots are a tool for doing multivariate analysis
and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables
we want to plot then the response Z will be plotted as slices on the X-Y plane
due to which contours are sometimes referred as Z-slices or iso-response.
Program:
fig, ax = [Link](1, 1)
Z = [Link](X / 2) + [Link](Y / 4)
[Link]()
Output:
Contoutf plot:
contour() and contourf() draw contour lines and filled contours, respectively.
Except as noted, function signatures and return values are the same for both
versions. contourf() differs from the MATLAB version in that it does not draw
the polygon edges. To draw edges, add line contours with calls to contour() .
Program:
import numpy as np
import [Link] as plt
x = [Link](1, 10)
y = [Link](-1, 1)
128
h=x*y
Output:
3D Plot:
For plotting lines in 3D we will have to initialize three variable points for the
line equation.
Program:
129
import [Link] as plt
fig = [Link]()
# plotting
ax.plot3D(x, y, z, 'green')
ax.set_title('3D line plot geeks for geeks')
[Link]()
Output:
Normal Plot:
130
Program:
import numpy as np
import [Link] as plt
from [Link] import norm
Output:
imshow(), colorbar()
Output:
132
Clabel:
Program: (Anaconda)
Output:
Result: Thus the python codes to generate different plots are executed and the
results are verified.
133