Ai 3
Ai 3
OUTPUT
1--->2--->4--->3--->1
Minimum cost is 80
class Rule:
def __init__(self, premises, conclusion):
self.premises = premises
self.conclusion = conclusion
# Knowledge base
rules = [
Rule(["A"], "B"),
Rule(["B", "C"], "D"),
Rule(["D"], "E"),
Rule(["F"], "C"),
Rule(["A"],"z")
]
def forward_chaining(knowledge_base, query):
inferred = set()
agenda = [query]
while agenda:
fact = agenda.pop(0)
if fact not in inferred:
inferred.add(fact)
matching_rules = [rule for rule in knowledge_base if all(premise
in inferred for premise in rule.premises)]
for rule in matching_rules:
agenda.append(rule.conclusion)
return inferred
# Test forward chaining
print("Forward Chaining:")
print("Inferred facts:", forward_chaining(rules, "A"))
OUTPUT:
Forward Chaining:
class Rule:
def __init__(self, premises, conclusion):
self.premises = premises
self.conclusion = conclusion
# Knowledge base
rules = [
Rule(["A"], "B"),
Rule(["B", "C"], "D"),
Rule(["D"], "E"),
Rule(["F"], "C") ]
def ask(fact):
# If fact is already inferred, return True
if fact in inferred:
return True
return False
OUTPUT 1:
Backward Chaining:
OUTPUT-2:
Backward Chaining:
def find_s_algorithm(examples):
hypothesis = None
for features, label in examples:
if label == 1:
if hypothesis is None:
hypothesis = features.copy()
else:
for i in range(len(hypothesis)):
if hypothesis[i] != features[i]:
hypothesis[i] = '?'
return hypothesis
# Example usage
examples = [
(['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same'], 1),
(['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same'], 1),
(['Rainy', 'Cold', 'High', 'Strong', 'Warm', 'Change'], 0),
(['Sunny', 'Warm', 'High', 'Strong', 'Cool', 'Change'], 1)
]
hypothesis = find_s_algorithm(examples)
print("Most specific hypothesis:", hypothesis)
OUTPUT: Most specific hypothesis: ['Sunny', 'Warm', '?', 'Strong', '?', '?']
8. Write a program to implement Template matching
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('doraemon.jpg', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with
os.path.exists()"
img2 = img.copy()
template = cv.imread('D1.jpg', cv.IMREAD_GRAYSCALE)
assert template is not None, "file could not be read, check with
os.path.exists()"
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED']
#['cv.TM_CCORR', 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF',
#'cv.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
res = cv.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv.rectangle(img,top_left, bottom_right, 255, 2)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
OUTPUT:
import numpy as np
import cv2 as cv
img = cv.imread('c.png', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
img = cv.medianBlur(img, 5)
cimg = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
OUTPUT:
10. Write a program to implement Multiple Linear Regression Model using python
import numpy as np
import matplotlib as mpl
#from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def generate_dataset(n):
x = []
y = []
random_x1 = np.random.rand()
random_x2 = np.random.rand()
for i in range(n):
x1 = i
x2 = i / 2 + np.random.rand() * n
x.append([1, x1, x2])
y.append(random_x1 * x1 + random_x2 * x2 + 1)
return np.array(x), np.array(y)
x, y = generate_dataset(50)
mpl.rcParams['legend.fontsize'] = 12
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter(x[:, 1], x[:, 2], y, label='Y', s=5,edgecolors='red')
ax.legend( )
ax.view_init(45, 0)
plt.show()
OUTPUT: