0% found this document useful (0 votes)
31 views16 pages

AI Lab3

lab 3

Uploaded by

Muhammad Umair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views16 pages

AI Lab3

lab 3

Uploaded by

Muhammad Umair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Lab 3-A

Graphs:

Data Visualization is very much important task in machine learning. For data visualization in python
we use matplotlib and sklearn modules. With the usage of these modules we can have clear view of
how data points are rendered in 2D space. Below are some exercises which would help you to plot
graphs in an easier way.
Example of visualization:

Created by Ms. Farwa Kazmi


Example-1: Line Plot in Python.

import matplotlib.pyplot as plt

import numpy as np

# Prepare the data

# Generates 100 samples between 0 to 10

x = np.linspace(0, 10, 100)

# Plot the data

plt.plot(x, x, label='linear')

# Add a legend

plt.legend()

# Show the plot

plt.show()

Example-2: Scatter Plot in Python.

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3, 4, 5], [10, 15,


20, 25, 30, 35], color='lightblue',
linewidth=3)

plt.scatter([0.3, 3.8, 1.2, 2.5], [15,


25, 9, 26], color='darkgreen',
marker='o')

plt.show()

Created by Ms. Farwa Kazmi


Example-3: Sub Plots in Python.
import matplotlib.pyplot as plt

fig = plt.figure()

# Set up Axes

sub1 = fig.add_subplot(221)

sub2 = fig.add_subplot(222)

sub3 = fig.add_subplot(223)

sub4 = fig.add_subplot(224)

# Scatter the data

sub1.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub2.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub3.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

sub4.scatter(np.linspace(0, 1, 5), np.linspace(0, 5, 5))

# Show the plot

plt.show()

Example-4: Iris Dataset with 2 Features.

Created by Ms. Farwa Kazmi


from sklearn import datasets

import matplotlib.pyplot as plt

iris = datasets.load_iris()

plt.scatter(iris.data[:,0],iris.data[:,1],
c=iris.target)

plt.colorbar(ticks=[0, 1, 2])

plt.show()

Example-4: 3D Plots in Python.

from mpl_toolkits import mplot3d

from sklearn import datasets

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

ax = plt.axes(projection='3d')

iris = datasets.load_iris()

ax.scatter(iris.data[:,0],

iris.data[:,1],iris.data[:,2],
c=iris.target)

ax.set_xlabel('Petal width')

ax.set_ylabel('Sepal length')

ax.set_zlabel('Petal length')

Created by Ms. Farwa Kazmi


Lab Journal 3A:
Visualize the following data in python. Please provide the reason for the choice of graph.

Feature 1 Feature 2

12 4

11 5

8 1

6 4

9 3

6 6

10 2

import matplotlib.pyplot as plt

fig1 = [12, 11, 8, 6, 9, 6, 10]


fig2 = [4, 5, 1, 4, 3, 6, 2]

plt.scatter(fig1, fig2, color="black", marker="o")

plt.show()

Created by Ms. Farwa Kazmi


Linear: Visualize continuous data.
Scatter: Identifying relationships between two variables/datasets for comparison.

Lab 3-B
Classes & Inheritance:
Class:
The word 'class' can be used when describing the code where the class is defined.
A variable inside a class is known as an Attribute
A function inside a class is known as a method

• A class is like a
– Prototype
– Blue-print
– An object creator
• A class defines potential objects
– What their structure will be
– What they will be able to do
• Objects are instances of a class
– An object is a container of data: attributes
– An object has associated functions: methods

Syntax:
# Defining a class
class class_name:
[statement 1]
[statement 2]
[statement 3] [etc]

‘self’ keyword:
The first argument of every class method, including init , is always a reference to the
current instance of the class. It represents the instance or objects of a class and binds the
attributes of a class with specific arguments. The use of self in Python helps to differentiate
between the instance attributes (and methods) and local variables.

If you do not want the variables of your class to be shared by all instances of the class, you
can declare variables within your class without self.

Example1: x = MyClass() print (x.i) print (x.f() )


class MyClass:
i = 12345
def f(self):

Created by Ms. Farwa Kazmi


return 'hello
world'

Created by Ms. Farwa Kazmi


Example2:
class Complex:
def init (self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print (x.r," ",x.i )

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables are for attributes and methods
shared by all instances of the class. Instance variables are variables whose value is assigned inside a
constructor or method with self whereas class variables are variables whose value is assigned in the class.
Defining instance variables using a constructor.

Output:

Created by Ms. Farwa Kazmi


Example-2:

class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print (x.r," ",x.i )

Example-3:
class Shape:
def __init__(self,x,y): #The __init__ function always runs first
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"

def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale

a=Shape(3,4)
print (a.area())

Inheritance Example:

class Square(Shape):
def __init__(self,x):
self.x = x
self.y = x

class DoubleSquare(Square):
def __init__(self,y):
self.x = 2 * y
self.y = y
Created by Ms. Farwa Kazmi
def perimeter(self):
return 2 * self.x + 2 * self.y

Created by Ms. Farwa Kazmi


Module:
A module is a python file that (generally) has only definitions of variables, functions, and
classes.
Example: Module name mymodule.py

# Define some variables:


ageofqueen = 78

# define some functions


def printhello():
print ("hello")
# define a class
class Piano:
def __init__(self):
self.type = input("What type of piano?: ")
self.height = input("What height (in feet)?: ")
self.price = input("How much did it cost?: ")
self.age = input("How old is it (in years)?: ")

def printdetails(self):
print ("This piano is a/an " + self.height + " foot")
print (self.type, "piano, " + self.age, "years old and costing " +
self.price + " dollars.")

Importing module in main program:


### mainprogam.py ##
# IMPORTS ANOTHER MODULE

import mymodule
print (mymodule.ageofqueen )
cfcpiano = mymodule.Piano()
cfcpiano.printdetails()

Another way of importing the module is:


from mymodule import Piano, ageofqueen
print (ageofqueen)
cfcpiano = Piano()
cfcpiano.printdetails()

Created by Ms. Farwa Kazmi


Lab Journal 3-B:
1. Create a class name basic_calc with following attributes and methods;
Two integers (values are passed with instance creation)
Different methods such as addition, subtraction, division, multiplication
Create another class inherited from basic_calc named s_calc which should have the
following additional methods;
Factorial, x_power_y,log, ln etc

from mpl_toolkits import mplot3d


from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
import math

class basic_calc:
def __init__(self, a, b):
self.a = a
self.b = b

def addition(self):
return self.a + self.b

def subtraction(self):
return self.a - self.b

def multiplication(self):
return self.a * self.b

def division(self):
if self.b != 0:
return self.a / self.b
else:
return "Division by zero is undefined"

class s_calc(basic_calc):

def factorial(self):
if self.a >= 0:
return math.factorial(self.a)
else:
return "Factorial not defined for negative numbers"

Created by Ms. Farwa Kazmi


def x_power_y(self):
return self.a**self.b

def log(self):
if self.a > 0:
return math.log10(self.a)
else:
return "Logarithm undefined for non-positive numbers"

def ln(self):
if self.a > 0:
return math.log(self.a)
else:
return "Natural logarithm undefined for non-positive numbers"

# Create an instance of basic_calc


calc = basic_calc(10, 5)
print("Basic Calculator:")
print("Addition:", calc.addition())
print("Subtraction:", calc.subtraction())
print("Multiplication:", calc.multiplication())
print("Division:", calc.division())

# Create an instance of s_calc


sci_calc = s_calc(5, 3)
print("\nScientific Calculator:")
print("Factorial of a:", sci_calc.factorial())
print("a^b (5^3):", sci_calc.x_power_y())
print("Log10 of a:", sci_calc.log())
print("Natural log (ln) of a:", sci_calc.ln())

Created by Ms. Farwa Kazmi


2. Modify the classes created in the above task under as follows:
Create a module name basic.py having the class name basic_calc with all the attributes
and methods defined before.
Now import the basic.py module in your program and do the inheritance step defined
before i.e.
Create another class inherited from basic_calc named s_calc which should have the
following additional methods;
Factorial, x_power_y, log, ln etc

Calculator.py

from mpl_toolkits import mplot3d


from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
import math

class basic_calc:
def __init__(self, a, b):
self.a = a
self.b = b

def addition(self):
return self.a + self.b

def subtraction(self):
return self.a - self.b

def multiplication(self):
return self.a * self.b

def division(self):
if self.b != 0:
return self.a / self.b
else:
return "Division by zero is undefined"

class s_calc(basic_calc):

def factorial(self):
if self.a >= 0:
return math.factorial(self.a)

Created by Ms. Farwa Kazmi


else:
return "Factorial not defined for negative numbers"

def x_power_y(self):
return self.a**self.b

def log(self):
if self.a > 0:
return math.log10(self.a)
else:
return "Logarithm undefined for non-positive numbers"

def ln(self):
if self.a > 0:
return math.log(self.a)
else:
return "Natural logarithm undefined for non-positive numbers"

calculator-module.py
import calculator as calculate

# Create an instance of basic_calc


calc = calculate.basic_calc(10, 5)
print("Basic Calculator:")
print("Addition:", calc.addition())
print("Subtraction:", calc.subtraction())
print("Multiplication:", calc.multiplication())
print("Division:", calc.division())

# Create an instance of s_calc


sci_calc = calculate.s_calc(5, 3)
print("\nScientific Calculator:")
print("Factorial of a:", sci_calc.factorial())
print("a^b (5^3):", sci_calc.x_power_y())
print("Log10 of a:", sci_calc.log())
print("Natural log (ln) of a:", sci_calc.ln())

Created by Ms. Farwa Kazmi


3. Create the module of the class created before and call its parameters in other file

# Create an instance of basic_calc


calc = calculate.basic_calc(10, 5)
print("Basic Calculator:")
print("Addition:", calc.addition())
print("Subtraction:", calc.subtraction())
print("Multiplication:", calc.multiplication())
print("Division:", calc.division())

# Create an instance of s_calc


sci_calc = calculate.s_calc(5, 3)
print("\nScientific Calculator:")
print("Factorial of a:", sci_calc.factorial())
print("a^b (5^3):", sci_calc.x_power_y())
print("Log10 of a:", sci_calc.log())
print("Natural log (ln) of a:", sci_calc.ln())

Created by Ms. Farwa Kazmi

You might also like