0% found this document useful (0 votes)
21 views17 pages

AI Lab - Manual - 136

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

AI Lab - Manual - 136

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

Mayank Dobariya – 22ss2it136

SSCS3512 - Artificial Intelligence

BSC IT- Sem 5B


1. Develop a simple search algorithm to assist users in finding relevant
information within a large dataset, such as a library catalogue or a database
of products.
import re dataset
= [
{"title": "Introduction to Computer Science", "description":
"A beginner's guide to computer science."},
{"title": "Advanced Algorithms", "description": "In-depth
coverage of algorithms."},
{"title": "Data Science with Python", "description": "Learn
data analysis and machine learning."}
] def
preprocess(text):
words = re.findall(r'\w+', text.lower())
return words
def search(query,
dataset):
query_words = preprocess(query)
results = []
for item in
dataset:
title_words = preprocess(item["title"])
desc_words = preprocess(item["description"])
title_matches = set(query_words) &
set(title_words) desc_matches = set(query_words) &
set(desc_words)
if title_matches or
desc_matches:
results.append(item)

return results
query = "computer
science"

results = search(query, dataset)


for result in results: print(f"Title:
{result['title']}, Description:
{result['description']}")
Output:

2. Build a predictive model to estimate the price of a house based on its features
(e.g., size, number of bedrooms, location) using historical housing data using
python library.
import numpy as np import pandas as pd from
sklearn.model_selection import train_test_split from
sklearn.linear_model import LinearRegression from
sklearn.preprocessing import LabelEncoder
data =
{
"size": [1500, 1800, 2400, 3000, 3500],
"bedrooms": [3, 4, 3, 5, 4],
"location": ["city", "city", "suburb", "suburb", "city"],
"price": [400000, 500000, 600000, 700000, 650000]
} df =
pd.DataFrame(data)
le = LabelEncoder() df['location'] =
le.fit_transform(df['location'])

X = df[['size', 'bedrooms', 'location']] y


= df['price']

X_train, X_test, y_train, y_test = train_test_split(X, y,


test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred =
model.predict(X_test)
print("Predicted prices:",
y_pred)
print("Actual prices:",
y_test.values)

Output:
3. Analyse customer reviews from an e-commerce website to determine overall
sentiment and identify common themes or issues raised by customers.
import pandas as pd from textblob import TextBlob from
sklearn.feature_extraction.text import CountVectorizer
import matplotlib.pyplot as plt from wordcloud import
WordCloud
data =
{
"reviews": [
"Great product, I really love it!",
"Terrible experience, the product broke after a week.",
"Amazing quality, fast delivery.",
"Not worth the price, very disappointing.",
"Good value for the money, satisfied with my purchase."
]
} df =
pd.DataFrame(data)
def
get_sentiment(review):
analysis = TextBlob(review) return 'positive' if
analysis.sentiment.polarity > 0 else
'negative'
df['sentiment'] =
df['reviews'].apply(get_sentiment)
print(df[['reviews',
'sentiment']])

vectorizer = CountVectorizer(stop_words='english') X
= vectorizer.fit_transform(df['reviews'])
common_words = vectorizer.get_feature_names_out()
word_counts = pd.DataFrame(X.toarray(),
columns=common_words).sum().sort_values(ascending=False)
print("\nCommon words:\n",word_counts) wordcloud =
WordCloud(width=800, height=400,
background_color='white').generate(' '.join(df['reviews']))
Output:

4. Create a neural network model to classify images of handwritten digits (e.g.,


MNIST dataset) for use in automated digit recognition systems using latest
python library.
import tensorflow as tf from
tensorflow.keras import layers, models from
tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt

(X_train, y_train), (X_test, y_test) = mnist.load_data()


X_train = X_train.astype('float32') / 255.0
X_test = X_test.astype('float32') / 255.0

X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)


X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)

y_train = tf.keras.utils.to_categorical(y_train, 10) y_test


= tf.keras.utils.to_categorical(y_test, 10)
model =
models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28,
28, 1)), layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(), layers.Dense(64,
activation='relu'), layers.Dense(10,
activation='softmax')
]) model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=5,
batch_size=32, validation_split=0.2)
test_loss, test_acc = model.evaluate(X_test,
y_test) print(f'Test accuracy: {test_acc}')
predictions =
model.predict(X_test)
for i in
range(2):
plt.imshow(X_test[i].reshape(28, 28), cmap='gray')
plt.title(f'Predicted: {predictions[i].argmax()}, Actual:
{y_test[i].argmax()}')
plt.axis('off')
plt.show()

Output:
5. Develop a system to automatically detect and classify different types of fruits
in images, which could be used in quality control processes for food
production.
import tensorflow as tf from tensorflow.keras import layers,
models from tensorflow.keras.preprocessing.image import
ImageDataGenerator
train_dir = 'path/to/train'
test_dir = 'path/to/test'
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir, target_size=(100, 100),
class_mode='categorical'
) test_generator = test_datagen.flow_from_directory(
test_dir, target_size=(100, 100), batch_size=32,
class_mode='categorical'
) model = models.Sequential([ layers.Conv2D(32, (3, 3),
activation='relu', input_shape=(100, 100, 3)),
layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3),
activation='relu'), layers.MaxPooling2D((2, 2)),
layers.Conv2D(128, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)), layers.Flatten(),
layers.Dense(128, activation='relu'), layers.Dense(64,
activation='relu'), layers.Dense(3,
activation='softmax')
]) model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit( train_generator,
epochs=10,
validation_data=test_generator
) test_loss, test_acc =
model.evaluate(test_generator) print(f'Test
accuracy: {test_acc}')
new_images_dir = 'path/to/new_fruit_images'
new_image_generator = test_datagen.flow_from_directory(
new_images_dir, target_size=(100, 100),
batch_size=1, class_mode=None, shuffle=False
) predictions =
model.predict(new_image_generator)
for i, pred in enumerate(predictions): predicted_class =
pred.argmax() print(f"Image {i + 1}: Predicted class
{predicted_class}")

Output:

6. Design a chatbot for a customer support service that can answer frequently
asked questions, provide product information, and assist with common
inquiries.
import random
faq_responses =
{
"hello": "Hello! How can I assist you today?",
"hi": "Hi! How can I help you?",
"how are you": "I'm a bot, but I'm here to assist you!",
"what is your name": "I'm your friendly customer support
assistant!",
"what products do you offer": "We offer a variety of products
including electronics, clothing, and accessories.",
"how can I track my order": "You can track your order by
logging into your account and clicking on 'Track Order'.",
"what is the return policy": "Our return policy allows returns
within 30 days of purchase with a receipt.",
"how can I contact support": "You can contact support by
emailing [email protected] or calling 1-800-123-4567.",
"thank you": "You're welcome! Let me know if you need any more
help.",
"bye": "Goodbye! Have a great day!"
} def
get_response(user_input):
user_input = user_input.lower()
if user_input in
faq_responses:
return faq_responses[user_input]

else:
return "I'm sorry, I didn't understand that. Can you
please rephrase or ask something else?"
def
chatbot():
print("Customer Support Bot: Hi! I'm here to help you with
any questions you may have. Type 'bye' to end the chat.")
while
True:
user_input = input("You: ")
if user_input.lower() ==
"bye":
print("Customer Support Bot: Goodbye! Have a great
day!") break
response =
get_response(user_input) print(f"Customer
Support Bot: {response}")
if __name__ ==
"__main__":
chatbot()
Output:

7. Train an autonomous agent to navigate through a maze or obstacle course in


a simulated environment, such as a robot exploring an unknown terrain.
import numpy as np import
random
class MazeEnv: def __init__(self):
self.size = 5 self.state = (0, 0)
self.goal = (4, 4) self.actions = ['up',
'down', 'left', 'right'] self.grid =
np.zeros((self.size, self.size))
self.grid[self.goal] = 1
def
reset(self):
self.state = (0, 0)
return self.state
def step(self, action):
x, y = self.state if action
== 'up' and x > 0:
x -= 1 elif action == 'down' and
x < self.size - 1:
x += 1 elif action == 'left' and y
> 0:
y -= 1 elif action == 'right' and y
< self.size - 1:
y += 1
self.state = (x,
y)
if self.state ==
self.goal:
return self.state, 1, True
else:
return self.state, -0.1, False
class QLearningAgent:
def __init__(self, env, learning_rate=0.1,
discount_factor=0.95, epsilon=0.1):
self.env = env self.q_table =
np.zeros((env.size, env.size, len(env.actions)))
self.lr = learning_rate self.gamma =
discount_factor self.epsilon = epsilon
def choose_action(self,
state):
if random.uniform(0, 1) <
self.epsilon:
return random.choice(self.env.actions)
else:
x, y = state return
self.env.actions[np.argmax(self.q_table[x, y])] def
update_q_table(self, state, action, reward, next_state):
x, y = state next_x, next_y = next_state
action_idx = self.env.actions.index(action)
self.q_table[x, y, action_idx] += self.lr * (
reward + self.gamma * np.max(self.q_table[next_x, next_y]) -
self.q_table[x, y, action_idx]
)
def train_agent(env, agent,
episodes=1000):
for episode in range(episodes):
state = env.reset()
done = False while
not done:
action = agent.choose_action(state)
next_state, reward, done = env.step(action)
agent.update_q_table(state, action, reward, next_state)
state = next_state if (episode + 1) % 100 == 0:
print(f"Episode {episode + 1}/{episodes} completed.")
def test_agent(env,
agent):
state = env.reset()
done = False steps = 0
print("Agent's path:")
while not done:
action = agent.choose_action(state)
state, _, done = env.step(action)
steps += 1 print(state, end=" -> ")
print(f"\nGoal reached in {steps} steps!")
env = MazeEnv() agent =
QLearningAgent(env)
train_agent(env, agent,
episodes=1000)
test_agent(env,
agent)

Output:

8. Develop a system to detect and count the number of vehicles in a traffic


surveillance camera feed, which could be used for traffic flow analysis and
congestion management.
import cv2 import
numpy as np
model_path =
'path_to_model/MobileNetSSD_deploy.caffemodel'
prototxt_path =
'path_to_model/MobileNetSSD_deploy.prototxt'
net = cv2.dnn.readNetFromCaffe(prototxt_path,
model_path)
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow",
"diningtable",
"dog", "horse", "motorbike", "person", "pottedplant",
"sheep",
"sofa", "train", "tvmonitor"]

VEHICLE_CLASSES = ["bus", "car", "motorbike"]


cap = cv2.VideoCapture('path_to_video/traffic_video.mp4')
while
cap.isOpened():
ret, frame = cap.read()
if not ret: break

(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300,
300)),
0.007843, (300, 300), 127.5)
net.setInput(blob)
detections =
net.forward()
vehicle_count =
0
for i in
range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.4: idx =
int(detections[0, 0, i, 1])
label = CLASSES[idx]
if label in
VEHICLE_CLASSES:
box = detections[0, 0, i, 3:7] * np.array([w, h,
w, h])
(startX, startY, endX, endY) = box.astype("int")
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0),
2)
label_text = f"{label}: {int(confidence *
100)}%" cv2.putText(frame, label_text, (startX,
startY -
10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0,
255, 0), 2)
vehicle_count +=
1
cv2.putText(frame, f"Vehicles: {vehicle_count}", (10,
30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255),
2)
cv2.imshow("Vehicle Detection",
frame)
if cv2.waitKey(1) & 0xFF ==
ord('q'):
break
cap.release() cv2.destroyAllWindows()
Output:

9. Analyse public sentiment on social media platforms (e.g., Twitter) regarding a


specific topic or event, such as a new product launch or a political campaign.
import tweepy from textblob
import TextBlob import
matplotlib.pyplot as plt
consumer_key = 'YOUR_CONSUMER_KEY'
consumer_secret = 'YOUR_CONSUMER_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
access_token_secret =
'YOUR_ACCESS_TOKEN_SECRET'
auth = tweepy.OAuth1UserHandler(consumer_key,
consumer_secret, access_token, access_token_secret) api =
tweepy.API(auth)
def get_tweets(topic,
count=100):
tweets = api.search_tweets(q=topic, count=count, lang='en',
tweet_mode='extended') return tweets
def
analyze_sentiment(tweets):
positive, negative, neutral = 0, 0, 0
for tweet in
tweets:
analysis = TextBlob(tweet.full_text)
if analysis.sentiment.polarity > 0:
positive += 1 elif
analysis.sentiment.polarity < 0:
negative += 1
else:
neutral += 1
return positive, negative,
neutral
def plot_results(positive, negative, neutral):
labels = ['Positive', 'Negative', 'Neutral']
sizes = [positive, negative, neutral] colors
= ['#4CAF50', '#F44336', '#FFC107']
plt.figure(figsize=(8, 5))
plt.bar(labels, sizes, color=colors)
plt.title('Sentiment Analysis of Tweets')
plt.xlabel('Sentiment')
plt.ylabel('Number of Tweets')
plt.ylim(0, max(sizes) + 10) plt.show()
def
main():
topic = input("Enter the topic you want to analyze: ")
tweets = get_tweets(topic, count=100) positive,
negative, neutral = analyze_sentiment(tweets)
print(f"Positive tweets: {positive}") print(f"Negative
tweets: {negative}") print(f"Neutral tweets:
{neutral}") plot_results(positive, negative, neutral)
if __name__ ==
"__main__":
main()

Output:

10. Deploy a trained image classification model as a web service to allow users
to upload images and receive predictions on the content of those images,
such as identifying objects or animals.
from PIL import Image import numpy as np from
tensorflow.keras.applications import MobileNetV2,
preprocess_input, decode_predictions
model =
MobileNetV2(weights='imagenet')
def
predict_image(image_path):
image = Image.open(image_path)
image = image.resize((224, 224))
image_array = np.array(image) image_array =
np.expand_dims(image_array, axis=0)
image_array = preprocess_input(image_array)
preds = model.predict(image_array)
return decode_predictions(preds, top=3)[0]
if __name__ ==
"__main__":
image_path = input("Enter the path to the image file: ")
predictions = predict_image(image_path)
print("Predictions:")
for pred in predictions:
print(f"Label: {pred[1]}, Probability: {pred[2]:.4f}")

Output:

You might also like