def print_ml_programs(indx):
    ml2_progs=[
r"""
#Program1a:
import csv  
a=[]  
with open('enjoysport.csv', 'r') as csvfile:  
    for row in csv.reader(csvfile): 
        a.append(row)  
print("\n The total number of training instances are: " ,len(a)-1)  
num_attribute =len(a[0])-1  
print("\n The initial hypothesis is: ")  
hypothesis =['0']*num_attribute  
print(hypothesis)  
for i in range(1,len(a)):  
    if a[i][num_attribute] == 'yes':  
        for j in range(0, num_attribute):  
            if hypothesis[j] =='0' or hypothesis[j] == a[i][j]:  
                hypothesis[j] =a[i][j]  
            else:  
                hypothesis[j] = '?'  
print("\n The hypothesis for the training instance {} is :\n".format(i),hypothesis)  
print("\n The Maximally specific hypothesis for the training instance is ") 
print(hypothesis)

#Program1b: 

import numpy as np  
import pandas as pd  
data = pd.DataFrame(data=pd.read_csv('enjoysport.csv'))  
concepts = np.array(data.iloc[:,0:-1])  
print(concepts)
target = np.array(data.iloc[:,-1])  
print(target)  
def learn(concepts, target):  
    specific_h = concepts[0].copy()  
    print("initialization of specific_h and general_h")  
    print(specific_h)  
    general_h = [["?" for i in range(len(specific_h))] for i in range(len(specific_h))]  
    print(general_h)  
    for i, h in enumerate(concepts):  
        if target[i] == "yes":  
            for x in range(len(specific_h)):  
                if h[x]!= specific_h[x]:  
                    specific_h[x]='?'  
                    general_h[x][x]='?' 
        if target[i] == "no":  
            for x in range(len(specific_h)):  
                if h[x]!= specific_h[x]:  
                    general_h[x][x]= specific_h[x]  
                else:  
                    general_h[x][x]='?'  
        print(" steps of Candidate Elimination Algorithm",i+1)  
        print(specific_h)  
        print(general_h)  
    indices =[i for i, val in enumerate(general_h) if val ==['?', '?', '?', '?', '?', '?']]  
    for i in indices:  
        general_h.remove (['?','?','?','?','?','?'])  
    return specific_h, general_h  
s_final, g_final = learn(concepts, target)  
print("Final Specific_h:", s_final, sep="\n")  
print("Final General_h:", g_final, sep="\n")""",
r"""
#Program 2:
import pandas as pd
import math

data = {
    "S.No": [1, 2, 3, 4, 5],
    "CGPA": [">=9", "<8", ">=9", "<8", ">=8"],
    "Interactiveness": ["Yes", "Yes", "Yes", "No", "Yes"],
    "Practical Knowledge": ["Good", "Good", "Average", "Good", "Good"],
    "Job Offer": ["Yes", "Yes", "No", "No", "No"]
}
df = pd.DataFrame(data)

def foil_gain(pos, neg, new_pos, new_neg):
    if new_pos == 0:
        return 0
    gain = new_pos * (math.log2(new_pos / (new_pos + new_neg)) - math.log2(pos / (pos + neg)))
    return gain

total_pos = len(df[df["Job Offer"] == "Yes"])
total_neg = len(df[df["Job Offer"] == "No"])

attributes = ["CGPA", "Interactiveness", "Practical Knowledge"]
values = {
    "CGPA": df["CGPA"].unique(),
    "Interactiveness": df["Interactiveness"].unique(),
    "Practical Knowledge": df["Practical Knowledge"].unique()
}
gains = []
for attr in attributes:
    for val in values[attr]:
        subset = df[df[attr] == val]
        new_pos = len(subset[subset["Job Offer"] == "Yes"])
        new_neg = len(subset[subset["Job Offer"] == "No"])
        gain = foil_gain(total_pos, total_neg, new_pos, new_neg)
        gains.append((f'{attr}={val}', gain, new_pos, new_neg))

gains.sort(key=lambda x: x[1], reverse=True)

print("FOIL Gain and Rule Candidates:\n")
for rule, gain, pos, neg in gains:
    print(f"Rule: IF {rule} THEN Job Offer = Yes | FOIL Gain = {gain:.4f} | Positives = {pos} | Negatives = {neg}")""",
r"""
#program3:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score, classification_report

data = load_breast_cancer()
X = data.data
y = data.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
bag_model = BaggingClassifier(
    estimator=DecisionTreeClassifier(),
    n_estimators=50,
    random_state=42
)
bag_model.fit(X_train, y_train)
y_pred_bag = bag_model.predict(X_test)

print("Bagging Accuracy:", accuracy_score(y_test, y_pred_bag))
print("\n Classification Report:\n", classification_report(y_test, y_pred_bag))
print("\n Bagging Accuracy:", accuracy_score(y_test, y_pred_bag))
print("\nClassification Report:\n", classification_report(y_test, y_pred_bag))

from sklearn.ensemble import AdaBoostClassifier
boost_model = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=50,
    random_state=42
)
boost_model.fit(X_train, y_train)
y_pred_boost = boost_model.predict(X_test)

print(" Boosting Accuracy:", accuracy_score(y_test, y_pred_boost))
print("\n Classification Report:\n", classification_report(y_test, y_pred_boost))""",
r"""
#Program4:
from sklearn.datasets import load_breast_cancer
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

data = load_breast_cancer()
X = data.data

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

k = 2
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
clusters = kmeans.fit_predict(X_scaled)

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
principal_components = pca.fit_transform(X_scaled)

plt.figure(figsize=(10, 7))
for cluster_id in sorted(set(clusters)):
    plt.scatter(principal_components[clusters == cluster_id, 0],
                principal_components[clusters == cluster_id, 1],
                label=f'Cluster {cluster_id}', alpha=0.7)
plt.title(f'K-Means Clusters (K={k}) - PCA Reduced Data')
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend()
plt.grid(True)
plt.show()""",
r"""
# PROGRAM 5

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from minisom import MiniSom
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names

data = pd.DataFrame(X, columns=iris.feature_names)
data['Species'] = [target_names[i] for i in y]

print("Dataset Head:")
print(data.head())

scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

som_x, som_y = 7, 7

som = MiniSom(
    x=som_x,
    y=som_y,
    input_len=X_scaled.shape[1],
    sigma=1.0,
    learning_rate=0.5
)

som.random_weights_init(X_scaled)

print("Training SOM...")
som.train_random(data=X_scaled, num_iteration=100)
print("Training Complete!")

plt.figure(figsize=(8, 8))
plt.pcolor(som.distance_map().T, cmap='coolwarm')
plt.colorbar(label='Distance')

markers = ['o', 's', 'D']
colors = ['r', 'g', 'b']

for i, x in enumerate(X_scaled):
    w = som.winner(x)
    plt.plot(
        w[0] + 0.5,
        w[1] + 0.5,
        markers[y[i]],
        markerfacecolor='None',
        markeredgecolor=colors[y[i]],
        markersize=12,
        markeredgewidth=2
    )

plt.title("Self-Organizing Map (SOM) - Iris Dataset")
plt.show()

clusters = [som.winner(x) for x in X_scaled]
data['Cluster'] = clusters

print("\nClustered Data:")
print(data.head())

data.to_csv("iris_som_clustered.csv", index=False)
print("Clustered data saved to 'iris_som_clustered.csv'")
""",
r"""
#PROGRAM 6

import numpy as np
import matplotlib.pyplot as plt

def uniform_random(n):
    return np.random.rand(n)

def f(x):
    return np.exp(x)

n = 10
x_samples = uniform_random(n)
f_samples = f(x_samples)

I_estimated = np.mean(f_samples)
I_true = np.e - 1

x = np.linspace(0, 1, 100)
y = f(x)

plt.figure(figsize=(8, 5))
plt.plot(x, y, 'b-', label='f(x) = e^x')
plt.fill_between(x, y, color='lightblue', alpha=0.3,
                 label='True area (integral e^x dx)')
plt.scatter(x_samples, f_samples, color='red', zorder=5, label='Random samples')
plt.hlines(np.mean(f_samples), 0, 1, colors='green', linestyles='--',
           label='Mean(f(x))')

plt.title('Monte Carlo Estimation of integral 0 to 1 e^x dx')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()

print("Monte Carlo estimated integral =", I_estimated)
print("True integral value =", I_true)
print("Absolute error =", abs(I_estimated - I_true))
""",
r"""
# PROGRAM 7

import pandas as pd
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

data = pd.DataFrame({
    'Weather': ['Sunny', 'Sunny', 'Overcast', 'Rain', 'Rain', 'Rain', 'Overcast', 'Sunny', 'Sunny',
                'Rain', 'Sunny', 'Overcast', 'Overcast', 'Rain'],
    'Temperature': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool', 'Mild', 'Cool', 'Mild',
                    'Mild', 'Mild', 'Hot', 'Mild'],
    'Humidity': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal',
                 'Normal', 'Normal', 'High', 'Normal', 'High'],
    'Wind': ['Weak', 'Strong', 'Weak', 'Weak', 'Weak', 'Strong', 'Strong', 'Weak', 'Weak', 'Weak',
             'Strong', 'Strong', 'Weak', 'Strong'],
    'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes',
             'Yes', 'Yes', 'Yes', 'Yes', 'No']
})

model = DiscreteBayesianNetwork([
    ('Weather', 'Play'),
    ('Temperature', 'Play'),
    ('Humidity', 'Play'),
    ('Wind', 'Play')
])

model.fit(data, estimator=MaximumLikelihoodEstimator)

inference = VariableElimination(model)

result = inference.query(variables=['Play'], evidence={'Weather': 'Sunny'})
print("Likelihood of Play when Weather is Sunny:\n", result)

query_result = inference.query(
    variables=['Play'],
    evidence={'Weather': 'Rain', 'Humidity': 'High'}
)
print("\n=== Likelihood of Event ===")
print("If Weather = Rain and Humidity = High:\n", query_result)
""",
r"""
# PROGRAM 8

import pandas as pd
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

data = pd.DataFrame({
    'Weather': ['Sunny', 'Sunny', 'Overcast', 'Rain', 'Rain', 'Rain', 'Overcast', 'Sunny', 'Sunny',
                'Rain', 'Sunny', 'Overcast', 'Overcast', 'Rain'],
    'Temperature': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool', 'Mild', 'Cool',
                    'Mild', 'Mild', 'Mild', 'Hot', 'Mild'],
    'Humidity': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal', 'High', 'Normal',
                 'Normal', 'Normal', 'High', 'Normal', 'High'],
    'Wind': ['Weak', 'Strong', 'Weak', 'Weak', 'Weak', 'Strong', 'Strong', 'Weak', 'Weak',
             'Weak', 'Strong', 'Strong', 'Weak', 'Strong'],
    'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes',
             'Yes', 'Yes', 'Yes', 'Yes', 'No']
})

model = DiscreteBayesianNetwork([
    ('Weather', 'Play'),
    ('Temperature', 'Play'),
    ('Humidity', 'Play'),
    ('Wind', 'Play')
])

model.fit(data, estimator=MaximumLikelihoodEstimator)
inference = VariableElimination(model)

queries = [
    {'Weather': 'Sunny', 'Humidity': 'High'},
    {'Weather': 'Rain', 'Wind': 'Weak'},
    {'Weather': 'Overcast'}
]

print("\n--- Inferences Based on Given Conditions ---")
for evidence in queries:
    prob = inference.query(variables=['Play'], evidence=evidence)
    print(f"\nEvidence: {evidence}")
    print(prob)
"""
    ]
    print(ml2_progs[indx-1])

def print_dl_programs(indx):
    dl_progs=[
r"""
#Program 1

import torch
import torch.nn as nn
import torch.optim as optim
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE

corpus = [
    "the cat sits on the mat",
    "dogs and cats are animals",
    "the mat is soft and comfortable"
]

window_size = 2
embedding_dim = 50
epochs = 100
learning_rate = 0.01

tokenized_corpus = [sentence.lower().split() for sentence in corpus]
vocab = set(word for sentence in tokenized_corpus for word in sentence)
word2idx = {word: idx for idx, word in enumerate(vocab)}
idx2word = {idx: word for word, idx in word2idx.items()}
vocab_size = len(vocab)


def generate_skip_gram(tokenized_text, window):
    pairs = []
    for sentence in tokenized_text:
        for center_pos in range(len(sentence)):
            center_word = sentence[center_pos]
            context_range = list(
                range(
                    max(0, center_pos - window),
                    min(len(sentence), center_pos + window + 1)
                )
            )
            context_range.remove(center_pos)
            for context_pos in context_range:
                pairs.append(
                    (word2idx[center_word], word2idx[sentence[context_pos]])
                )
    return pairs


training_pairs = generate_skip_gram(tokenized_corpus, window_size)


class SkipGramModel(nn.Module):
    def __init__(self, vocab_size, embedding_dim):
        super(SkipGramModel, self).__init__()
        self.embeddings = nn.Embedding(vocab_size, embedding_dim)
        self.output_layer = nn.Linear(embedding_dim, vocab_size)

    def forward(self, input_word):
        embedding = self.embeddings(input_word)
        out = self.output_layer(embedding)
        return out


model = SkipGramModel(vocab_size, embedding_dim)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

print("Training started...")
for epoch in range(epochs):
    total_loss = 0
    for center, context in training_pairs:
        center_tensor = torch.tensor([center], dtype=torch.long)
        context_tensor = torch.tensor([context], dtype=torch.long)

        optimizer.zero_grad()
        output = model(center_tensor)
        loss = criterion(output, context_tensor)
        loss.backward()
        optimizer.step()

        total_loss += loss.item()

    if (epoch + 1) % 10 == 0:
        print(f"Epoch {epoch+1}/{epochs}, Loss: {total_loss:.4f}")
print("Training complete.")

embeddings = model.embeddings.weight.data
with open("word_embeddings.txt", "w") as f:
    for idx, vector in enumerate(embeddings):
        word = idx2word[idx]
        vec_str = " ".join(map(str, vector.tolist()))
        f.write(f"{word} {vec_str}\n")
print("Saved word embeddings to 'word_embeddings.txt'.")


def visualize_embeddings(embeddings, word2idx, words=None):
    if words is None:
        words = list(word2idx.keys())

    vecs = torch.stack([embeddings[word2idx[word]] for word in words]).numpy()

    perplexity = min(30, len(words) - 1)
    tsne = TSNE(
        n_components=2,
        init="pca",
        random_state=0,
        perplexity=perplexity
    )
    reduced = tsne.fit_transform(vecs)

    plt.figure(figsize=(10, 8))
    for i, word in enumerate(words):
        x, y = reduced[i]
        plt.scatter(x, y)
        plt.annotate(word, (x, y), fontsize=12)
    plt.title("t-SNE Visualization of Word Embeddings")
    plt.grid(True)
    plt.show()


visualize_embeddings(embeddings, word2idx)

""",
r"""
#Program 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelBinarizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import plot_model

iris = load_iris()
X = iris.data
y = iris.target

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

encoder = LabelBinarizer()
y_encoded = encoder.fit_transform(y)

X_train, X_test, y_train, y_test = train_test_split(
    X_scaled,
    y_encoded,
    test_size=0.2,
    random_state=42
)

model = Sequential([
    Dense(64, input_shape=(X.shape[1],), activation="relu"),
    Dense(32, activation="relu"),
    Dense(16, activation="relu"),
    Dense(3, activation="softmax")
])

model.compile(
    optimizer="adam",
    loss="categorical_crossentropy",
    metrics=["accuracy"]
)

model.summary()

history = model.fit(
    X_train,
    y_train,
    epochs=100,
    validation_split=0.2,
    batch_size=8,
    verbose=0
)

loss, accuracy = model.evaluate(X_test, y_test)
print(f"\nTest Accuracy: {accuracy * 100:.2f}%")

plt.plot(history.history["accuracy"], label="Train Accuracy")
plt.plot(history.history["val_accuracy"], label="Validation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.title("Training & Validation Accuracy")
plt.grid(True)
plt.show()

""",
r"""
#Program 3
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

x_train, x_test = x_train / 255.0, x_test / 255.0

class_names = [
    "Airplane",
    "Automobile",
    "Bird",
    "Cat",
    "Deer",
    "Dog",
    "Frog",
    "Horse",
    "Ship",
    "Truck"
]

model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation="relu", input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64, (3, 3), activation="relu"),
    layers.MaxPooling2D((2, 2)),

    layers.Conv2D(64, (3, 3), activation="relu"),

    layers.Flatten(),
    layers.Dense(64, activation="relu"),
    layers.Dense(10, activation="softmax")
])

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

model.summary()

history = model.fit(
    x_train,
    y_train,
    epochs=10,
    validation_split=0.2,
    batch_size=64
)

test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)
print(f"\nTest Accuracy: {test_accuracy * 100:.2f}%")

plt.plot(history.history["accuracy"], label="Train Accuracy")
plt.plot(history.history["val_accuracy"], label="Validation Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.title("Training and Validation Accuracy")
plt.grid(True)
plt.show()
""",
r"""
#Program 4
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras import regularizers

(x_train, _), (x_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((len(x_train), -1))
x_test = x_test.reshape((len(x_test), -1))

encoding_dim = 32

input_img = Input(shape=(784,))
encoded = Dense(128, activation="relu")(input_img)
encoded = Dense(64, activation="relu")(encoded)
encoded = Dense(encoding_dim, activation="relu")(encoded)

decoded = Dense(64, activation="relu")(encoded)
decoded = Dense(128, activation="relu")(decoded)
decoded = Dense(784, activation="sigmoid")(decoded)

autoencoder = Model(input_img, decoded)
encoder = Model(input_img, encoded)

autoencoder.compile(optimizer="adam", loss="binary_crossentropy")

autoencoder.fit(
    x_train,
    x_train,
    epochs=50,
    batch_size=256,
    shuffle=True,
    validation_data=(x_test, x_test)
)

encoded_imgs = encoder.predict(x_test)
decoded_imgs = autoencoder.predict(x_test)

n = 10
plt.figure(figsize=(18, 6))

for i in range(n):
    ax = plt.subplot(3, n, i + 1)
    plt.imshow(x_test[i].reshape(28, 28), cmap="gray")
    plt.title("Original")
    plt.axis("off")

    ax = plt.subplot(3, n, i + 1 + n)
    plt.imshow(encoded_imgs[i].reshape(8, 4), cmap="viridis")
    plt.title("Encoded")
    plt.axis("off")

    ax = plt.subplot(3, n, i + 1 + 2 * n)
    plt.imshow(decoded_imgs[i].reshape(28, 28), cmap="gray")
    plt.title("Reconstructed")
    plt.axis("off")

plt.show()
""",
r"""
#Program 5
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout

vocab_size = 10000
maxlen = 200
embedding_dim = 128

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)

x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)

model = Sequential([
    Embedding(vocab_size, embedding_dim, input_length=maxlen),
    LSTM(128, return_sequences=False),
    Dropout(0.5),
    Dense(1, activation="sigmoid")
])

model.compile(
    loss="binary_crossentropy",
    optimizer="adam",
    metrics=["accuracy"]
)

model.summary()

history = model.fit(
    x_train,
    y_train,
    epochs=5,
    batch_size=64,
    validation_split=0.2
)

loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")
""",
r"""
#Program 6
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler

np.random.seed(42)
time = np.arange(0, 200, 0.1)
series = np.sin(time) + 0.1 * np.random.normal(size=len(time))

plt.plot(time, series)
plt.title("Synthetic Time Series Data")
plt.show()


def create_dataset(data, window_size=20):
    X, y = [], []
    for i in range(len(data) - window_size):
        X.append(data[i : i + window_size])
        y.append(data[i + window_size])
    return np.array(X), np.array(y)


window_size = 20
X, y = create_dataset(series, window_size)

X = X.reshape((X.shape[0], X.shape[1], 1))

scaler = MinMaxScaler()
X_reshaped = X.reshape(-1, 1)
X_scaled = scaler.fit_transform(X_reshaped).reshape(X.shape)
y_scaled = scaler.transform(y.reshape(-1, 1))

model = Sequential([
    LSTM(50, activation="relu", input_shape=(window_size, 1)),
    Dense(1)
])

model.compile(optimizer="adam", loss="mse")

history = model.fit(
    X_scaled,
    y_scaled,
    epochs=30,
    batch_size=32,
    validation_split=0.2
)

y_pred_scaled = model.predict(X_scaled)
y_pred = scaler.inverse_transform(y_pred_scaled)

plt.figure(figsize=(12, 6))
plt.plot(series[window_size:], label="Actual")
plt.plot(y_pred.flatten(), label="Predicted")
plt.title("Time Series Forecasting with LSTM")
plt.xlabel("Time Steps")
plt.ylabel("Value")
plt.legend()
plt.show()
""",
r"""
#Program 7
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os

print("TensorFlow Version:", tf.__version__)

train_dir = "dataset/train"
val_dir = "dataset/val"
test_dir = "dataset/test"

img_size = 224
batch_size = 32

train_gen = ImageDataGenerator(
    rescale=1.0 / 255,
    rotation_range=20,
    zoom_range=0.2,
    horizontal_flip=True,
)

val_gen = ImageDataGenerator(rescale=1.0 / 255)

train_data = train_gen.flow_from_directory(
    train_dir, target_size=(img_size, img_size), batch_size=batch_size, class_mode="categorical"
)

val_data = val_gen.flow_from_directory(
    val_dir, target_size=(img_size, img_size), batch_size=batch_size, class_mode="categorical"
)

base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(img_size, img_size, 3))

for layer in base_model.layers:
    layer.trainable = False

x = GlobalAveragePooling2D()(base_model.output)
x = Dense(256, activation="relu")(x)
output = Dense(train_data.num_classes, activation="softmax")(x)

model = Model(inputs=base_model.input, outputs=output)
model.compile(optimizer=Adam(1e-4), loss="categorical_crossentropy", metrics=["accuracy"])

model.summary()

history = model.fit(train_data, validation_data=val_data, epochs=5)

plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(history.history["accuracy"])
plt.plot(history.history["val_accuracy"])
plt.title("Accuracy")
plt.legend(["Train", "Validation"])

plt.subplot(1, 2, 2)
plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("Loss")
plt.legend(["Train", "Validation"])

plt.show()


def predict_image(img_path):
    img = image.load_img(img_path, target_size=(img_size, img_size))
    img_array = image.img_to_array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    prediction = model.predict(img_array)
    class_index = np.argmax(prediction)
    class_names = list(train_data.class_indices.keys())

    print("Predicted Class:", class_names[class_index])
""",
r"""
#Program 8
class GridWorld:
    def __init__(self):
        self.rows = 5
        self.cols = 5

        self.start = (0, 0)
        self.goal = (4, 4)

        self.obstacles = {(1, 1), (2, 2), (3, 1)}

        self.agent_pos = self.start

    def reset(self):
        self.agent_pos = self.start
        return self.agent_pos

    def step(self, action):
        x, y = self.agent_pos

        if action == 0:
            next_pos = (x - 1, y)
        elif action == 1:
            next_pos = (x, y + 1)
        elif action == 2:
            next_pos = (x + 1, y)
        elif action == 3:
            next_pos = (x, y - 1)

        if not (0 <= next_pos[0] < self.rows and 0 <= next_pos[1] < self.cols):
            reward = -2
            next_pos = self.agent_pos
        elif next_pos in self.obstacles:
            reward = -2
            next_pos = self.agent_pos
        elif next_pos == self.goal:
            reward = +10
            self.agent_pos = next_pos
            return next_pos, reward, True
        else:
            reward = -1

        self.agent_pos = next_pos
        done = False
        return next_pos, reward, done

    def render(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if (i, j) == self.agent_pos:
                    print("A", end=" ")
                elif (i, j) == self.start:
                    print("S", end=" ")
                elif (i, j) == self.goal:
                    print("G", end=" ")
                elif (i, j) in self.obstacles:
                    print("X", end=" ")
                else:
                    print(".", end=" ")
            print()
        print()


env = GridWorld()

state = env.reset()
env.render()

actions = [1, 1, 2, 2, 2, 1, 1]

for action in actions:
    print("Action:", action)
    next_state, reward, done = env.step(action)
    env.render()
    print("Reward:", reward)
    print("Done:", done)
    print("------------------")
    if done:
        break
"""
    ]
    print(dl_progs[indx-1])