Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 80

Python Lab Manual

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY


(Autonomous)
Aziz Nagar Gate, C.B. Post, Hyderabad-75

Department of Computer science &


Engineering(Data Science)

Year : II B.Tech Semester : I

Data Structure Lab Manual


(R20)

LAB MANUAL

1
Python Lab Manual

Index

Title of Program Pgno


1. a) Installation and Environment setup of python. 3-7
b) Write a program to demonstrate the use of basic Data Types
c) Write a program to demonstrate the Operators and Expressions
d) Write a program to demonstrate the Functions and parameter passing
Techniques.
2. Write a Program to implement 8-11
i. Packages ii. Modules iii. Built-in Functions
3. Write a Program to implement 12-22
a) i. List ii. Tuple iii. Dictionaries
b) Programs on Stings, String Operations and Regular Expressions
4. a) Write a Program to implement Class and Object 23-26
b) Write a Program to implement Static and Instance methods, Abstract
Classes.
c) Write a program to compute distance between two points taking input
from the user
(Pythagorean Theorem)
5. a) Write a program to implement Inheritance and Polymorphism 27-31
b) Write a program to implement Files
c) Write a program to illustrate Exception Handling.
6. a) Write a program using scikit-learn to implement K-means Clustering 32-51
b) Program to calculate the entropy and the information gain
c) Program to implement perceptron learning
7. a) Write a program to implement decision tree algorithm and evaluate 52-55
using accuracy,precison,recall and RMSE.
b) Occupancy estimator using random forest
8. a) Calculating with matrices using numpy : inv, pinv, matrix rank, solve, 56-64
lstsq, svd, transpose, eig,sort, linspace, meshgrid, mgrid, ogrid,
concatenate, tile, squeeze, integrate
9. a) Program using panda 65-71
b) Program using matplotlib use minimum 5 plotting techniques
10. a) Graph using matplotlib 72-75
11. a) Vector using matplotlib 76-77

2
Python Lab Manual

Exercise 1

a) Installation and environment setup of python

#I have used google colab for python.


#google-google colab-new file will be created-start working.

b) Write a program to demonstrate the use of basic data types.

Integer=5
Float=78.9
String='Suchetha'
Tuple=(45,78,32.8,'Suchetha')
List=[45,90,'Hello']
Set={78,89,67}
print(type(Integer))
print(type(Float))
print(type(String))
print(type(Tuple)) print(type(List))
print(type(Set))

<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>
<class 'set'>

c) Write a program to demonstrate the operators and expressions.

A=1653
B=7863
#Arthematic operators
print("ARTHEMATIC OPERATORS")
print("Addition:",A+B)#Addition
print("Subraction:",A-B)#Subtraction
print("Multiplication:",A*B)#Multiplication
print("Float division:",A/B)#Division(float)
print("Integer division:",A//B)#Division(int)
print("Remaider:",A%B)#Modulus

3
Python Lab Manual
print("Power:",A**B)#Exponentiation

print("\nASSIGNMENT OPERATORS")
#Assignment operators
X=542647
print("X is :",X)
X+=3 #X=X+3
print("X is :",X)
X-=3 #X=X-3
print("X is :",X)
X*=3 #X=X*
print("X is :",X)
X//=3 #X=X//3
print("X is :",X)
X%=3 #X=X%3
print("X is :",X)
X**=3 #X=X**3
print("X is :",X)
X&=3 #X=X&3
print("X is :",X)
X|=3 #X=X|3
print("X is :",X)
X^=3 #X=X^3
print("X is :",X)
X<<=3 #X=X<<3
print("X is :",X)
X>>=3 #X=X>>3
print("X is :",X)
X/=3 #X=X/3
print("X is :",X)

#Comparison operators
print("\nCOMPARISON OPERATORS")
print("A==B: ",A==B)
print("A!=B: ",A!=B)
print("A<B: ",A<B)
print("A>B: ",A>B)
print("A<=B: ",A<=B)
print("A>=B: ",A>=B)

#Logical operators
print("\nLOGICAL OPERATORS")
print("A>10 and B<10: ",A>10 and
B<10) print("A>10 or B<10: ",A>10
or B<10)
print("not(A>10 and B<10): ",not(A>10 and B<10))

#Membership operators
print("\nMEMBERSHIP OPERATIONS")

4
Python Lab Manual
L=["Apple","Mango"]
print("Pineapple is there in L:","Pineapple" in L)#in
print("Pineapple is not there in L:","Pineapple" not in L)#not in
print("Mango is there in L:","Mango" in L)#in
print("Mango is not there in L:","Mango" not in L)#not in

#Identity operators
print("\nIDENTITY OPERATORS")
print("A is B: ",A is B)#is-checks if both are same
print("A is not B: ",A is not B)#is not-checks if both not are same

#Bitwise operators
print("\nBITWISE OPERATORS")
print("And:",A&B)#And
print("Or:",A|B)#Or
print("Binary left shift:",A<<2)#Binary Left shift by 2
print("Binary right shift:",B>>2)#Binary Right shift
by 2 print("Binary Xor:",A^B)#Binary Xor
print("Binary one's complement:",~A)#Binary one's complement(NOT)

OutPut:
ARTHEMATIC OPERATORS
Addition: 9516
Subraction: -6210
Multiplication: 12997539
Float division: 0.2102251049217856
Integer division: 0
Remaider: 1653
Power:190303875322563709653989761043708948896755897273709912141338919820843374057302736273715

ASSIGNMENT OPERATORS
X is : 542647
X is : 542650
X is : 542647
X is : 1627941
X is : 542647
X is : 1
X is : 1
X is : 1
X is : 3
X is : 0
X is : 0
X is : 0
X is : 0.0

COMPARISON OPERATORS
A==B: False A!
=B: True A<B:
True
A>B:False
A<=B:True A>=B:
False

LOGICAL OPERATORS
5
Python Lab Manual
A>10 and B<10: False A>10
or B<10: True
not(A>10 and B<10): True

MEMBERSHIP OPERATIONS
Pineapple is there in L: False
Pineapple is not there in L: True
Mango is there in L: True
Mango is not there in L: False

IDENTITY OPERATORS
A is B: False
A is not B: True

BITWISE OPERATORS
And: 1589
Or: 7927
Binary left shift: 6612
Binary right shift: 1965
Binary Xor: 6338
Binary one's complement: -1654

d) Write a program to demonstrate the functions and parameters passing techniques

#Without return and without parameter passing


def wor_wop():
print("Enter integer a:")
a=int(input())
print("Enter integer b:")
b=int(input())
sum=a+b
print("Sum of a+b:",sum)
wor_wop()

Enter integer a:
21
Enter integer b:
11
Sum of a+b: 32

1#without return and with parameter


passing def wor_wp(a,b):
sum=a+b
print("Sum of a+b:",sum)
print("Enter integer a:")
a=int(input())
print("Enter integer b:")
b=int(input())
wor_wp(a,b)

6
Python Lab Manual

Enter integer a:
11
Enter integer b:
12
Sum of a+b: 23

#with return and without parameter


passing def wr_wop():
print("Enter integer
a:") a=int(input())
print("Enter integer
b:") b=int(input())
sum=a+b
return sum
sum=wr_wop()
print("sum of a+b: ",sum)

Enter integer a:
90
Enter integer b:
21
sum of a+b: 111

#with return and with parameter


passing def wr_wp(a,b):
sum=a+b
return sum
print("Enter integer a:")
a=int(input())
print("Enter integer b:")
b=int(input())
sum=wr_wp(a,b)
print("sum of a+b: ",sum)
Enter integer a:11
Enter integer b:11
sum of a+b: 22

Exercise 2
7
Python Lab Manual

a) Write a program to implement

i)modules ii)packages iii)built-in functions

# Import built-in module


random from random import *

print(dir(random))

[' call ', ' class ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', '
ge

# module math
import math
from math import pi,sqrt,
factorial print(math.pi)
print(sqrt(16))
print(factorial(6))

from math import *


print(e)
print(pi)

3.141592653589793
4.0
720
2.718281828459045
3.141592653589793

#greet module named


greet.py def
SayHello(name):
print("Hello ", name)

#funtion module named


functions.py def sum(x,y):
return x+y

def average(x,y): return (x+y)/2

def power(x,y): return x**y

8
Python Lab Manual

#import a module from package


from mypackages import
function function.power(3,2)

from mypackage.functions import


sum sum(10,20)

#to check the available


modules help('modules')

atexit hmac profile


traitlets atomicwrites holidays
progressbar tree
attr holoviews prometheus_client tty
audioop html promise
turtle audioread html5lib
prompt_toolkit tweepy
autograd http pstats typeguard
autoreload httpimport psutil types
babel httplib2 psycopg2
typing
backcall httplib2shim pty
typing_extensions base64 humanize
ptyprocess tzlocal
bdb hyperopt pvectorc unicodedata
bin ideep4py pwd unittest
binascii idna py
uritemplate binhex imageio py_compile
urllib
9
Python Lab Manual
bisect imagesize pyarrow urllib3
bleach imaplib pyasn1 uu
blis imblearn pyasn1_modules uuid
bokeh imgaug pyclbr vega_datasets
boost imghdr pycocotools venv
bottleneck imp pycparser vis
branca importlib pyct warnings
bs4 importlib_metadata pydata_google_auth wasabi
bson importlib_resources pydoc wave
builtins imutils pydoc_data
wcwidth bz2 inflect pydot
weakref
cProfile iniconfig pydot_ng webbrowser
cachecontrol inspect pydotplus
webencodings cached property install
pydrive werkzeug

10
Python Lab Manual
Cachetools intervaltree pyemd Wheel
caffe2 io pyexpat widgetsnbextension
Calendar ipaddress pyglet Wordcloud
Catalogue ipykernel pygments Wrapt
Certify ipykernel_launcher pygtkcompat Wsgiref
Cffi ipython_genutils pylab Xarray
Cftime ipywidgets pymc3 Xdrlib
Cgi isympy pymeeus Xgboost
Cgitb itertools pymongo Xkit
Chardet itsdangerous pymystem3 Xlrd
charset_normalizer jax pynvml Xlwt
Chess jaxlib pyparsing Xml
Chunk jdcal pyrsistent Xmlrpc
Click jedi pysndfile Xxlimited
Client jieba pystan Xxsubtype
Cloudpickle jinja2 pytest Yaml
Cmake joblib python_utils Yellowbrick
Cmath jpeg4py pytz Zict
Cmd json pyviz_comms Zipapp
Cmdstanpy jsonschema pywt Zipfile
Code jupyter pyximport Zipimport
Codecs jupyter_client qdldl Zipp
Codeop jupyter_console qtconsole Zlib
Colab jupyter_core qtpy Zmq
Collections jupyterlab_pygments queue
Colorcet jupyterlab_widgets quopri

Enter any module name to get more help. Or, type "modules spam" to search for modules whose name or summary contain the
string "spam".
#build in functions
print("Hello world")
print(int(8.0))
print(float(8))
print(complex(8))
a=input(int())

Hello
world 8
8.0
(8+0j)
67

11
Python Lab Manual
Exercise 3

Write a program to implement

i)list ii)tuple iii)dictionary

#i)List
List = []
print("Blank List: ")
print(List)
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
List = ["Car", "Cat", "Fish"] print("\nList
Items: ")
print(List[0])
print(List[2])

List = [['Car', 'Cat'] , ['Fish']]


print("\nMulti-Dimensional List: ")
print(List)

OUTPUT:
Blank List:[]

List of numbers:
[10, 20, 14]

List Items:
Car Fish

Multi-Dimensional List:
[['Car', 'Cat'], ['Fish']]

#ii)Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Tuple1 = ('Hello', 'World')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('Hello')
print("\nTuple with the use of function: ")
print(Tuple1)

OUTPUT:
12
Python Lab Manual
Initial empty Tuple:()

Tuple with the use of


String: ('Hello', 'World')

Tuple using List:(1, 2, 4, 5, 6)

Tuple with the use of function: ('H', 'e', 'l', 'l', 'o')

#iii)Dictionary
Dict = dict({1: 'Nathan', 2: 'James', 3:'USA'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Lap'), (2, 'Top')])
print("\nDictionary with each item as a pair: ")
print(Dict)
print("\nDict keys:",list(Dict.keys()))
values=Dict.values
print("\nDict values:",list(Dict.values()))

OUTPUT:
Dictionary with the use of dict():{1: 'Nathan', 2: 'James', 3: 'USA'}

Dictionary with each item as a pair:{1: 'Lap', 2: 'Top'}

Dict keys: [1, 2]

Dict values: ['Lap', 'Top']

b) Programs on strings,string operations and regular expressions

#Strings
String1 = 'Messi is a Football Player'
print("String with the use of Single Quotes: ")
print(String1)
String1 = "Sun rises in the east"
print("\nString with the use of Double Quotes: ")
print(String1)
String1 = '''Captain Chandler is on the board"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
String1 = '''Live to Rule'''
print("\nCreating a multiline String: ")
print(String1)

OUTPUT:
String with the use of Single Quotes: Messi is a Football Player
String with the use of Double Quotes: Sun rises in the east

13
Python Lab Manual
String with the use of Triple Quotes: Captain Chandler is on the board"
Creating a multiline String:Live to Rule

#String operations
#Accessing characters in string:
String1 = "Everything is OKay"
print("Initial String: ")
print(String1)
print("\nFirst character of String is: ")
print(String1[0])
print("\nLast character of String is: ")
print(String1[-1])

OUTPUT:
Initial String:
Everything is OKay
First character of String is: E
Last character of String is:y

#String Slicing:
String1 = "There is a key"
print("Initial String: ")
print(String1)
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
print("\nSlicing characters between " +"3rd and 2nd last character: ")
print(String1[3:-2])

OUTPUT:
Initial String:
There is a key

Slicing characters from 3-12:re is a k

Slicing characters between 3rd and 2nd last character: re is a k

#Deleting and Updating a String:


#Deleting:
String1 = "Hello, This is Suchetha" print("Initial
String: ")
print(String1)
del String1
print("\nDeleting entire String: ")
print(String1)

OUTPUT:

Initial String:
Hello, This is Suchetha

14
Python Lab Manual
Deleting entire String:

NameError Traceback (most recent call last)


<ipython-input-469-c57c18a7dca4> in <module>()
6 del String1
7 print("\nDeleting entire String: ")
----> 8 print(String1)
9
10

NameError: name 'String1' is not defined

SEARCH STACK OVERFLOW

#Updating :
String1 = "As much as U can"
print("Initial String: ")
print(String1)
String1 = "The more we can" print("\
nUpdated String: ") print(String1)
OUTPUT:
Initial String:
As much as U can

Updated String:
The more we can

#Formatting of String:
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
String1 = "{0:.2f}".format(1/6) print("\
none-sixth is : ")
print(String1)

OUTPUT:
Exponent representation of 165.6458
is 1.656458e+02

one-sixth is :0.17

#Regularexpressions

#\A :import re
txt = "The rain in Spain"
#Check if the string starts with "The"
x = re.findall("\AThe", txt)
print(x)

15
Python Lab Manual
if x:
print("Yes, there is a match!")
else:
print("No match")

OUTPUT:
['The']
Yes, there is a match!

#\b :
import re
txt = "The rain in Spain"
#Check if "ain" is present at the beginning of a WORD:
x = re.findall(r"\bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
[]
No match

#\B:
import re
txt = "The rain in Spain"

#Check if "ain" is present, but NOT at the beginning of a word:


x = re.findall(r"\Bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
['ain', 'ain']
Yes, there is at least one match!

#\d:
import re
txt = "The rain in Spain"
#Check if the string contains any digits (numbers from 0-9):
x = re.findall("\d", txt) print(x)
if x:
print("Yes, there are digits")
else:
print("No digits")

16
Python Lab Manual
OUTPUT:
[]
No digits

#\D:
import re
txt = "The rain in Spain"
#Return a match at every no-digit character:
x = re.findall("\D", txt)
print(x)
if x:
print("Yes, there is no digit match!")
else:
print("Yes are are digits")

OUTPUT:
['T', 'h', 'e', ' ', 'r', 'a', 'i', 'n', ' ', 'i', 'n', ' ', 'S', 'p', 'a', 'i', 'n']
Yes, there is no digit match!

#\s:
import re
txt = "The rain in Spain"
#Return a match at every white-space
character: x = re.findall("\s", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
[' ', ' ', ' ']
Yes, there is at least one match!

#\t:
import re
txt = "The rain in Spain"
#Return a match at every NON white-space character:
x = re.findall("\S", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!

#\w:
17
Python Lab Manual
import re
txt = "The rain in Spain"
#Return a match at every word character (characters from a to Z, digits from 0-9, and the
underscore
x = re.findall("\w", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!

#\W:
import re
txt = "The rain in Spain"
#Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-
spa
x = re.findall("\W", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
[' ', ' ', ' ']
Yes, there is at least one match!

#\Z:
import re
txt = "The rain in Spain"
#Check if the string ends with "Spain"
: x = re.findall("Spain\Z", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")

OUTPUT:
['Spain']

Yes, there is a match!

#[ ] :
import re
txt = "The rain in Spain"
18
Python Lab Manual
#Find all lower case characters alphabetically between "a" and "m"
: x = re.findall("[a-m]", txt)
print(x)
OUTPUT

['h', 'e', 'a', 'i', 'i', 'a', 'i']

#\ :
import re
txt = "That will be 59 dollars"
#Find all digit characters:
x = re.findall("\d", txt) print(x)

OUTPUT:

['5', '9']

#. :
import re
txt = "hello world"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o"
: x = re.findall("he..o", txt)
print(x)

OUTPUT:

['hello']

#^ :
import re
txt = "hello world"
#Check if the string starts with
'hello': x = re.findall("^hello", txt)
if x:
print("Yes, the string starts with 'hello'")
else:
print("No match")

OUTPUT:

Yes, the string starts with 'hello'

#$ :
import re
txt = "hello world"
#Check if the string ends with 'world'
: x = re.findall("world$", txt)
if x:
print("Yes, the string ends with 'world'") else:
print("No match")
19
Python Lab Manual

OUTPUT:
Yes, the string ends with 'world'

#*:
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 0 or more "x" characters
: x = re.findall("aix*", txt)
print(x) if
x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:

['ai', 'ai', 'ai', 'ai']


Yes, there is at least one match!

#+ :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 1 or more "n" characters
: x = re.findall("ain+", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
['ain', 'ain', 'ain', 'ain']
Yes, there is at least one match!

#{} :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "a" followed by exactly two "l" characters
: x = re.findall("al{2}", txt)
print(x) if
x:
print("Yes, there is at least one match!") else:
print("No match")

OUTPUT:

['all']
Yes, there is at least one match!

20
Python Lab Manual

#| :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays"
: x = re.findall("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")

OUTPUT:
['falls']
Yes, there is at least one match!

#[arn] :
import re
txt = "The rain in Spain"
#Check if the string has any a, r, or n
characters: x = re.findall("[arn]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")
OUTPUT:

['r', 'a', 'n', 'n', 'a', 'n']


Yes, there is at least one match!

#[a-n] :
import re
txt = "The rain in Spain"
#Check if the string has any characters between a and
n: x = re.findall("[a-n]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")

OUTPUT:

['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i', 'n']
Yes, there is at least one match!

#[0123] :
txt = "The rain in Spain"
21
Python Lab Manual
#Check if the string has any 0, 1, 2, or 3
digits: x = re.findall("[0123]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")

OUTPUT:

[]
No match

#[0-9]:
import re
txt = "8 times before 11:45 AM"
#Check if the string has any
digits: x = re.findall("[0-9]",
txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print( No match )

OUTPUT:

['8', '1', '1', '4', '5']


Yes, there is at least one match!

Exercise 4

22
Python Lab Manual
a) Implement Class and object

#Class
class Person:
def init (self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("Suchetha",
20)#Object print(p1.name)
print(p1.age
)
p1.myfunc()

OUTPUT:
Sucheth
a 20
Hello my name is Suchetha

b) Write a program to implement static and instance methods,abstract classes and interfaces

#Static Method :
class Mathematics:
def addNumbers(x,
y): return x + y
# create addNumbers static method
Mathematics.addNumbers =
staticmethod(Mathematics.addNumbers) print('The sum is:',
Mathematics.addNumbers(5, 10))

OUTPUT:

The sum is: 15

#Instance Method :
class shape:

# Calling Constructor
def init (self, edge, color):
self.edge = edge
self.color = color

# Instance Method
def
23
Python Lab Manual
finEdges(self):
return self.edge

# Instance Method
def modifyEdges(self,
newedge): self.edge =
newedge
circle = shape(0, 'red')
square = shape(4, 'blue')

# Calling Instance Method


print("No. of edges for circle: "+ str(circle.finEdges()))

# Calling Instance
Method
square.modifyEdges(6)

print("No. of edges for square: "+ str(square.finEdges()))

OUTPUT:
No. of edges for circle:
0 No. of edges for
square: 6

#Abstract Class:
from abc import ABC,

abstractmethod class Polygon(ABC):

@abstractmethod
def
noofsides(self)
: pass

class Triangle(Polygon):

# overriding abstract
method def noofsides(self):
print("I have 3

sides") class

Pentagon(Polygon):

# overriding abstract
method def noofsides(self):
print("I have 5

sides") class

24
Python Lab Manual
Quadrilateral(Polygon):

# overriding abstract
method def noofsides(self):
print("I have 4 sides")

# Driver code
R =
Triangle()
R.noofsides()

K =
Quadrilateral()
K.noofsides()

R =
Pentagon()
R.noofsides()
OUTPUT:

I have 3 sides
I have 4
sides I have
5 sides

#Interfaces:
import zope.interface
class
MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self,
x): pass
def
method2(self)
: pass
print(type(MyInterface))
print(MyInterface. module )
print(MyInterface. name
) # get attribute
x =
MyInterface['x']
print(x)
print(type(x))

ModuleNotFoundError Traceback (most recent call last)


<ipython-input-4-20a110b45956> in
<module>() 1
2 #Interfaces:
----> 3 import zope.interface
4 class MyInterface(zope.interface.Interface):

25
Python Lab Manual
5 x =

zope.interface.Attribute("foo")

ModuleNotFoundError: No module named 'zope'

NOTE: If your import is failing due to a missing package, you


can manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click


the "Open Examples" button below.

OPEN EXAMPLES SEARCH STACK OVERFLOW

c) Write a program to compute distance between two points taking input from the
user (Pythogorean Theorem)

x1=int(input("enter x1 :

")) x2=int(input("enter

x2 : "))

y1=int(input("enter y1 :

")) y2=int(input("enter y2

: "))

result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)

print("Distance between",(x1,x2),"and",(y1,y2),"is : ",result)

OUTPUT:

enter x1 : 45
enter x2 : 67
enter y1 : 89
enter y2 : 56
Distance between (45, 67) and (89, 56) is : 39.66106403010388

26
Python Lab Manual

Exercise 5

a) Write a program to implement Inheritance and polymorphism

#Inheritance :

class

Person(object):

# Constructor
def init (self, name):
self.name = name

# To get name
def getName(self):
return self.name

# To check if this person is an


employee def isEmployee(self):
return False

# Inherited or Subclass (Note Person in


bracket) class Employee(Person):

# Here we return
true def

27
Python Lab Manual
isEmployee(self):
return True

# Driver code
emp = Person("Suchetha") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Sunitha") # An Object of


Employee print(emp.getName(), emp.isEmployee())

OUTPUT:
Suchetha
False Sunitha
True

#Polymorphism :
class DS():
def about(self):
print("DS is new branch in VJIT")

def sections(self):
print("There are 1 section of DS")

def members(self):
print("There are 61 students in DS")

class CSE():
def about(self):
print("CSE is old branch in VJIT")

def sections(self):
print("There are 4 sections of CSE in each year")

def members(self):
print("There are 240 students in CSE first year")

obj_ai= DS()
obj_cse = CSE()
for branch in (obj_ai,
obj_cse): branch.about()
branch.sections(
)
branch.members()

OUTPUT:
DS is new branch in VJIT
There are 1 section of DS
There are 61 students in
DS CSE is old branch in
VJIT
There are 4 sections of CSE in each
28
Python Lab Manual
year There are 240 students in CSE
first year

b) Write a program to implement files

#Create a File :
file = open('new.txt','w')
file.write("This is the write command\n")
file.write("It allows us to write in a particular
file") file.close()

This can be viewed as follows

# Python code to illustrate read()


mode file = open("new.txt", "r")
print (file.read())

OUTPUT:
This is the write command
It allows us to write in a particular file
# Python code to illustrate read() mode character wise
file = open("new.txt",
"r") print (file.read(6))
OUTPUT:
This i

# Python code to illustrate append()


mode file = open('new.txt','a')
file.write("\n This will add this
line") file.close()

After updatation the file will become

29
Python Lab Manual

# a file named "new", will be opened with the reading


mode. file = open('new.txt', 'r')
# This will print every line one by one in the
file for each in file:
print (each)

OUTPUT:
This is the write command

It allows us to write in a particular

file This will add this line

# Python code to illustrate with() alongwith


write() with open("new.txt", "w") as f:
f.write("Hello World!!!") #it will clear the previous data

After this the file will be

# Python code to illustrate split()


function with open("new.txt", "r") as file:
data =
file.readlines() for
line in data:
word =
line.split() print
(word)
OUTPUT:
['Hello', 'World!!!']

#Write:
with open('app.log', 'w') as
f: #first line
f.write('my first file\
n') #second line
f.write('This file\
n') #third line
f.write('contains three lines\n')

30
Python Lab Manual
with open('app.log', 'r') as
f: content = f.readlines()

for line in
content:
print(line)

OUTPUT:
my first
file This
file
contains three lines

This is app.log file

c) Write a program to illustrate exception handling


#Syntax :
age=19
if(amount>18)
print("You are eligible to vote")
File "<ipython-input-426-edc6dfdf0764>", line

#Division by 0: ^
SyntaxError:
marks = 10000 invalid syntax

# performSEARCH STACK
division with OVERFLOW
0a=
marks / 0
print(a)

ZeroDivisionError Traceback (most recent call last)


<ipython-input-495-dc5f74c59cfa> in <module>()
3
4 # perform division with 0
----> 5 a = marks / 0
6 print(a)

ZeroDivisionError: division by zero

SEARCH STACK OVERFLOW

31
Python Lab Manual
3 if(amount>18)
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in


array print ("Fourth element = %d" %(a[3]))

except IndexError:
print ("An error occurred")

OUTPUT:
Second element =
2 An error
occurred

Exercise 6

a) Write a program using scikit-learn to implement K-Means clustering

#Required
libraries import
pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import
LabelEncoder from sklearn.preprocessing
import MinMaxScaler import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

# Load the train and test datasets to create two DataFrames

train_url =
"http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv" train =
pd.read_csv(train_url)

test_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/test.csv"
32
Python Lab Manual
test = pd.read_csv(test_url)

print("***** Train_Set
*****") print(train.head())
print("\n")
print("***** Test_Set
*****") print(test.head())

***** Train_Set *****


PassengerId Survived Pclass ... Fare Cabin Embarked
0 1 0 3 ... 7.2500 NaN S
1 2 1 1 ... 71.2833 C85 C
2 3 1 3 ... 7.9250 NaN S
3 4 1 1 ... 53.1000 C123 S
4 5 0 3 ... 8.0500 NaN S

[5 rows x 12 columns]

***** Test_Set *****


PassengerId Pclass ... Cabin Embarked
0 892 3 ... NaN Q
1 893 3 ... NaN S
2 894 2 ... NaN Q
3 895 3 ... NaN S
4 896 3 ... NaN S

[5 rows x 11 columns]

print("Train
shape",train.shape) print("Test
shape",test.shape)

Train shape (891, 12)


Test shape (418, 11)

print("***** Train_Set
*****")
print(train.describe())
print("\n")
print("***** Test_Set
*****")
print(test.describe())

***** Train_Set *****


PassengerId Survived Pclass ... SibSp Parch Fare
count 891.000000 891.000000 891.000000 ... 891.000000 891.000000 891.000000
mean 446.000000 0.383838 2.308642 ... 0.523008 0.381594 32.204208
std 257.353842 0.486592 0.836071 ... 1.102743 0.806057 49.693429
min 1.000000 0.000000 1.000000 ... 0.000000 0.000000 0.000000
25% 223.500000 0.000000 2.000000 ... 0.000000 0.000000 7.910400

33
Python Lab Manual
50% 446.000000 0.000000 3.000000 ... 0.000000 0.000000 14.454200
75% 668.500000 1.000000 3.000000 ... 1.000000 0.000000 31.000000
max 891.000000 1.000000 3.000000 ... 8.000000 6.000000 512.329200

[8 rows x 7 columns]

***** Test_Set *****


PassengerId Pclass Age SibSp Parch Fare
count 418.000000 418.000000 332.000000 418.000000 418.000000 417.000000
mean 1100.500000 2.265550 30.272590 0.447368 0.392344 35.627188
std 120.810458 0.841838 14.181209 0.896760 0.981429 55.907576

34
Python Lab Manual
min 892.000000 1.000000 0.170000 0.000000 0.000000 0.000000
25% 996.250000 1.000000 21.000000 0.000000 0.000000 7.895800
50% 1100.500000 3.000000 27.000000 0.000000 0.000000 14.454200
75% 1204.750000 3.000000 39.000000 1.000000 0.000000 31.500000
max 1309.000000 3.000000 76.000000 8.000000 9.000000 512.329200

print(train.columns.values
)
print(test.columns.values)

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp'


'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']
['PassengerId' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket'
'Fare' 'Cabin' 'Embarked']

# For the train


set
train.isna().head(
)

PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embark

0 False False False False False False False False False False True Fa

1 False False False False False False False False False False False Fa

2 False False False False False False False False False False True Fa

3 False False False False False False False False False False False Fa

4 False False False False False False False False False False True Fa

# For the test


set
test.isna().head(
)

PassengerId Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked

0 False False False False False False False False False True False

1 False False False False False False False False False True False

2 False False False False False False False False False True False

3 False False False False False False False False False True False

4 False False False False False False False False False True False

#Total missing values


print("*****In the train

35
Python Lab Manual
set*****")
print(train.isna().sum())
print("\n")
print("*****In the test
set*****")
print(test.isna().sum())

*****In the train set*****


PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64

*****In the test set*****


PassengerId 0
Pclass 0
Name 0
Sex 0
Age 86
SibSp 0
Parch 0
Ticket 0
Fare 1
Cabin 327
Embarked 0
dtype: int64

# Fill missing values with mean column values in the train


set train.fillna(train.mean(), inplace=True)

# Fill missing values with mean column values in the test


set test.fillna(test.mean(), inplace=True)

print(train.isna().sum())#remaining missing values in train set

PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
36
Python Lab Manual
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64

print(test.isna().sum())#remaining missing values in test set

PassengerId 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 327
Embarked 0
dtype: int64

train['Ticket'].head()

0 A/5 21171
1 PC 17599
2 STON/O2. 3101282
3 113803
4 373450
Name: Ticket, dtype: object

train['Cabin'].head()

0 NaN
1 C85
2 NaN
3 C123
4 NaN
Name: Cabin, dtype: object

#Age vs survived
g = sns.FacetGrid(train,
col='Survived') g.map(plt.hist, 'Age',
bins=20)

<seaborn.axisgrid.FacetGrid at 0x7f0d20ec3c90>

37
Python Lab Manual

#Age vs survived with pclass


grid = sns.FacetGrid(train, col='Survived', row='Pclass', size=2.2,
aspect=1.6) grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend();
/usr/local/lib/python3.7/dist-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parame
warnings.warn(msg, UserWarning)

train.info()

<class 'pandas.core.frame.DataFrame'> RangeIndex: 891


entries, 0 to 890
Data columns (total 12 columns):
#ColumnNon-Null Count Dtype

0 PassengerId 891 non-null int64


1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null Object
4 Sex 891 non-null Object
5 Age 891 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null Object
9 Fare 891 non-null float64
10 Cabin 204 non-null Object
11 Embarked 889 non-null Object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB

#As some of the colums are non-numeric drop them


train = train.drop(['Name','Ticket', 'Cabin','Embarked','PassengerId'],
axis=1) test = test.drop(['Name','Ticket', 'Cabin','Embarked','PassengerId'],
axis=1) #As passeger ID is not responsible

#Convert the categorical value sex to numeric


value labelEncoder = LabelEncoder()
38
Python Lab Manual
labelEncoder.fit(train['Sex']
)
labelEncoder.fit(test['Sex'])
train['Sex'] =
labelEncoder.transform(train['Sex']) test['Sex'] =
labelEncoder.transform(test['Sex'])

# Let's investigate if you have non-numeric data

left train.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to
890 Data columns (total 7
columns):
# Column Non-Null Count Dtype

0 Survived 891 non-null int64


1 Pclass 891 non-null int64
2 Sex 891 non-null int64
3 Age 891 non-null float64
4 SibSp 891 non-null int64
5 Parch 891 non-null int64
6 Fare 891 non-null float64
dtypes: float64(2),
int64(5) memory usage: 48.9
KB
test.info()

<class
'pandas.core.frame.DataFrame'>
RangeIndex: 418 entries, 0 to 417
Data columns (total 6 columns):
# Column Non-Null Count Dtype

0 Pclass 418 non-null int64


1 Sex 418 non-null int64
2 Age 418 non-null float64
3 SibSp 418 non-null int64
4 Parch 418 non-null int64
5 Fare 418 non-null float64
dtypes: float64(2),
int64(4) memory usage: 19.7
KB

X = np.array(train.drop(['Survived'], 1).astype(float))

Y= np.array(train['Survived'])

kmeans = KMeans(n_clusters=2) # You want cluster the passenger records into 2: Survived or Not
survi kmeans.fit(X)
39
Python Lab Manual

KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,


n_clusters=2, n_init=10, n_jobs=None,
precompute_distances='auto', random_state=None, tol=0.0001,
verbose=0)

correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1

predict_me.shap

e (1, 6)

print(predict_me)

[[ 3. 1. 32. 0. 0. 7.75]]

print(correct/

len(X))#Score

0.6442199775533108

#parameters can be changed as follows


kmeans = kmeans = KMeans(n_clusters=2, max_iter=600, algorithm =
'auto') kmeans.fit(X)

KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,


n_clusters=2, n_init=10, n_jobs=None,
precompute_distances='auto', random_state=None, tol=0.0001,
verbose=0)

correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1

print(correct/len(X))

40
Python Lab Manual

0.6442199775533108

scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

kmeans.fit(X_scaled)

KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,


n_clusters=2, n_init=10, n_jobs=None,
precompute_distances='auto', random_state=None, tol=0.0001,
verbose=0)

correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1

print(correct/len(X))

0.2772166105499439

kmeans.cluster_centers_#6 dimensional space

array([[ 5.79617834e-01, -1.99840144e-15, 3.49292913e-01,


8.67834395e-02, 1.08280255e-01, 8.68188224e-02],
[ 6.94974003e-01, 1.00000000e+00, 3.78057605e-01,
5.37261698e-02, 3.92836511e-02, 4.98193221e-02]])

b) Program to calculate information gain and entropy

The entropy (very common in Information Theory) characterizes the (im)purity of an arbitrary collection
of examples

If we have a set with k different values in it, we can calculate the entropy as follows:

Where P(valuei) is the probability of getting the ith value when randomly selecting one from the set. So, for
41
Python Lab Manual
the set R = {a,a,a,b,b,b,b,b}

let us consider the following example

import numpy as
np import math
import pandas as pd

Data=np.array([["Jeff",32,0,1,1,1],["Pete",25,1,1,0,1],["Anne",33,1,1,0,1],["Natalie",26,0,0,1,0],["
["Sarah",29,1,0,1,0],["David",35,1,0,0,1],["Eric",28,1,1,1,0],["Mike",20,0,1,0,1],["Karen",38,
Data=pd.DataFrame(Data,columns=("Names","Age","Apple_pie","Potato_salad","Sushi","Mid_west"))

Data

42
Python Lab Manual
Names Age Apple_pie Potato_salad Sushi Mid_west

0 Jeff 32 0 1 1 1

1 Pete 25 1 1 0 1

2 Anne 33 1 1 0 1

3 Natalie 26 0 0 1 0

4 Stella 30 1 1 1 1

5 Rob 25 1 0 0 1

6 Joe 42 1 1 0 1

7 Jim 38 1 1 0 1

8 Lisa 36
def calc_entropy(column): 1 1 0 0
# Compute the counts of each unique value in the
9 Sarah 29 1 0 1 0
column counts = np.bincount(column)
# Divide
10 by the35total column
David 1 length to get0 a 0 1
probability probabilities = counts / len(column)
11 Eric 28 1 1 1 0
# Initialize the entropy to
12 Mike 20 0 1 0 1
0 entropy = 0
# Loop through 38
13 Karen the probabilities,
1 and add0 each one
0 to the 1total
entropy for prob in probabilities:
14ifMegan
prob > 0:31 0 0 1 0
# use log from math and set base to
2 entropy += prob * math.log(prob,
2)

return -entropy

If we want to split the data as follows with root node of potato salad

43
Python Lab Manual

Here target value is mid_west column

def calc_information_gain(data, split_name,

target_name): # Calculate the original entropy


original_entropy = calc_entropy(data[target_name])

#Find the unique values in the


column values =
data[split_name].unique()

# Make two subsets of the data, based on the unique


values left_split = data[data[split_name] == values[0]]
right_split = data[data[split_name] == values[1]]

# Loop through the splits and calculate the subset


entropies to_subtract = 0
for subset in [left_split, right_split]:
prob = (subset.shape[0] / data.shape[0])
to_subtract += prob * calc_entropy(subset[target_name])

44
Python Lab Manual
# Return information gain
return original_entropy - to_subtract

calc_entropy(Data["Mid_west"])#entropy before

split 0.9182958340544896

45
Python Lab Manual
#Information gain when splitted by potato_salad
column
calc_information_gain(Data,"Potato_salad","Mid_west")

0.0597731301493174

columns = ['Apple_pie', 'Potato_salad',

'Sushi'] def highest_info_gain(columns):


#Intialize an empty dictionary for information
gains information_gains = {}

#Iterate through each column name in our


list for col in columns:
#Find the information gain for the column
information_gain = calc_information_gain(Data, col, 'Mid_west')
#Add the information gain to our dictionary using the column name as the
ekey information_gains[col] = information_gain

print("Information gains:

",information_gains) #Return the key with the

highest value
return max(information_gains, key=information_gains.get)

Best_split=highest_info_gain(columns)
print("The data has to be splitted by ",Best_split," in order to get more information gain")

Information gains: {'Apple_pie': 0.03170514719803608, 'Potato_salad': 0.0597731301493174, 'Su


The data has to be splitted by Sushi in order to get more information gain

46
Python Lab Manual
So we
need to
split the

data as
follows in c) Program to implement perceptron
order to
get more
informati
on gain

47
Python Lab Manual
from centers=2,cluster_std=1.05,
sklearn random_state=2)
import
datasets
X, Y =
datasets.mak
e_blobs(n_sa
mples=150,n_
features=2,

#Plotting
fig = plt.figure(figsize=(10,8))
plt.plot(X[:, 0][Y == 0], X[:, 1][Y== 0], 'r^')
plt.plot(X[:, 0][Y == 1], X[:, 1][Y == 1], 'bs')
plt.xlabel("feature 1")
plt.ylabel("feature 2")
plt.title('Random Classification Data with 2 classes')

Text(0.5, 1.0, 'Random Classification Data with 2 classes')

print(X)

[[-5.32783010e-01 -
1.64847081e+00] [-5.50226372e-01
-1.16166152e+01]
[ 1.38862276e+00 -
48
Python Lab Manual
1.43580590e+00] [ 1.37033956e+00
-6.40220712e-01] [-8.80606388e-
01 -9.70946740e+00] [-
2.22746033e+00 -1.01019963e+01]
[-3.83660791e+00 -
9.36311253e+00] [-2.61500332e-01
-1.80587922e+00]
[ 1.18267985e+00 -7.12729660e-
01] [-8.91135194e-01 -
8.05385981e+00] [-3.42244116e+00
-9.43290706e+00] [-
3.24159714e+00 -7.66373146e+00]
[-8.14411765e-02 -
1.76413571e+00] [ 2.82215236e+00
-1.76342807e+00]
[ 1.90632766e+00 -
2.43499725e+00] [ 1.12041042e+00
-2.18272234e+00] [ 4.12652646e-
01 -9.79048994e-01] [-
1.61986103e+00 -9.03645942e+00]
[ 1.24676117e+00 -7.71255216e-
01] [-2.01362140e+00 -
1.04568119e+01]

49
Python Lab Manual
[-6.48510353e-01 -9.47763290e+00]
[ 1.90763236e+00 -6.71105011e-
01] [-7.57264801e-01 -
9.34864598e+00] [ 2.18263294e+00
-9.04732063e-01]
[ 1.53216357e+00 -
1.64513848e+00] [ 1.12431439e+00
-4.99224897e-01]
[ 1.19440189e+00 -
1.98887161e+00] [-2.43377785e+00
-7.81776395e+00] [ 3.50550070e-
01 -1.66237773e+00] [-
7.52076469e-01 -1.07890279e+01]
[ 8.37695007e-01 2.82956613e-
01] [ 1.86418091e+00 -
6.31399082e-01] [ 2.07793008e+00
-1.63900470e+00] [-
3.16320932e+00 -1.03653101e+01]
[ 2.09100144e+00 1.43914678e-01]
[-1.51976189e+00 -
1.16545682e+01] [ 1.57354644e+00
-2.17601731e+00] [-
1.23648559e+00 -1.06552971e+01]
[-2.89251066e-01 6.01148326e-
01] [ 2.60959954e-01 -
9.83393657e+00] [ 1.39785819e+00
-1.10283073e+01] [-8.24930811e-
01 -8.13917717e+00] [-
1.63748148e+00 6.23742032e-01]
[-1.76520757e+00 -
9.11304244e+00] [ 5.01485985e-01
-2.61100847e+00] [ 6.65365354e-
01 9.58359846e-01] [-
1.05318015e+00 -1.14330184e+01]
[ 6.02120538e-01 -
9.93193935e+00] [-8.79142411e-01
-8.88688615e+00] [ 3.69806196e-
01 -8.65765515e-02] [-
1.94963972e+00 -1.07284683e+01]
[ 1.05673513e+00 -
2.69907047e+00] [ 2.16363071e+00
-8.46207098e+00] [-4.14163801e-
01 -8.17085180e+00] [-
4.78938837e-02 -1.19422587e+01]
[-1.47904469e+00 -
9.56255496e+00] [-1.01070298e+00
-1.05196934e+01] [-
1.94651523e+00 -8.94765931e+00]
[-2.76985304e+00 -
9.74583819e+00]

print(Y)

[1 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 0 1 0 1 1 1 0 1 0 1
0 1 0 0 0 1 0 1 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 1 0 1 1 1
1 0 1 0 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 0 0 1 0

50
Python Lab Manual
1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 0 1 0 1 0 0 0 0 1 0
1 1]

Step function

def step_func(z):
return 1.0 if (z > 0) else 0.0

Perceptron update rule

#Backward propogation
def perceptron(X, y, lr, epochs):

# X --> Inputs.
# y --> labels/target.
# lr --> learning
rate.
# epochs --> Number of iterations.

# m-> number of training


examples # n-> number of
features
m, n = X.shape

# Initializing parapeters(theta) to
zeros. # +1 in n+1 for the bias term.
theta = np.zeros((n+1,1))

# Empty list to store how many examples


were # misclassified at every iteration.
n_miss_list = []

# Training.
for epoch in range(epochs):

51
Python Lab Manual

# variable to store
#misclassified. n_miss = 0

# looping for every example.


for idx, x_i in enumerate(X):

# Insering 1 for bias, X0 = 1.


x_i = np.insert(x_i, 0, 1).reshape(-1,1)

# Calculating prediction/hypothesis.
y_hat = step_func(np.dot(x_i.T, theta))

# Updating if the example is


misclassified. if (np.squeeze(y_hat) -
y[idx]) != 0:
theta += lr*((y[idx] - y_hat)*x_i)

# Incrementing by
1. n_miss += 1

# Appending number of misclassified


examples # at every iteration.
n_miss_list.append(n_miss

) return theta, n_miss_list

m, n = X.shape
theta = np.zeros((n+1,1))
theta

array([[0.],[0.],[0.]])

theta, miss_l = perceptron(X, Y, 0.5, 100)

theta

array([[5. ],[0.7442977 ],[0.84692166]])

miss_l

[14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

#Forward
propogation/prediction
x_test=[[2.7525,-3.7423]]

52
Python Lab Manual
x_test = np.insert(x_test, 0, 1).reshape(-
1,1) x_test

array([[ 1. ],[2.7525],[-3.7423]])

y_test= step_func(np.dot(x_test.T, theta))#.T for


transform y_test

1.0

Exercise 7

a)Generate a decision tree.Find the depth of decision trees and observe the
results,then propose some changes in DecisionTreeClassifier function to limit.

import numpy as np
import pandas as pd
from sklearn.datasets import
load_iris from sklearn import tree
from sklearn.model_selection import train_test_split

iris = load_iris()
X, Y= iris.data, iris.target
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.4,random_state=6)
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, Y_train)

array([[5.1, 3.5, 1.4, 0.2],


[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
[5.4, 3.9, 1.7, 0.4],
[4.6, 3.4, 1.4, 0.3],
[5. , 3.4, 1.5, 0.2],
[4.4, 2.9, 1.4, 0.2],

53
Python Lab Manual
[4.9, 3.1, 1.5, 0.1],
[5.4, 3.7, 1.5, 0.2],
[4.8, 3.4, 1.6, 0.2],
[4.8, 3. , 1.4, 0.1],
[4.3, 3. , 1.1, 0.1],
[5.8, 4. , 1.2, 0.2],
[5.7, 4.4, 1.5, 0.4],
[5.4, 3.9, 1.3, 0.4],
[5.1, 3.5, 1.4, 0.3],
[5.7, 3.8, 1.7, 0.3],
[5.1, 3.8, 1.5, 0.3],
[5.4, 3.4, 1.7, 0.2],
[5.1, 3.7, 1.5, 0.4],
[4.6, 3.6, 1. , 0.2],
[5.1, 3.3, 1.7, 0.5],
[4.8, 3.4, 1.9, 0.2],
[5. , 3. , 1.6, 0.2],
[5. , 3.4, 1.6, 0.4],
[5.2, 3.5, 1.5, 0.2],
[5.2, 3.4, 1.4, 0.2],
[4.7, 3.2, 1.6, 0.2],
[4.8, 3.1, 1.6, 0.2],
[5.4, 3.4, 1.5, 0.4],
[5.2, 4.1, 1.5, 0.1],
[5.5, 4.2, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.2],
[5. , 3.2, 1.2, 0.2],
[5.5, 3.5, 1.3, 0.2],
[4.9, 3.6, 1.4, 0.1],
[4.4, 3. , 1.3, 0.2],
[5.1, 3.4, 1.5, 0.2],
[5. , 3.5, 1.3, 0.3],
[4.5, 2.3, 1.3, 0.3],
[4.4, 3.2, 1.3, 0.2],
[5. , 3.5, 1.6, 0.6],
[5.1, 3.8, 1.9, 0.4],
[4.8, 3. , 1.4, 0.3],
[5.1, 3.8, 1.6, 0.2],
[4.6, 3.2, 1.4, 0.2],
[5.3, 3.7, 1.5, 0.2],
[5. , 3.3, 1.4, 0.2],
[7. , 3.2, 4.7, 1.4],
[6.4, 3.2, 4.5, 1.5],
[6.9, 3.1, 4.9, 1.5],
[5.5, 2.3, 4. , 1.3],
[6.5, 2.8, 4.6, 1.5],
[5.7, 2.8, 4.5, 1.3],
[6.3, 3.3, 4.7, 1.6],
[4.9, 2.4, 3.3, 1. ],
[6.6, 2.9, 4.6, 1.3],

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
54
Python Lab Manual
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

iris.target_names

array(['setosa', 'versicolor', 'virginica'], dtype='<U10')

iris.feature_names

['sepal length
(cm)', 'sepal width
(cm)', 'petal
length (cm)',
'petal width (cm)']

tree.plot_tree(clf)

[Text(125.55000000000001, 201.90857142857143, 'X[2] <= 2.45\ngini = 0.666\nsamples = 90\nvalue


Text(83.7, 170.84571428571428, 'gini = 0.0\nsamples = 28\nvalue = [28, 0, 0]'),
Text(167.4, 170.84571428571428, 'X[3] <= 1.65\ngini = 0.499\nsamples = 62\nvalue = [0, 32, 30
Text(83.7, 139.78285714285715, 'X[0] <= 7.1\ngini = 0.062\nsamples = 31\nvalue = [0, 30, 1]')
Text(41.85, 108.72, 'gini = 0.0\nsamples = 30\nvalue = [0, 30, 0]'),
Text(125.55000000000001, 108.72, 'gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]'),
Text(251.10000000000002, 139.78285714285715, 'X[2] <= 5.05\ngini = 0.121\nsamples = 31\nvalue
Text(209.25, 108.72, 'X[1] <= 2.9\ngini = 0.444\nsamples = 6\nvalue = [0, 2, 4]'),
Text(167.4, 77.65714285714284, 'gini = 0.0\nsamples = 3\nvalue = [0, 0, 3]'),
Text(251.10000000000002, 77.65714285714284, 'X[1] <= 3.1\ngini = 0.444\nsamples = 3\nvalue
= Text(209.25, 46.59428571428572, 'X[2] <= 4.9\ngini = 0.5\nsamples = 2\nvalue = [0, 1,
1]'),
Text(167.4, 15.531428571428563, 'gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]'),
Text(251.10000000000002, 15.531428571428563, 'gini = 0.0\nsamples = 1\nvalue = [0, 1, 0]'),
Text(292.95, 46.59428571428572, 'gini = 0.0\nsamples = 1\nvalue = [0, 1, 0]'),
Text(292.95, 108.72, 'gini = 0.0\nsamples = 25\nvalue = [0, 0, 25]')]

print(clf)
print("Max depth:",clf.max_depth)#max depth

55
Python Lab Manual
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
max_depth=None, max_features=None,
max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0,
presort='deprecated', random_state=None,
splitter='best')
Max depth: None

Ypred=clf.predict(X_test)

Ypred

array([0, 2, 0, 0, 2, 1, 1, 0, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 0, 0, 2,
0, 0, 1, 1, 1, 2, 0, 1, 0, 1, 0, 0, 1, 2, 1, 2, 1, 0, 0, 2, 1, 1,
0, 0, 1, 0, 0, 1, 2, 2, 2, 0, 2, 0, 0, 0, 1, 2])

from sklearn.metrics import


accuracy_score Score=accuracy score(Y
test,Ypred)

print(Score)

0.95

clf =
tree.DecisionTreeClassifier(max_depth=8,random_state=5) clf
= clf.fit(X_train, Y_train)

print(clf)
print("Max depth:",clf.max_depth)#max depth

DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',


max_depth=8, max_features=None,
max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, min_samples_leaf=1,
min_samples_split=2,
min_weight_fraction_leaf=0.0,
presort='deprecated', random_state=5,
splitter='best')
Max depth: 8

Ypred=clf.predict(X_test)

Ypred

array([0, 2, 0, 0, 2, 1, 2, 0, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 0, 0, 2,
0, 0, 1, 1, 1, 2, 0, 1, 0, 1, 0, 0, 1, 2, 1, 2, 1, 0, 0, 2, 1, 1,
0, 0, 1, 0, 0, 1, 2, 2, 2, 0, 2, 0, 0, 0, 1, 2])

56
Python Lab Manual

Score=accuracy_score(Y_test,Ypred)
print(Score)#Score is changed from 0.95 to

0.96 0.9666666666666667

Exercise 8

a)Calculating with matrices using numpy:


inv,pinv,matrix_rank,solve,lstsq,svd,transpose,eig,sort,linspace,meshgrid,mgrid,ogrid,concatenat
e,tile,squeeze

import numpy as np

#inv

x = np.array([[1,2],
[3,4]]) y =
np.linalg.inv(x)
print(x
)
print(y
)

[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
#pinv

x = np.array([[1,2],
[3,4]]) y =
np.linalg.pinv(x)
print(x
)
print(y
)

[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]

#matrix_rank

57
Python Lab Manual
x = np.array([[1,2],[3,4]])
y =
np.linalg.matrix_rank(x)
print(x)
print(y)

[[1 2]
[3 4]]
2

#solve

x = np.array([[1,2],[3,4]])
#1*x0+2*x1=8,3*x0+4*x1 b=np.array([8,16])
y = np.linalg.solve(x,b) #x0 are x1 are solved
print(x)
print(y)

[[1 2]
[3 4]]
[0. 4.]

#lstsq-least square solution

#Fit a line, y = mx + c, through some noisy data-

points: x = np.array([0, 1, 2, 3])


y = np.array([-1, 0.2, 0.9, 2.1])

#By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut
the

#We can rewrite the line equation as y = Ap, where A = [[x 1]] and p = [[m], [c]]. Now use lstsq to

A = np.vstack([x,
np.ones(len(x))]).T print("A is:\
n",A)

m, c = np.linalg.lstsq(A, y, rcond=None)
[0] print("m and c are:",m,c)

import matplotlib.pyplot as plt


_ = plt.plot(x, y, 'o', label='Original data', markersize=10)
_ = plt.plot(x, m*x + c, 'r', label='Fitted line')
_ =
plt.legend()
plt.show()
A is:
[[0. 1.][1. 1.][2. 1.][3. 1.]]
m and c are: 0.9999999999999999 -0.9499999999999995
58
Python Lab Manual

#svd-Singular value

decomposition #Here A=U S VT


#A=mx
n
#U=mx
m
#S=mxn diagonal values are singular
values #V=nxn
A=np.array([[1,2],[2,1],[1,1]])
U,S,VT=np.linalg.svd(A,full_matrices=True)
print("Left singular vectors")
print(U)
print("\nSingular
values") print(S)
print("\nRight singular
vectors")
print(np.transpose(VT))

smat=np.zeros((3,2))
smat[:2,:2]=np.diag(S) print("\
nSmat:")
print(smat)

A_D=np.linalg.multi_dot([U,smat,VT]
) print("\nBefore decomposition")
print(A)
print("\nAfter
decomposition") print(A_D)

Left singular vectors


[[-6.39602149e-01 7.07106781e-01 -3.01511345e-01]
[-6.39602149e-01 -7.07106781e-01 -3.01511345e-01]
[-4.26401433e-01 -1.16837442e-16 9.04534034e-
01]]
59
Python Lab Manual

Singular values
[3.31662479 1. ]

Right singular vectors

[[-0.70710678 -0.70710678]
[-0.70710678 0.70710678]]

Smat:
[[3.31662479 0. ]
[0. 1. ]
[0. 0. ]]

Before decomposition
[[1 2]
[2 1]
[1 1]]

After decomposition
[[1. 2.]
[2. 1.]
[1. 1.]]

#transpose

A=np.array([[1,2],[2,1],[3,9]])
print("Orginal matrix
A") print(A)
print("\nTranspose of matrix
A:") print(np.transpose(A))

Orginal matrix A
[[1 2]
[2 1]
[3 9]]

Transpose of matrix
A: [[1 2 3]
[2 1 9]]

#eig-Ax=Lamba*x

A=np.array([[4,1],[6,3]])
print("Orginal array
A") print(A)
e_val,e_vec=np.linalg.eig(A)

print("\nEigen
value:") print(e_val)

print("\nEigen

60
Python Lab Manual
vector:") print(e_vec)

print("\nAx=")
print(np.dot(A,e_vec))

print("\
nLamba*x")
print(e_val*e_vec
)

Orginal array
A [[4 1][6 3]]

Eigen
value: [6.
1.]

61
Python Lab Manual
Eigen vector:
[[ 0.4472136 -0.31622777]
[ 0.89442719 0.9486833 ]]

Ax=
[[ 2.68328157 -0.31622777]
[ 5.36656315 0.9486833 ]]

Lamba*x
[[ 2.68328157 -0.31622777]
[ 5.36656315 0.9486833 ]]

#sort

a = np.array([[1,4],
[3,1]]) print("Orginal
array:")
print(a)

b=np.sort(a) # sort along the last


axis print("\nsort along the last axis")
print(b)

c=np.sort(a, axis=None) # sort the flattened


array print("\nsort the flattened array")
print(c)

d=np.sort(a, axis=0) # sort along the first


axis print("\nsort along the first axis")
print(d)

Orginal array:
[[1 4]
[3 1]]

sort along the last


axis [[1 4]
[1 3]]

sort the flattened


array [1 1 3 4]

sort along the first


axis [[1 1]
[3 4]]

#linspace

print("5 Numbers between 2.0 and 3.0")


print(np.linspace(2.0, 3.0, num=5))

print("\n5 Numbers between 2.0 and 3.0 without end


62
Python Lab Manual
point") print(np.linspace(2.0, 3.0, num=5,
endpoint=False))

print("\n5 Numbers between 2.0 and 3.0 with end point and
step") print(np.linspace(2.0, 3.0, num=5, retstep=True))

5 Numbers between 2.0 and


3.0 [2. 2.25 2.5 2.75 3.
]

5 Numbers between 2.0 and 3.0 without end


point [2. 2.2 2.4 2.6 2.8]

5 Numbers between 2.0 and 3.0 with end point and


step (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

#meshgrid

na, nb = (5, 10)


a = np.linspace(1, 2, na)
b = np.linspace(1, 2, nb)
xa, xb = np.meshgrid(a,
b) print(xa)
print(xb)

xa, xb = np.meshgrid(a,
b,sparse=True) print(xa)
print(xb)

[[1. 1.25 1.5 1.75 2. ]


[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]
[1. 1.25 1.5 1.75 2. ]]
[[1. 1. 1. 1. 1. ]
[1.11111111 1.11111111 1.11111111 1.11111111 1.11111111]
[1.22222222 1.22222222 1.22222222 1.22222222 1.22222222]
[1.33333333 1.33333333 1.33333333 1.33333333 1.33333333]
[1.44444444 1.44444444 1.44444444 1.44444444 1.44444444]
[1.55555556 1.55555556 1.55555556 1.55555556 1.55555556]
[1.66666667 1.66666667 1.66666667 1.66666667 1.66666667]
[1.77777778 1.77777778 1.77777778 1.77777778 1.77777778]
[1.88888889 1.88888889 1.88888889 1.88888889 1.88888889]
[2. 2. 2. 2. 2. ]]
[[1. 1.25 1.5 1.75 2. ]]
[[1. ][1.11111111][1.22222222][1.33333333][1.44444444][1.55555556][1.66666667]
[1.77777778][1.88888889][2. ]]
63
Python Lab Manual

#mgrid

print(np.mgrid[0:5,0:5])

print(np.mgrid[-1:1:5j])

[[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]

[4 4 4 4 4]
]
[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
]]
[-1. -0.5 0. 0.5 1. ]

#ogrid

print(np.ogrid[-1:1:5j])

print(np.ogrid[0:5,0:5])

[-1. -0.5 0. 0.5 1. ]


[array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]])]

#concatenate

a = np.array([[1, 2], [3,


4]]) b = np.array([[5, 6]])
print(np.concatenate((a, b), axis=0))

print(np.concatenate((a, b.T),

axis=1))

print(np.concatenate((a, b), axis=None))


64
Python Lab Manual

[[1 2]
[3 4]
[5 6]]
[[1 2 5]
[3 4 6]]
[1 2 3 4 5 6]

#tile

a = np.array([0, 1, 2])
print(np.tile(a, 2))

print("\n",np.tile(a, (2, 2)))

print("\n",np.tile(a, (2, 1, 2)))

b = np.array([[1, 2], [3, 4]])


print("\n","\n",np.tile(b, 2))

print("\n",np.tile(b, (2,

1))) c = np.array([1,2,3,4])
print("\n","\n",np.tile(c,(4,1)))

[0 1 2 0 1 2]

[[0 1 2 0 1 2]
[0 1 2 0 1 2]]

[[[0 1 2 0 1 2]]

[[0 1 2 0 1 2]]]

[[1 2 1 2]
[3 4 3 4]]

[[1 2]
[3 4]
[1 2]
[3 4]]

[[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]]

65
Python Lab Manual

#squeeze
x = np.array([[[0], [1], [2]]])
print(x.shape)

print(np.squeeze(x).shape)

print(np.squeeze(x, axis=0).shape)

print(np.squeeze(x,

axis=2).shape) x =

np.array([[1234]])
print(x.shape)

print(np.squeeze(x))

print(np.squeeze(x).shape

) print(np.squeeze(x)

[()])

(1, 3, 1)
(3,)
(3, 1)
(1, 3)
(1, 1)
123
4
()
1234

66
Python Lab Manual

Exercise 9

a) Program using Pandas

#download a dataset

from sklearn.datasets import load_iris


import pandas as pd

data=load_iris()

data.feature_names

['sepal length
(cm)', 'sepal width
(cm)', 'petal
length (cm)',
'petal width (cm)']

X=data.dat
a X

array([[5.1, 3.5, 1.4, 0.2],


[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
[5.4, 3.9, 1.7, 0.4],
[4.6, 3.4, 1.4, 0.3],
[5. , 3.4, 1.5, 0.2],
[4.4, 2.9, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.1],
[5.4, 3.7, 1.5, 0.2],
[4.8, 3.4, 1.6, 0.2],
[4.8, 3. , 1.4, 0.1],
[4.3, 3. , 1.1, 0.1],
[5.8, 4. , 1.2, 0.2],
[5.7, 4.4, 1.5, 0.4],
[5.4, 3.9, 1.3, 0.4],
[5.1, 3.5, 1.4, 0.3],
[5.7, 3.8, 1.7, 0.3],
[5.1, 3.8, 1.5, 0.3],
[5.4, 3.4, 1.7, 0.2],
[5.1, 3.7, 1.5, 0.4],
[4.6, 3.6, 1. , 0.2],
[5.1, 3.3, 1.7, 0.5],
67
Python Lab Manual
[4.8, 3.4, 1.9, 0.2],
[5. , 3. , 1.6, 0.2],
[5. , 3.4, 1.6, 0.4],
[5.2, 3.5, 1.5, 0.2],
[5.2, 3.4, 1.4, 0.2],
[4.7, 3.2, 1.6, 0.2],
[4.8, 3.1, 1.6, 0.2],
[5.4, 3.4, 1.5, 0.4],
[5.2, 4.1, 1.5, 0.1],
[5.5, 4.2, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.2],
[5. , 3.2, 1.2, 0.2],
[5.5, 3.5, 1.3, 0.2],
[4.9, 3.6, 1.4, 0.1],
[4.4, 3. , 1.3, 0.2],
[5.1, 3.4, 1.5, 0.2],
[5. , 3.5, 1.3, 0.3],
[4.5, 2.3, 1.3, 0.3],
[4.4, 3.2, 1.3, 0.2],
[5. , 3.5, 1.6, 0.6],
[5.1, 3.8, 1.9, 0.4],
[4.8, 3. , 1.4, 0.3],
[5.1, 3.8, 1.6, 0.2],

68
Python Lab Manual
[4.6, 3.2, 1.4, 0.2],
[5.3, 3.7, 1.5, 0.2],
[5. , 3.3, 1.4, 0.2],
[7. , 3.2, 4.7, 1.4],
[6.4, 3.2, 4.5, 1.5],
[6.9, 3.1, 4.9, 1.5],
[5.5, 2.3, 4. , 1.3],
[6.5, 2.8, 4.6, 1.5],
[5.7, 2.8, 4.5, 1.3],
[6.3, 3.3, 4.7, 1.6],
[4.9, 2.4, 3.3, 1. ],
[6.6, 2.9, 4.6, 1.3],

Y=data.targe
t Y

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

print(type(data)
) print(X.shape)
print(Y.shape)

<class
'sklearn.utils.Bunch'> (150,
4)
(150,)

datapd=pd.DataFrame(x,columns=data.feature_names)

datapd

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

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

... ... ... ... ...

145 6.7 3.0 5.2 2.3

69
Python Lab Manual
146 6.3 2.5 5.0 1.9

147 6.5 3.0 5.2 2.0

148 6.2 3.4 5.4 2.3

149 5.9 3.0 5.1 1.8

150 rows × 4 columns

datapd.isnull().sum()
sepal length (cm) 0
sepal width (cm) 0
petal length (cm) 0
petal width (cm) 0
dtype: int64

d = pd.Series([i for i in range(100,127)], index=[i for i in


range(0,27)]) d

0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
10 110
11 111
12 112
13 113
14 114
15 115
16 116
17 117
18 118
19 119
20 120
21 121
22 122
23 123
24 124
25 125
26 126
dtype: int64

b) Program using matplotlib-5 plotting techniques


70
Python Lab Manual

import matplotlib.pyplot as plt

#Plot
x= [1,2,3,4]
y=[2,4,6,8]
plt.plot(x,y,'g', linewidth=3.0)

plt.ylabel('number*2'
)
plt.xlabel("number")
plt.title('Plot')
plt.show()

#Bar
Number_of_people = [1,3,5,7,9]
age= [5,2,7,8,2]

plt.bar(age,Number_of_people ,label="Example 1",color='r')


plt.legend()

plt.xlabel("age")
plt.ylabel("no.of

people") plt.title("Bar

graph")

71
Python Lab Manual
plt.show()

# histogram

students_marks= [11,12,13,56,67,45,22,21]

marks = [0,10,20,30,40,50,60,70,80,90,100]

plt.hist(students_marks, marks, color="c", rwidth=1) # histogram is representing frequnecy of each


v

plt.xlabel('marks')
plt.ylabel('no. of

students')

plt.title('Histogram')

plt show()

x1=[8,8.5,9,9.5,10,10.5,11]

72
Python Lab Manual
y1=[3,3.5,3.7,4,4.5,5,5.2]

plt.scatter(x1,y1, label= "stars", color= "green", m arker=


"*",)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter
Plot') plt.legend()
plt.show()

#pie
Cities=["Hyderabad","Delhi","Agra"

] people_like= [23, 17, 35]

# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(people_like, labels
=Cities ) plt.title("Pie chart")
# show plot
plt.show()

73
Python Lab Manual

Exercise 10

a)Graph using matplotlib

#Simple plot
# x axis
values x =
[1,2,3,8,6]
# corresponding y axis
values y = [2,4,1,7,8]

# plotting the
points plt.plot(x,
y)

# naming the x axis


plt.xlabel('x -
axis') # naming the y
axis
plt.ylabel('y - axis')

# giving a title to my
graph plt.title('My first
graph!')

# function to show the


plot plt.show()

74
Python Lab Manual

# line 1 points
x1 =
[2,4,6,7,8]
y1 = [2,4,1,9,0]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1",color="b")

# line 2 points
x2 =
[1,2,3,6,1,]
y2 = [4,1,3,10,5]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2",color='r')

# naming the x axis


plt.xlabel('x -
axis') # naming the y
axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')

# show a legend on the


plot plt.legend()

# function to show the


plot plt.show()

#customise
# x axis values

75
Python Lab Manual
x =
[1,2,3,4,5,6]
# corresponding y axis
values y = [2,4,1,5,2,6]

# plotting the points


plt.plot(x, y, color='green', linestyle='--', linewidth = 3, marker='*',
markerfacecolor='red', markersize=15)

# setting x and y axis


range plt.ylim(1,8)
plt.xlim(1,8)

# naming the x axis


plt.xlabel('x -
axis') # naming the y
axis
plt.ylabel('y - axis')

# giving a title to my
graph
plt.title('Customizations!'
)

# function to show the


plot plt.show()

#subplot
# x axis values
x1 =
[1,2,3,8,6]
# corresponding y axis
values y1 = [2,4,1,7,8]

76
Python Lab Manual
x2=[4,6,2,3,9]
y2=[6,7,1,1,2]

x3=[2,4,5,7,1,3]
y3=[6,2,3,1,1,9]
# plotting the
points
plt.subplot(2,3,1)
plt.plot(x1, y1,'b*--')

plt.subplot(2,3,2)
plt.plot(x2, y2,'g--')

plt.subplot(2,3,3)
plt.plot(x3, y3,'ro--')

plt.subplot(2,3,4)
plt.plot(x3, y3,'bo--')

77
Python Lab Manual
[<matplotlib.lines.Line2D at 0x7f0d211c4650>]

#pie
# defining labels
firstyear = ['AI', 'CSE', 'EEE', 'IT']

# portion covered by each


label slices =
[60,240,180,120]

# color for each label


colors = ['r', 'y', 'g', 'b']

# plotting the pie chart


plt.pie(slices, labels = firstyear, colors=colors,
startangle=90, shadow = True, explode = (0.1, 0, 0,
0), radius =1, autopct = '%1.1f%%')

plt.title("No of students in first


year") # plotting legend
plt.legend()

# showing the
plot plt.show()

78
Python Lab Manual
Exercise 11

a)Vector using matplotlib


import numpy as np
from matplotlib import pyplot as plt

#2D
u=[4,-1]
v=[-1,9]

fig=plt.figur
e
ax=plt.axes()
ax.set_xlim([-5,5])
ax.set_ylim([-10,10])

start=[0,0]
ax.quiver(start[0],start[1],u[0],u[1],color='blue')
ax.quiver(start[0],start[1],v[0],v[1],color='green')

<matplotlib.quiver.Quiver at 0x7f9f98f5e6d0>

#3D
u=[4,5,-7]
v=[-1,4,9]
w=[1,-3,5]

fig=plt.figure
ax=plt.axes(projection='3d'
) ax.set_xlim([-1,10])
ax.set_ylim([-5,8])
ax.set_zlim([-10,10])

79
Python Lab Manual
start=[0,0,0]
ax.quiver(start[0],start[1],start[2],u[0],u[1],u[2],color='blue')
ax.quiver(start[0],start[1],start[2],v[0],v[1],v[2],color='green')
ax.quiver(start[0],start[1],start[2],w[0],w[1],w[2],color='red')
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7f9fa76a7a90>

80

You might also like