Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Exercise: 1

Date :
TOY PROBLEM

Problem Statement : Given an integer N and an array of seats[] where N is the number of people
standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the i th row of
the movie theater. The task is to find the maximum amount a theater owner can make by selling
movie tickets to N people. Price of a ticket is equal to the maximum number of empty seats among
all the rows.

Algorithm:

1. Initialize queue q insert all seats array elements to the queue.


2. Tickets sold and the amount generated to be set to 0.
3. If tickets sold < N (People in the queue) and q top > 0
4. Then remove top element from queue and update total amount
5. Repeat step 3 and 4 until tickets sold = number of people in the queue.

Optimization technique: This problem can be solved by using a priority queue that will store the
count of empty seats for every row and the maximum among them will be available at the top.

1. Create an empty priority_queue q and traverse the seats[] array and insert all elements
into the priority_queue.
2. Initialize two integer variable ticketSold = 0 and ans = 0 that will store the number of
tickets sold and the total collection of the amount so far.
3. Now check while ticketSold < N and q.top() > 0 then remove the top element from the
priority_queue and update ans by adding top element of the priority queue. Also store this
top value in a variable temp and insert temp – 1 back to the priority_queue.
4. Repeat these steps until all the people have been sold the tickets and print the final result.

Tool:VS Code and Python 3.9.0


Programming code :

def maxAmount(M, N, seats):


q = []
for i in range(M):
q.append(seats[i])
ticketSold = 0
ans = 0
q.sort(reverse = True)
while (ticketSold < N and q[0] > 0):
ans = ans + q[0]
temp = q[0]
q = q[1:]
q.append(temp - 1)
q.sort(reverse = True)
ticketSold += 1
return ans
if __name__ == '__main__':
seats = []
rows = int(input("Enter number of rows available : "))
for i in range(0, rows):
empty = int(input())
seats.append(empty)
print(seats)
M = len(seats)
N = int(input("Enter the number of People standing in the queue : "))
print("Maximum Profit generated = ", maxAmount(N, M, seats))

Output screen shots:

Result: Successfully found out the maximum amount the theater owner can make by selling
movie tickets to N people for a movie.

5
Exercise: 2

Date :
GRAPH COLORING PROBLEM

PROBLEM STATEMENT : Given a graph, color its edges such that no two adjacent have

the same color using minimum number of colors and return the Chromatic number.

ALGORITHM :

Initialize:

1. Color first vertex with first color.

Loop for remaining V-1 vertices.:

1. Consider the currently picked vertex and color it with the lowest numbered color that has

not been used on any previously colored vertices adjacent to it.

2. If all previously used colors appear on vertices adjacent to v, assign a new color to it.

3. Repeat the following for all edges.

4. Index of color used is the chromatic number.

OPTIMIZATION TECHNIQUE:

Graph coloring problem is to assign colors to certain elements of a graph subject to certain

constraints.

Vertex coloring is the most common graph coloring problem. The problem is, given m colors,

find a way of coloring the vertices of a graph such that no two adjacent vertices are colored using

1
the same color. The other graph coloring problems like Edge Coloring (No vertex is incident to

two edges of same color) and Face Coloring (Geographical Map Coloring) can be transformed

into vertex coloring.

Chromatic Number: The smallest number of colors needed to color a graph G is called its

chromatic number. For example, the following can be colored at least 2 colors.

CODE - EDGE COLORING :

import matplotlib.pyplot as plt

import networkx as nx

from matplotlib.patches import Polygon

import numpy as np

G = nx.Graph()

colors = {0:"red", 1:"green", 2:"blue", 3:"yellow"}

G.add_nodes_from([1,2,3,4,5])

G.add_edges_from([(1,2), (1,3), (2,4), (3,5), (4,5)])

nodes = list(G.nodes)

edges = list(G.edges)

2
color_lists = []

color_of_edge = []

some_colors = ['red','green','blue','yellow']

for i in range(len(nodes) + 1):

color_lists.append([])

color_of_edge.append(-1)

def getSmallestColor(ls1,ls2):

i=1

while(i in ls1 or i in ls2):

i=i+1

return i

#iterate over edges

i=0

for ed in edges:

newColor = getSmallestColor(color_lists[ed[0]],color_lists[ed[1]])

color_lists[ed[0]].append(newColor)

color_lists[ed[1]].append(newColor)

color_of_edge[i] = newColor

i=i+1

3
# Makin graph again

G = nx.Graph()

for i in range(len(edges)):

G.add_edge(edges[i][0],edges[i][1],color=some_colors[color_of_edge[i]-1])

colors = nx.get_edge_attributes(G,'color').values()

nx.draw(G, edge_color=colors, with_labels=True, width=2)

plt.show()

OUTPUT :

4
CODE - VERTEX COLORING :

import matplotlib.pyplot as plt

import networkx as nx

G = nx.Graph()

colors = {0:"red", 1:"green", 2:"blue"}

G.add_nodes_from([1,2,3,4,5])

G.add_edges_from([(1,2), (1,3), (2,4), (3,5), (4,5)])

d = nx.coloring.greedy_color(G, strategy = "largest_first")

node_colors = []

for i in sorted (d.keys()):

node_colors.append(colors[d[i]])

nx.draw(G, node_color = node_colors, with_labels = True, width = 5)

plt.show()

5
OUTPUT :

CODE - FACE COLORING :

import networkx as nx

G = nx.Graph()

colors = {0:"red", 1:"green", 2:"blue", 3:"yellow"}

G.add_nodes_from([1,2,3,4,5])

G.add_edges_from([(1,2), (1,3), (2,4), (3,4), (4,5)])

nodes = list(G.nodes)

edges = list(G.edges)

some_colors = ['red','green','blue','yellow']

no_of_faces = len(edges)+2-len(nodes)-1

6
def regionColour(regions):

print("NO OF FACES : "+str(regions))

for i in range(1,regions+1):

print("FACE 1 : "+some_colors[i%4])

regionColour(no_of_faces)

OUTPUT :

RESULT :

Edge, vertex and face coloring problem which are together known as graph coloring problem
solved and visualized in an optimized way using greedy approach.

7
Experiment No. 4a - Implementation of Breadth First Search
Aim
To implement BFS in Python.
ALGORITHM
Algorithm:

1. Create a queue
2. Mark each new node as visited and put that node into the queue
3. While Queue is non-empty:
4. Remove the head of Queue
5. Mark and enqueue all (unvisited) neighbors.

Program
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited_bfs = []
queue = []
def bfs(visited_bfs, graph, node):
visited_bfs.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


if neighbour not in visited_bfs:
visited_bfs.append(neighbour)
queue.append(neighbour)

visited = set()
print("BFS:" , end =" ")
bfs(visited_bfs, graph, 'A')

Results
Breadth First Search was successfully implemented in Python.
Experiment No. 4b - Implementation of Depth First Search
Aim
To implement DFS in Python.
ALGORITHM
The DFS algorithm works as follows:

1. Start by putting any one of the graph's vertices on top of a stack.


2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes.
4. Add the ones which aren't in the visited list to the top of the stack.
5. Keep repeating steps 2 and 3 until the stack is empty.
Program
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited_bfs = []
queue = []
visited = set()

def dfs(visited, graph, node):


if node not in visited:
print (node, end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("DFS:" , end =" ")
dfs(visited, graph, 'A')

Results
Depth First Search was successfully implemented in Python.
NAME:
REG.NO:
EXPERIMENT 5 – DEVELOPING BEST FIRST SEARCH AND A* ALGORITHM FOR
REAL WORLD PROBLEMS

AIM
To write a python program for developing best first search and a* algorithm for real world problems.

ALGORITHM
1.First, create a list of all the characters that need assigning to pass to Solve.
2.If all characters are assigned, return true if puzzle is solved, false otherwise.
3.Otherwise, consider the first unassigned character for (every possible choice among the digits
not in use)make that choice and then recursively try to assign the rest of the characters.
4.If all digits have been tried and nothing worked, return false to trigger backtracking.

PROGRAM
import time
import itertools
def timeit(fn):
def wrapper():
start = time.perf_counter()
ret = fn()
elapsed = time.perf_counter() - start
print("%s took %2.fs" % (fn.__name__, elapsed))
return ret
return wrapper

@timeit
def solve1():
for s in range(1,10):
for e in range(0,10):
for n in range(0,10):
for d in range(0,10):
for m in range(1,10):
for o in range(0,10):
for r in range(0,10):
for y in range(0,10):
if distinct(s,e,n,d,m,o,r,y):
send = 1000*s + 100*e + 10*n + d
more = 1000*m + 100*o + 10*r + e
money = 10000*m + 1000*o + 100*n + 10*e + y
if send + more == money:
return send, more, money
def distinct(*args):
return len(set(args)) == len(args)

@timeit
def solve2():
letters = ('s','e','n','d','m','o','r','y')
digits = range(10)
for perm in itertools.permutations(digits, len(letters)):
sol = dict(zip(letters, perm))
if sol['s'] == 0 or sol['m'] == 0:
continue
send = 1000*sol['s'] + 100*sol['e'] + 10*sol['n'] + sol['d']
more = 1000*sol['m'] + 100*sol['o'] + 10*sol['r'] + sol['e']
money = 10000*sol['m'] + 1000*sol['o'] + 100*sol['n'] + 10*sol['e'] + sol['y']
if send + more == money:
return send, more, money

print(solve1())
print(solve2())

OUTPUT
RESULT
Thus, developing best first search and a* algorithm for real world problems has been done
successfully.
NAME:
REG.NO:
EXPERIMENT 6 – IMPLEMENTATION OF MINIMAX ALGORITHM FOR AN
APPLICATION
AIM
To write a python program for implementation of minimax algorithm for an application.

ALGORITHM
1.Start.

2.Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice between 3
and 5. Being the minimizer it will definitely choose the least among both, that is 3.
3.Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice between 2
and 9. He will choose 2 as it is the least among the two values.
4. Being the maximizer you would choose the larger value that is 3. Hence the optimal move for
the maximizer is to go LEFT and the optimal value is 3.

PROGRAM
import math

def minimax (curDepth, nodeIndex,


maxTurn, scores,
targetDepth):

# base case : targetDepth reached


if (curDepth == targetDepth):
return scores[nodeIndex]

if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
False, scores, targetDepth))

else:
return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
True, scores, targetDepth))
scores = [3, 5, 2, 9, 12, 5, 23, 21]

treeDepth = math.log(len(scores), 2)

print("The optimal value is : ", end = "")


print(minimax(0, 0, True, scores, treeDepth))
OUTPUT

RESULT
Thus, implementation of minimax algorithm for an application has been done successfully.
NAME:
REG. NO:

EXPERIMENT 7 - Implementation of unification and resolution for


real world problems

Aim:
To implement unification with Python.

Algorithm:

Step 1: If Ψ1 or Ψ2 is a variable or constant, then:

a, If Ψ1 or Ψ2 are identical, then return NULL.

b, Else if Ψ1 is a variable:

- then if Ψ1 occurs in Ψ2, then return False

- Else return (Ψ2 / Ψ1)

c, Else if Ψ2 is a variable:

- then if Ψ2 occurs in Ψ1, then return False

- Else return (Ψ1 / Ψ2)

d, Else return False

Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.

Step 3: IF Ψ1 and Ψ2 have a different number of arguments, then return False.

Step 4: Create Substitution list.

Step 5: For i=1 to the number of elements in Ψ1.

a, Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the result
into S.
b, If S = False then returns False

c, If S ≠ Null then append to Substitution list

Step 6: Return Substitution list.

Program:

def get_index_comma(string):

"""

Return index of commas in string

"""

index_list = list()

# Count open parentheses

par_count = 0

for i in range(len(string)):

if string[i] == ',' and par_count == 0:

index_list.append(i)

elif string[i] == '(':

par_count += 1

elif string[i] == ')':

par_count -= 1
return index_list

def is_variable(expr):

"""

Check if expression is variable

"""

for i in expr:

if i == '(':

return False

return True

def process_expression(expr):

"""

input: - expression:

'Q(a, g(x, b), f(y))'

return: - predicate symbol:

Q
- list of arguments

['a', 'g(x, b)', 'f(y)']

"""

# Remove space in expression

expr = expr.replace(' ', '')

# Find the first index == '('

index = None

for i in range(len(expr)):

if expr[i] == '(':

index = i

break

# Return predicate symbol and remove predicate symbol in expression

predicate_symbol = expr[:index]

expr = expr.replace(predicate_symbol, '')

# Remove '(' in the first index and ')' in the last index

expr = expr[1:len(expr) - 1]

# List of arguments
arg_list = list()

# Split string with commas, return list of arguments

indices = get_index_comma(expr)

if len(indices) == 0:

arg_list.append(expr)

else:

arg_list.append(expr[:indices[0]])

for i, j in zip(indices, indices[1:]):

arg_list.append(expr[i + 1:j])

arg_list.append(expr[indices[len(indices) - 1] + 1:])

return predicate_symbol, arg_list

def get_arg_list(expr):

"""

input: expression:

'Q(a, g(x, b), f(y))'

return: full list of arguments:

['a', 'x', 'b', 'y']


"""

_, arg_list = process_expression(expr)

flag = True

while flag:

flag = False

for i in arg_list:

if not is_variable(i):

flag = True

_, tmp = process_expression(i)

for j in tmp:

if j not in arg_list:

arg_list.append(j)

arg_list.remove(i)

return arg_list

def check_occurs(var, expr):

"""
Check if var occurs in expr

"""

arg_list = get_arg_list(expr)

if var in arg_list:

return True

return False

def unify(expr1, expr2):

# Step 1:

if is_variable(expr1) and is_variable(expr2):

if expr1 == expr2:

return 'Null'

else:

return False

elif is_variable(expr1) and not is_variable(expr2):

if check_occurs(expr1, expr2):

return False

else:
tmp = str(expr2) + '/' + str(expr1)

return tmp

elif not is_variable(expr1) and is_variable(expr2):

if check_occurs(expr2, expr1):

return False

else:

tmp = str(expr1) + '/' + str(expr2)

return tmp

else:

predicate_symbol_1, arg_list_1 = process_expression(expr1)

predicate_symbol_2, arg_list_2 = process_expression(expr2)

# Step 2

if predicate_symbol_1 != predicate_symbol_2:

return False

# Step 3

elif len(arg_list_1) != len(arg_list_2):

return False

else:

# Step 4: Create substitution list

sub_list = list()
# Step 5:

for i in range(len(arg_list_1)):

tmp = unify(arg_list_1[i], arg_list_2[i])

if not tmp:

return False

elif tmp == 'Null':

pass

else:

if type(tmp) == list:

for j in tmp:

sub_list.append(j)

else:

sub_list.append(tmp)

# Step 6

return sub_list

if __name__ == '__main__':

# Data 1

f1 = 'p(b(A), X, f(g(Z)))'
f2 = 'p(Z, f(Y), f(Y))'

# Data 2

# f1 = 'Q(a, g(x, a), f(y))'

# f2 = 'Q(a, g(f(b), a), x)'

# Data 3

# f1 = 'Q(a, g(x, a, d), f(y))'

# f2 = 'Q(a, g(f(b), a), x)'

result = unify(f1, f2)

if not result:

print('Unification failed!')

else:

print('Unification successfully!')

print(result)

Output:
Result:

Thus, implementation of unification and resolution is done successfully


using Python.
NAME:
REG. NO:

EXPERIMENT 8 - Implementation of knowledge representation


schemes – Use cases

Aim:
To solve sudoku using knowledge representation.

Algorithm:
1. Start.
2. Find some empty space.
3. Attempt to place the digits 1-9 in that space.
4. Check if that digit is valid in the current spot based on the current board.
5. a. If the digit is valid, recursively attempt to fill the board using steps 1-3.
b. If it is not valid, reset the square you just filled and go back to the previous step.
6. Once the board is full by the definition of this algorithm we have found a solution.
7. Stop.

Program:

size = 9

matrix = [

[5,0,0,0,7,0,0,0,0],

[0,0,0,1,9,0,0,0,0],

[0,9,8,0,0,0,0,6,0],

[8,0,0,0,6,0,0,0,3],

[4,0,0,8,0,3,0,0,1],

[7,0,0,0,2,0,0,0,6],

[0,6,0,0,0,0,2,8,0],

[0,0,0,4,1,9,0,0,5],

[0,0,0,0,8,0,0,7,0]]
def print_sudoku():

for i in matrix:

print (i)

def number_unassigned(row, col):

num_unassign = 0

for i in range(0,size):

for j in range (0,size):

if matrix[i][j] == 0:

row = i

col = j

num_unassign = 1

a = [row, col, num_unassign]

return a

a = [-1, -1, num_unassign]

return a

def is_safe(n, r, c):

for i in range(0,size):
if matrix[r][i] == n:

return False

for i in range(0,size):

if matrix[i][c] == n:

return False

row_start = (r//3)*3

col_start = (c//3)*3;

for i in range(row_start,row_start+3):

for j in range(col_start,col_start+3):

if matrix[i][j]==n:

return False

return True

def solve_sudoku():

row = 0

col = 0

a = number_unassigned(row, col)

if a[2] == 0:
return True

row = a[0]

col = a[1]

for i in range(1,10):

if is_safe(i, row, col):

matrix[row][col] = i

if solve_sudoku():

return True

matrix[row][col]=0

return False

if solve_sudoku():

print_sudoku()

else:

print("No solution")
Output:
Result:

Thus, implementation of knowledge representation schemes is done


successfully.
NAME:
REG. NO:
EXPERIMENT 10 - Block World Problem

Aim: To implement Block World Problem.

Algorithm:
1. Import the necessary header files.

2. Define the necessary functions.

3. Define the necessary enums.

4. Define the necessary structures and maps.

5. Define the necessary prototypes.

6. Print the ouput.

Program:
"""n = int(input("enter number of stacks"))

stac = []

for i in range(n):

temp = input("enter stack 1").split()

stac.append(temp)"""

stac = [['B','A'],['D'],['C']]

finalstac = ['B','C','A','D']

print("initial stack ",stac)

print("goal stack ",finalstac)

nu = 4

intermediate = []

def matrixIndex(st, arg):

for i in range(len(st)):
for j in range(len(st[i])):

if(st[i][j]==arg):

return(i,j)

for i in stac:

for j in i:

j = list(j)

intermediate.append(j)

print("Step 1", intermediate)

for i in range (0,len(finalstac)):

t = finalstac[i]

if(i==0):

flagm,flagn = matrixIndex(intermediate,t)

continue

else:

intermediate[flagm].append(t)

indm,indn = matrixIndex(intermediate,t)

intermediate[indn][indm]=" "

print("step "+str(i+1)+" ",intermediate)

Output:
Result: Thus Block World Problem has been successfully implemented.
NAME:
REG. NO:

EXPERIMENT 11 - Implementation Of Learning Algorithm


For An Application

Aim:
To implement uncertain methods for an application.

Algorithm:

1. Start
2. import all required libraries required.
3. Do data cleaning if required.
4. To understand the data, use visualization and find patterns.
5. Split the dataset for training and testing.
6. Finally predict the accuracy.
7. Stop.

Program:
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):
n = np.size(x)
m_x = np.mean(x)
m_y = np.mean(y)
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
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):


plt.scatter(x, y, color = "m",
marker = "o", s = 30)
y_pred = b[0] + b[1]*x
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()

def main():
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0], b[1]))
plot_regression_line(x, y, b)

if __name__ == "__main__":

main()

Output:

Result:

Thus, implementation of learning algorithm for an application has been


done successfully.
NAME:
REG.NO:
EXPERIMENT 12- DEVELOPMENT OF ENSEMBLE MODEL FOR ANY APPLICATION
AIM
To build the ensemble model using the adaboostclassifier.

ALGORITHM

1. Initially, all observations in the dataset are given equal weights.


2. A model is built on a subset of data.
3. Using this model, predictions are made on the whole dataset.
4. Errors are calculated by comparing the predictions and actual values.
5. While creating the next model, higher weights are given to the data points which were
predicted incorrectly.
6. Weights can be determined using the error value. For instance, higher the error more is the
weight assigned to the observation.
7. This process is repeated until the error function does not change, or the maximum limit of
the number of estimators is reached.

PROGRAM

# Train Adaboost Classifer

from sklearn.ensemble import AdaBoostClassifier

from sklearn import datasets

# Import train_test_split function

from sklearn.model_selection import train_test_split

#Import scikit-learn metrics module for accuracy calculation

from sklearn import metrics

iris = datasets.load_iris()

X = iris.data

y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

abc = AdaBoostClassifier(n_estimators=50,

learning_rate=1)
model = abc.fit(X_train, y_train)

y_pred = model.predict(X_test)

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

from sklearn.ensemble import AdaBoostClassifier

# Import Support Vector Classifier

from sklearn.svm import SVC

#Import scikit-learn metrics module for accuracy calculation

from sklearn import metrics

svc=SVC(probability=True, kernel='linear')

# Create adaboost classifer object

abc =AdaBoostClassifier(n_estimators=50, base_estimator=svc,learning_rate=1)

#Predict the response for test dataset

y_pred = model.predict(X_test)

# Model Accuracy, how often is the classifier correct?

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
OUTPUT

RESULT
Thus, development of ensemble model for any application has been implemented successfully.
NAME:
REG. NO:

EXPERIMENT 13 - Classification model using the gradient boosting


algorithm using Boston Housing Dataset

Aim:
To build the classification model using the gradient boosting algorithm.
Algorithm:

1. Start.
2. Creating a First Base Learner.
3. Calculating the Total Error (TE).
4. Calculating Performance of Stump.
5. Updating Weights.
6. Creating A New Dataset.
7. Stop.

Program:

from sklearn.datasets import make_classification

## defining dataset

X, y = make_classification(n_samples=1000, n_features=20,

n_informative=15, n_redundant=5, random_state=7)

print(X.shape, y.shape)

from numpy import mean

from numpy import std

from sklearn.datasets import make_classification

from sklearn.model_selection import cross_val_score

from sklearn.model_selection import RepeatedStratifiedKFold


from sklearn.ensemble import GradientBoostingClassifier

## defining dataset

X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5,


random_state=7)

## defining the model

model = GradientBoostingClassifier()

## defining the evaluation method

cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)

## Assess the dataset model

n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1)

## production of the study

print('Mean Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))

from sklearn.datasets import make_classification

from sklearn.ensemble import GradientBoostingClassifier

## define dataset

X, y = make_classification(n_samples=1000, n_features=20, n_informative=15,

n_redundant=5, random_state=7)

## define the model

model = GradientBoostingClassifier()

## Fit the entire dataset model


model.fit(X, y)

## make a single prediction

row = [0.2929949, -4.21223056, -1.288332, -2.17849815, -0.64527665, 2.58097719,

0.28422388, -7.1827928, -1.91211104, 2.73729512, 0.81395695, 3.96973717,

-2.66939799, 3.34692332, 4.19791821, 0.99990998, -0.30201875, -4.43170633,

-2.82646737, 0.44916808]

yhat = model.predict([row])

## summarize prediction

print('Predicted Class: %d' % yhat[0])

Output:
Result:

Thus, the classification model using the gradient boosting algorithm is


implemented successfully.
NAME:
REG. NO:

EXPERIMENT 14 - Implementation of NLP programs

AIM: To write a python program for tokenizing a given text, extracting usernames from
emails, spelling corrections in a given text, extracting all the pronouns in a text and removal
of punctuations from the text using artificial intelligence methods.

ALGORITHM: (tokenizing a given text)

1. Get a large enough corpus.


2. Define a desired subword vocabulary size.
3. Split word to sequence of characters.
4. Initialize the vocabulary with all the characters in the text.
5. Build a language model based on the vocabulary.

PROGRAM: (tokenizing a given text)


import nltk

nltk.download('punkt')
nltk.download('stop')
nltk.download('stopwords')
text="It has been proved by statistics, that if everyone wears a mask o
utside home,dreaded ‘second wave’ of the pandemic can be avoided."
tokens=nltk.word_tokenize(text)
for token in tokens:
print(token)

OUTPUT:
ALGORITHM: (extracting usernames from emails)
1) get the input string from user

2) frame a regular expression to check for email validation.

3) match the string with the regular expression

4) if the string satisfies the condition of regular expression, then the email id is valid.

PROGRAM: (extracting usernames from emails)


text= "The new registrations are sheikh709@gmail.com , shaheer101@gmail
.com. If you find any disuptions, kindly contac anant111@gamil.com or d
ev77@gamil.com "
import re
usernames= re.findall('(\S+)@', text)
print(usernames)

OUTPUT:

ALGORITHM: (spelling corrections in a given text)


1. To facility the spell check, corpus is needed.

2. Simply use dataset from sklearn library without pre-processing.

3. Use your domain specific dataset to build a better corpus for your data .

PROGRAM: ( spelling corrections in a given text)


from textblob import TextBlob
text=TextBlob(text)
print(text.correct())

OUTPUT:

ALGORITHM: (extracting all the pronouns in a text)


1. To facility the spell check, corpus is needed.

2. Simply use dataset from sklearn library without pre-processing.

3. Use spacy.load() function from the library to check for pronouns

PROGRAM: (extracting all the pronouns in a text)


import spacy
nlp=spacy.load("en_core_web_sm")
nlp
text="John is happy finally. He had landed his dream job . He told his
mom. She was elated "
nlp=spacy.load("en_core_web_sm")
doc=nlp(text)

for token in doc:


if token.pos_=='PRON':
print(token.text)

OUTPUT:
ALGORITHM: (and removal of punctuations)
1. To facility the spell check, corpus is needed.

2. Simply use dataset from sklearn library without pre-processing.

3. Use token.is_punct function from the library to check for punctuations.

4. If token.is_punct==False then do new_tokens.append(token.text) for removing the punctuations.

PROGRAM: ( and removal of punctuations)


doc=nlp(text)
new_tokens=[]
for token in doc:
if token.is_punct==False:
new_tokens.append(token.text)

" ".join(new_tokens)

OUTPUT:

RESULT: Hence, implementation of NLP programs is done and executed successfully


NAME:
REG. NO:

EXPERIMENT 15 – Applying Deep Learning Methods To Solve An


Application

Aim:
To Apply Deep learning methods for an application.

Algorithm:

1. Start
2. Load the data
3. Examine the data
4. One-hot encode the output
5. Build the model architecture
6. Train the model
7. Evaluate the model
8. Stop.

Program:
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline

np.random.seed(42)

# Loading the data (it's preloaded in Keras)


(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)

print(x_train.shape)
print(x_test.shape)

print(x_train[0])
print(y_train[0])

# One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])

# One-hot encoding the output


num_classes = 2
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
print(y_test.shape)

# Building the model architecture with one layer of length 100


model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.summary()

# Compiling the model using categorical_crossentropy loss, and rmsprop optimizer.


model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])

# Running and evaluating the model


hist = model.fit(x_train, y_train,
batch_size=32,
epochs=10,
validation_data=(x_test, y_test),
verbose=2)

score = model.evaluate(x_test, y_test, verbose=0)


print("Accuracy: ", score[1])

Output:
Result:

Thus, Deep learning for an application has been done successfully.

You might also like