AI Lab - Manual - 136
AI Lab - Manual - 136
return results
query = "computer
science"
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'])
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:
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:
Output:
(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:
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: