Practical Report On Advanced Artificial Intelligence & Machine Learning MASTERS OF SCIENCE (INFORMATION TECHNOLOGY) PART II – SEM III DEPARTMENT OF INFORMATION TECHNOLOGY COSMOPOLITAN'S VALIA C.L. COLLEGE OF COMMERCE & VALIA L.C. COLLEGE OFARTS (Autonomous) (Affiliated to University of Mumbai) D.N. NAGAR, ANDHERI (WEST), MUMBAI 400 053 2025 – 2026 VALIA C.L. COLLEGE OF COMMERCE & VALIA L.C. COLLEGE OF ARTS (Autonomous) (Affiliated to University of Mumbai) D.N. NAGAR, ANDHERI (WEST), MUMBAI 400 053 DEPARTMENT OF INFORMATION TECHNOLOGY CERTIFICATE Internal Guide Sign: Date: Name: Akbar Khan External Examiner Sign: Date: Name: Co - Ordinator Sign: Date: Name: Aarti Patkar College Seal: Index Sr. No. Practicals Date Page No. Sign. 1 Implementing advanced deep learning algorithms such as convolutional neural networks (CNNs) or recurrent neural networks (RNNs) using Python libraries like TensorFlow or PyTorch. 1 2 Building a natural language processing (NLP) model for sentiment analysis or text classification. 3 3 Creating a chatbot using advanced techniques like transformer models. 5 4 Developing a recommendation system using collaborative filtering or deep learning approaches. 7 5 Implementing a computer vision project, such as object detection or image segmentation. 10 6 Training a generative adversarial network (GAN) for generating realistic images. 12 7 Applying reinforcement learning algorithms to solve complex decision - making problems. 14 8 Utilizing transfer learning to improve model performance on limited datasets. 17 9 Building a deep learning model for time series forecasting or anomaly detection. 19 10 Implementing a machine learning pipeline for automated feature engineering and model selection. 24 MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 1 PRACTICAL NO: 1 Implementing advanced deep learning algorithms such as convolutional neural networks (CNNs) or recurrent neural networks (RNNs) using Python libraries like TensorFlow or PyTorch. Code: import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, Dataset import numpy as np class SequenceDataset(Dataset): def init (self, num_sequences=1000, sequence_length=10, num_classes=2): self.num_sequences = num_sequences self.sequence_length = sequence_length self.num_classes = num_classes self.data = np.random.randn(num_sequences, sequence_length, 1) self.labels = np.random.randint(0, num_classes, num_sequences) def len (self): return self.num_sequences def getitem (self, idx): sequence = self.data[idx] label = self.labels[idx] return torch.tensor(sequence, dtype=torch.float32), torch.tensor(label, dtype=torch.long) class LSTMClassifier(nn.Module): def init (self, input_size=1, hidden_size=64, num_layers=2, num_classes=2): super(LSTMClassifier, self). init () self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device) out, _ = self.lstm(x, (h0, c0)) out = out[:, - 1, :] out = self.fc(out) return out MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 2 input_size = 1 hidden_size = 64 num_layers = 2 num_classes = 2 num_epochs = 10 batch_size = 32 learning_rate = 0.001 dataset = SequenceDataset() train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = LSTMClassifier(input_size, hidden_size, num_layers, num_classes).to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) for epoch in range(num_epochs): for sequences, labels in train_loader: sequences, labels = sequences.to(device), labels.to(device) outputs = model(sequences) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') with torch.no_grad(): test_sequence = torch.randn(1, dataset.sequence_length, input_size).to(device) prediction = model(test_sequence) predicted_class = torch.argmax(prediction, dim=1).item() print(f'Predicted class: {predicted_class}') Output: MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 3 PRACTICAL NO: 2 Building a natural language processing (NLP) model for sentiment analysis or text classification. # Code # """ # Text Classification with IMDB Movie Reviews # """ # pip install tensorflow scikit - learn pandas joblib from tensorflow.keras.datasets import imdb from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.metrics import classification_report, accuracy_score import joblib # Convert integer sequences to text using Keras's word index def decode_review(sequence, word_index): reverse_word_index = {value: key for key, value in word_index.items()} # Words are offset by 3 in Keras IMDB (0,1,2 are reserved) return " ".join([reverse_word_index.get(i - 3, "?") for i in sequence if i >= 3]) if name == " main ": # Load IMDB dataset (num_words=10000 means only the top 10k words) (X_train_seq, y_train), (X_test_seq, y_test) = imdb.load_data(num_words=10000) word_index = imdb.get_word_index() # Convert integer sequences to text X_train = [decode_review(seq, word_index) for seq in X_train_seq] X_test = [decode_review(seq, word_index) for seq in X_test_seq] # Build and train pipeline pipeline = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), max_df=0.95, min_df=2), LogisticRegression(max_iter=1000) ) print("Training model...") pipeline.fit(X_train, y_train) print("Training complete.") # Evaluate y_pred = pipeline.predict(X_test) MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 4 print("Accuracy:", accuracy_score(y_test, y_pred)) print(classification_report(y_test, y_pred, target_names=["Negative", "Positive"])) # Save model joblib.dump(pipeline, "imdb_text_clf_model.joblib") print("Model saved to imdb_text_clf_model.joblib") # Test prediction example_review = "The movie was an absolute masterpiece with stunning visuals." pred = pipeline.predict([example_review])[0] print(f"Example review prediction: {'Positive' if pred == 1 else 'Negative'}") Output MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 5 PRACTICAL NO: 3 Creating a chatbot using advanced techniques like transformer models. Code import torch from transformers import AutoModelForCausalLM, AutoTokenizer # Load pre - trained DialoGPT model and tokenizer (medium version) model_name = "microsoft/DialoGPT - medium" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name) # Chat loop chat_history_ids = None step = 0 print("Chatbot: Hello! Type 'quit' to end the chat.") while True: user_input = input("You: ") if user_input.lower() == 'quit': print("Chatbot: Goodbye!") break # Encode user input and add to chat history new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt') # Append new user input to chat history bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim= - 1) if step > 0 else new_input_ids # Generate response chat_history_ids = model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, do_sample=True, top_k=50, top_p=0.95, temperature=0.75, ) # Decode and print the bot's response response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[ - 1]:][0], skip_special_tokens=True) MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 6 print(f"Chatbot: {response}") step += 1 Output MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 7 PRACTICAL NO: 4 Developing a recommendation system using collaborative filtering or deep learning approaches. Code import torch import torch.nn as nn import torch.optim as optim import random # # Original positive dataset: (user_id, item_id, rating) # Movies: 0 = Inception, 1 = Avatar, 2 = Titanic, 3 = Matrix, 4 = Interstellar # positive_data = [ (0, 0, 1), (0, 1, 1), (0, 3, 1), # User 0 likes Inception, Avatar, Matrix (1, 1, 1), (1, 2, 1), # User 1 likes Avatar, Titanic (2, 0, 1), (2, 2, 1), (2, 4, 1), # User 2 likes Inception, Titanic, Interstellar (3, 3, 1), (3, 4, 1) # User 3 likes Matrix, Interstellar ] num_users = 4 num_items = 5 embed_dim = 8 neg_per_pos = 2 # negatives per positive # # Generate negative samples # all_items = list(range(num_items)) positive_dict = {} for u, i, r in positive_data: positive_dict.setdefault(u, set()).add(i) data = positive_data.copy() for u, i, r in positive_data: neg_count = 0 while neg_count < neg_per_pos: neg_item = random.choice(all_items) if neg_item not in positive_dict[u]: data.append((u, neg_item, 0)) # mark as negative neg_count += 1 print(f"Training samples: {len(data)}") MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 8 # # Collaborative Deep Learning Model # class CFModel(nn.Module): def init (self, n_users, n_items, emb_dim): super(). init () self.user_emb = nn.Embedding(n_users, emb_dim) self.item_emb = nn.Embedding(n_items, emb_dim) self.fc = nn.Sequential( nn.Linear(emb_dim * 2, 16), nn.ReLU(), nn.Linear(16, 1), nn.Sigmoid() ) def forward(self, u, i): u_emb = self.user_emb(u) i_emb = self.item_emb(i) x = torch.cat([u_emb, i_emb], dim=1) return self.fc(x) # # Prepare data # users = torch.tensor([u for u, i, r in data]) items = torch.tensor([i for u, i, r in data]) ratings = torch.tensor([r for u, i, r in data], dtype=torch.float32) # # Train model # model = CFModel(num_users, num_items, embed_dim) criterion = nn.BCELoss() optimizer = optim.Adam(model.parameters(), lr=0.01) for epoch in range(50): optimizer.zero_grad() preds = model(users, items).squeeze() loss = criterion(preds, ratings) loss.backward() optimizer.step() # # Make predictions for a given user # user_id = 0 test_items = torch.arange(num_items) MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 9 scores = model(torch.tensor([user_id]*num_items), test_items).detach().numpy().flatten() movies = ["Inception", "Avatar", "Titanic", "Matrix", "Interstellar"] print(f" \ nRecommendations for user {user_id}:") for m, s in sorted(zip(movies, scores), key=lambda x: x[1], reverse=True): print(f"{m}: {float(s):.3f}") Output: MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 10 PRACTICAL NO: 5 Implementing a computer vision project, such as object detection or image segmentation. Code import torch, torchvision from PIL import Image, ImageDraw import matplotlib.pyplot as plt import torchvision.transforms as T import requests from io import BytesIO # 1. Download a sample image url = " https://images.unsplash.com/photo - 1516117172878 - fd2c41f4a759 " # sample image response = requests.get(url) img = Image.open(BytesIO(response.content)).convert("RGB") # 2. Load pretrained Faster R - CNN model model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) model.eval() # 3. Transform image to tensor transform = T.Compose([T.ToTensor()]) img_tensor = transform(img) # 4. Run object detection with torch.no_grad(): preds = model([img_tensor])[0] # 5. Draw bounding boxes draw = ImageDraw.Draw(img) for box, score, label in zip(preds['boxes'], preds['scores'], preds['labels']): if score > 0.5: # confidence threshold draw.rectangle(box.tolist(), outline="red", width=3) draw.text((box[0], box[1]), f"{label.item()}:{score:.2f}", fill="red") # 6. Show result plt.imshow(img) plt.axis("off") plt.show() MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 11 Output: MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 12 PRACTICAL NO: 6 Training a generative adversarial network (GAN) for generating realistic images. Code import torch, torch.nn as nn from torchvision import datasets, transforms, utils # Hyperparams z_dim, lr, epochs, batch = 64, 2e - 4, 20, 128 device = 'cuda' if torch.cuda.is_available() else 'cpu' # Data data = torch.utils.data.DataLoader( datasets.MNIST('.', train=True, download=True, transform=transforms.ToTensor()), batch_size=batch, shuffle=True) # Models G = nn.Sequential( nn.Linear(z_dim, 128), nn.ReLU(), nn.Linear(128, 784), nn.Tanh()).to(device) D = nn.Sequential( nn.Linear(784, 128), nn.LeakyReLU(0.2), nn.Linear(128, 1), nn.Sigmoid()).to(device) # Loss & opt loss = nn.BCELoss() opt_G = torch.optim.Adam(G.parameters(), lr=lr) opt_D = torch.optim.Adam(D.parameters(), lr=lr) # Training for epoch in range(epochs): for x, _ in data: x = x.view( - 1, 784).to(device) b = x.size(0) # Train D z = torch.randn(b, z_dim, device=device) fake = G(z) loss_D = loss(D(x), torch.ones(b, 1, device=device)) + \ loss(D(fake.detach()), torch.zeros(b, 1, device=device)) opt_D.zero_grad(); loss_D.backward(); opt_D.step() MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 13 # Train G loss_G = loss(D(fake), torch.ones(b, 1, device=device)) opt_G.zero_grad(); loss_G.backward(); opt_G.step() print(f"Epoch {epoch+1}/{epochs} | D: {loss_D.item():.3f} | G: {loss_G.item():.3f}") utils.save_image(fake.view(b, 1, 28, 28), f"sample_{epoch+1}.png", normalize=True) Output MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 14 PRACTICAL NO: 7 Applying reinforcement learning algorithms to solve complex decision - making problems. Code # ---- Compatibility Fix ---- import numpy as np if not hasattr(np, 'bool8'): np.bool8 = np.bool_ # Patch for older Gym expecting np.bool8 import gym # Create the environment env = gym.make("FrozenLake - v1", is_slippery=False) # Initialize Q - table with zeros state_size = env.observation_space.n action_size = env.action_space.n Q = np.zeros((state_size, action_size)) # Hyperparameters alpha = 0.1 # Learning rate gamma = 0.99 # Discount factor epsilon = 1.0 # Exploration rate epsilon_decay = 0.99 epsilon_min = 0.01 episodes = 2000 max_steps = 100 # Training loop for episode in range(episodes): # Handle both Gym API styles reset_output = env.reset() state = reset_output[0] if isinstance(reset_output, tuple) else reset_output done = False for step in range(max_steps): # Epsilon - greedy action selection if np.random.rand() < epsilon: action = env.action_space.sample() else: action = np.argmax(Q[state, :]) # Step the environment (handle both Gym API formats) step_output = env.step(action) MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 15 if len(step_output) == 5: next_state, reward, terminated, truncated, _ = step_output done = terminated or truncated else: next_state, reward, done, _ = step_output # Q - learning update Q[state, action] += alpha * (reward + gamma * np.max(Q[next_state, :]) - Q[state, action]) state = next_state if done: break # Decay exploration rate epsilon = max(epsilon_min, epsilon * epsilon_decay) print("Training finished! \ n") print("Learned Q - table:") print(Q) # ---- Testing the agent ---- reset_output = env.reset() state = reset_output[0] if isinstance(reset_output, tuple) else reset_output done = False env.render() while not done: action = np.argmax(Q[state, :]) step_output = env.step(action) if len(step_output) == 5: state, reward, terminated, truncated, _ = step_output done = terminated or truncated else: state, reward, done, _ = step_output env.render() env.close() MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 16 Output MSC IT PART 2 SEM III ADVANCE ARTIFICIAL INTELLIGENCE 17 PRACTICAL NO: 8 Utilizing transfer learning to improve model performance on limited datasets. Code #RUN THIS FIRST → Creates sample dataset import os import numpy as np from PIL import Image # Create directories folders = [ "dataset/train/cats", "dataset/train/dogs", "dataset/val/cats", "dataset/val/dogs" ] for f in folders: os.makedirs(f, exist_ok=True) # helper function def make_image(path, color): img = Image.new("RGB", (224, 224), color) img.save(path) # Generate 5 sample images per class for i in range(5): make_image(f"dataset/train/cats/cat_{i}.jpg", (255, 180, 180)) make_image(f"dataset/train/dogs/dog_{i}.jpg", (180, 180, 255)) make_image(f"dataset/val/cats/cat_{i}.jpg", (255, 200, 200)) make_image(f"dataset/val/dogs/dog_{i}.jpg", (200, 200, 255)) print("Sample images created!") # NOW Load the dataset + Train (Short Transfer Learning Code) from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import MobileNetV2 from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, GlobalAveragePooling2D # Load data gen = ImageDataGenerator(rescale=1/255) train = gen.flow_from_directory("dataset/train", target_size=(224,224), batch_size=4, class_mode="categorical")