Abhi Lab File
Abhi Lab File
Abhi Lab File
1.2 PROGRAM
import nltk
python
The code below shows that utility Chat is a class that provides logic for building the
chatbot.
print(Chat)
Output:
<class 'nltk.chat.util.Chat'>
The other import you did above was Reflections, which is a dictionary that contains a
set of input text and its corresponding output values. You can examine the dictionary
with the code below. This is an optional dictionary and you can create your own
dictionary in the same format as below.
reflections
Output:
'i': 'you',
'my': 'your',
'your': 'my',
'yours': 'mine',
'you': 'me',
'me': 'you'
}
set_pairs
= [ [
r"my name is (.*)",
["Hello %1, How are you doing today ?",]
],
[
r"hi|hey|hello", ["Hello", "Hey there",]
],
[
r"what is your name?",
["You can call me a chatbot ?",]
],
[
r"how are you ?",
["I am fine, thank you! How can i help you?",]
],
[
r"I am fine, thank you",
["great to hear that, how can i help you?",]
],
[
r"i'm (.*) doing good",
["That's great to hear","How can i help you?:)",]
],
[
r"i am looking for online guides and courses to learn data science, can you
suggest?",
["Pluralsight is a great option to learn data science. You can check their website",]
],
[
r"thanks for the suggestion. do they have great authors and instructors?", ["Yes,
they have the world class best authors, that is their strength;)",]
],
[
r"(.*) thank you so much, that was helpful",
["Iam happy to help", "No problem, you're welcome",]
]
]
After creating the pairs of rules above, we define the chatbot using the code below. The
code is simple and prints a message whenever the function is invoked.
def chatbot():
print("Hi, I'm the chatbot you built")
chatbot()
Output:
Hi, I'm the chatbot you built
The next step is to instantiate the Chat() function containing the pairs and reflections.
chat = Chat(set_pairs, reflections)
print(chat)
Output:
<nltk.chat.util.Chat object at 0x7f49c76e3be0>
You have created a simple rule-based chatbot, and the last step is to initiate the
conversation. This is done using the code below where the converse() function triggers
the conversation.
chat.converse()
if name == " main ":
chatbot()
The code above will generate the following chatbox in your notebook, as shown in the
image below.
Output:
You're ready to interact with the chatbot. Start by typing a simple greeting, "hi", in the
box, and you'll get the response "Hello" from the bot, as shown in the image below.
Output:
You can continue conversing with the Chabot and quit the conversation once you are
done, as shown in the image below.
Output:
Program No: 2
2.2 CODING:
# Tic-Tac-Toe Program using # random number in Python
# Checks whether the player has three # of their marks in a horizontal row
def row_win(board, player): for x in range(len(board)):
win = True
for y in range(len(board)): if board[x, y] != player:
win = False continue
if win == True: return(win)
return(win)
# Checks whether the player has three # of their marks in a vertical row
def col_win(board, player): for x in range(len(board)):
win = True
# Checks whether the player has three # of their marks in a diagonal row
def diag_win(board, player): win = True
y = 0
for x in range(len(board)): if board[x, x] != player:
win = False if win:
return win == True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player: win = False
return win
winner = 0
for player in [1, 2]:
if (row_win(board, player) or col_win(board,player) or
diag_win(board,player)):
winner = player
while winner == 0:
for player in [1, 2]:
board = random_place(board, player) print("Board after " +
str(counter) + " move") print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
print("Winner is: " + str(play_game()))
2.3 OUTPUT:
[[0 0 0]
[0 0 0]
[0 0 0]]
Winner is: 2
Program No: 3
ALPHA-BETA PRUNING
3.2 CODING:
# Returns optimal value for current player #(Initially called for root and
maximizer)
# Driver Code
if name == " main ":
values = [3, 5, 6, 9, 1, 2, 0, -1]
print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))
3.3 OUTPUT:
4.2 CODING:
# Python3 implementation of program to count
# minimum number of steps required to measure # d litre water using jugs
of m liters and n
# liters capacity.
# Driver code
if name == ' main ':
n = 3
m = 5
d = 4
print('Minimum number of steps required is ',minSteps(n, m, d))
4.3 OUTPUT:
bfs(adjacency, "a")
5.3 OUTPUT: BFS
a
b
c
d
e
5.4 PROGRAM: A*
#for each node m,compare its distance from start i.e g(m) to
the #from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
if n == None:
print('Path does not exist!') return None
#define function to return neighbor and its distance #from the passed node
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v] else:
return None
return H_dist[n]
aStarAlgo('A', 'G')
5.5 OUTPUT: A*
HILL-CLIMBING ALGORITHM
Pseudo code
i <- generate an individual randomly
best_so_far <- i
while stopping criterion has not been met:
get i''s bit string and convert it to the problem representation (int or
float) increment or decrement one of the genes by the step size
if the resulting individual has higher fitness
replace i with this individual and increase the step size
else
decrease the step size
if the step size reaches zero and increments and decrements of the current
gene have been tested
move on to the next gene if
i is at a local optimum
if fitness(i) > fitness(best_so_far)
best_so_far <- i
i <- generate an individual randomly
6.3 CODING:
def objective(x):
return x[0]**2.0
if select == 1:
print(number_1, "+", number_2, "=", add(number_1, number_2))
elif select == 2:
print(number_1, "-", number_2, "=", subtract(number_1, number_2))
elif select == 3:
print(number_1, "*", number_2, "=", multiply(number_1, number_2))
elif select == 4:
print(number_1, "/", number_2, "=", divide(number_1, number_2))
else:
print("Invalid input")
7.3 OUTPUT:
POS (PARTS OF SPEECH) TAGGING FOR THE GIVEN SENTENCE USING NLTK
8.1 OBJECTIVE: WAP to POS (Parts of Speech) tagging for the given sentence
using NLTK.
8.2 CODING:
#define a text
sentence = "The man was excited after he was informed about his promotion
at work"
8.3 OUTPUT:
[('The', 'DT'),
('man', 'NN'),
('was', 'VBD'),
('excited', 'VBN'),
('after', 'IN'),
('he', 'PRP'),
('was', 'VBD'),
('informed', 'VBN'),
('about', 'IN'),
('his', 'PRP$'),
('promotion', 'NN'),
('at', 'IN'),
('work', 'NN')]
Program No: 9
9.2 CODING:
def pose_estimation(input_image):
preprocessed_image = np.copy(input_image)
preprocessed_image = preprocessing(preprocessed_image, 256, 456)
return preprocessed_image
def text_detection(input_image):
preprocessed_image = np.copy(input_image)
preprocessed_image = preprocessing(preprocessed_image, 768, 1280)
return preprocessed_image
def car_meta(input_image):
preprocessed_image = np.copy(input_image)
preprocessed_image = preprocessing(preprocessed_image, 72, 72)
return preprocessed_image
def set_solution_functions():
global solution_funcs
solution_funcs = {
test_names[0]: pose_solution,
test_names[1]: text_solution,
test_names[2]: car_solution}
def pose_solution(input_image):
return preprocessing(input_image, 256, 456)
def text_solution(input_image):
return preprocessing(input_image, 768, 1280)
def car_solution(input_image):
return preprocessing(input_image, 72, 72)
def test_pose():
comparison = test(pose_estimation, test_names[0], POSE_IMAGE)
return comparison
def test_text():
comparison = test(text_detection, test_names[1], TEXT_IMAGE)
return comparison
def test_car():
comparison = test(car_meta, test_names[2], CAR_IMAGE)
return comparison
solution = solution_funcs[test_name](test_image)
comparison = np.array_equal(s_processed, solution)
print_test_result(test_name, comparison)
return comparison
def print_exception(test_name):
print("Failed to run test on {}.".format(test_name))
print("The code should be valid Python and return the preprocessed
image.")
def feedback(tests_passed):
print("You passed {} of 3 tests.".format(int(tests_passed)))
if tests_passed == 3:
print("Congratulations!")
else:
print("See above for additional feedback.")
9.3 OUTPUT:
10.2 CODING:
dataset = datasets.load_iris()
model.fit(dataset.data, dataset.target)
print(model)
# make predictions
expected = dataset.target
predicted = model.predict(dataset.data)
GaussianNB()
[[50 0 0]
[ 0 47 3]
[ 0 3 47]]