def dl(i):
    if i==1:
        print('''
#1
import numpy as np
import matplotlib.pyplot as plt

class Neuron:
    def __init__(self, n):
        self.w = np.random.rand(n)
        self.b = np.random.rand()

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def forward(self, data):
        return self.sigmoid(data@self.w + self.b)

# Generate
inputs = np.random.rand(100, 5)
neuron = Neuron(5)
outputs = neuron.forward(inputs)

print(outputs)

# Plot
x = np.linspace(-10, 10, 100)
plt.plot(x, neuron.sigmoid(x))
plt.xlabel("Input")
plt.ylabel("Output")
plt.show()

#1b
import numpy as np
from scipy.special import softmax

def sigmoid(x):
  return 1/(1+np.exp(-x))
def tanh(x):
  return np.tanh(x)
def softmaxx(x):
  vals=[softmax([i,0,0])[0] for i in x]
  return np.array(vals)

x=np.linspace(-10,10,1000)
plt.plot(x, sigmoid(x))
plt.show()
plt.plot(x, tanh(x))
plt.show()
plt.plot(x,softmaxx(x))
plt.show()
              ''')
    elif i==2:
        print('''
#2
import numpy as np

class Perceptron:
    def __init__(self, lr=0.01, epochs=100):
        self.lr = lr
        self.epochs = epochs

    def fit(self, X, y):
        self.w = np.zeros(X.shape[1])
        self.b = 0.
        for _ in range(self.epochs):
            for xi, yi in zip(X, y):
                p = self.predict(xi)
                e = yi - p
                self.w += self.lr * e * xi
                self.b += self.lr * e

    def predict(self, x):
        return int(np.dot(x, self.w) + self.b >= 0)

X = np.array([[2,3],[1,4],[3,5],[4,2]])
y = np.array([0,0,1,1])

p = Perceptron(0.01, 100)
p.fit(X, y)

x_new = np.array([2,4])
print("Prediction:", p.predict(x_new))

              ''')
    elif i==3:
        print('''
              #3
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
import matplotlib.pyplot as plt

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["target"] = iris.target

X, y = df.drop("target", axis=1), df["target"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

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

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

history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.1)
loss, acc = model.evaluate(X_test, y_test)
print("Test accuracy:", acc)

plt.plot(history.history["accuracy"], label="train")
plt.plot(history.history["val_accuracy"], label="val")
plt.title("Accuracy")
plt.legend()
plt.show()

plt.plot(history.history["loss"], label="train")
plt.plot(history.history["val_loss"], label="val")
plt.title("Loss")
plt.legend()
plt.show()

              ''')
    elif i==4:
        print('''
#4
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
import matplotlib.pyplot as plt

X, y = load_iris(return_X_y=True)
y = OneHotEncoder(sparse_output=False).fit_transform(y.reshape(-1, 1))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

def model():
    return Sequential([
        Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
        Dense(32, activation='relu'),
        Dense(3, activation='softmax')
    ])

def train(optimizer, batch):
    m = model()
    m.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
    return m.fit(X_train, y_train, epochs=50, batch_size=batch,
                 validation_data=(X_test, y_test), verbose=0)

gd_hist = train(SGD(0.01), 32)
sgd_hist = train(SGD(0.01), 1)

def plot(hist, title):
    plt.plot(hist.history['loss']); plt.plot(hist.history['val_loss'])
    plt.title(title + " Loss"); plt.legend(["Train", "Val"]); plt.show()

    plt.plot(hist.history['accuracy']); plt.plot(hist.history['val_accuracy'])
    plt.title(title + " Accuracy"); plt.legend(["Train", "Val"]); plt.show()

plot(gd_hist, "GD")
plot(sgd_hist, "SGD")

              ''')
    elif i==5:
        print('''
#5
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, Sequential
from tensorflow.keras.optimizers import Adam
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

# --- dataset ---
x, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

# ---dropout and clipnorm---
model = Sequential([
    layers.Dense(32, activation='relu', input_shape=(20,)),
    layers.Dropout(0.1),
    layers.Dense(16, activation='relu'),
    layers.Dropout(0.1),
    layers.Dense(1, activation='sigmoid')
])

opt = Adam(clipnorm=0.1)
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])
res1 = model.fit(x_train, y_train, epochs=3, validation_split=0.1)

plt.plot(res1.history['accuracy'])
plt.plot(res1.history['val_accuracy'])
plt.show()

# ---EarlyStopping ---
model = Sequential([
    layers.Dense(32, activation='relu', input_shape=(20,)),
    layers.Dense(16, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

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

es = tf.keras.callbacks.EarlyStopping()

res2 = model.fit(x_train, y_train, epochs=300, validation_split=0.1, callbacks=[es])

plt.plot(res2.history['accuracy'])
plt.plot(res2.history['val_accuracy'])
plt.show()


              ''')
    elif i==6:
        print(''' 
#6
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import layers, Sequential

#=== data ===
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train/255
x_test = x_test/255
x_train = x_train[...,None]
x_test  = x_test[...,None]
y_train = tf.keras.utils.to_categorical(y_train)
y_test  = tf.keras.utils.to_categorical(y_test)

#=== model ===
def create_model():
    model = Sequential([
        layers.Conv2D(13, 3, activation='relu', input_shape=(28,28,1)),
        layers.MaxPooling2D(),
        layers.Flatten(),
        layers.Dense(32, activation='relu'),
        layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    return model

#=== adversarial noise ===
def adv_net(x):
    perturbation = np.random.randn(*x.shape)
    eps = 0.1
    x_adv = x + eps * perturbation
    return np.clip(x_adv, 0, 1)

#=== tangent prop layer ===
class TangentProp(layers.Layer):
    def call(self, x):
        return x + tf.random.normal(tf.shape(x), stddev=0.1)

#=== adv net training ===
model = create_model()
x_adv = adv_net(x_train)
x_combined = np.concatenate([x_train, x_adv])
y_combined = np.concatenate([y_train, y_train])

res1 = model.fit(x_combined, y_combined, epochs=3, validation_split=0.1)

plt.plot(res1.history['accuracy'])
plt.plot(res1.history['val_accuracy'])
plt.show()

#=== tangent prop training ===
model = create_model()
model.add(TangentProp())   # valid Layer, not function

res2 = model.fit(x_train, y_train, epochs=3, validation_split=0.1)

plt.plot(res2.history['accuracy'])
plt.plot(res2.history['val_accuracy'])
plt.show()

    ''')
    elif i==7:
        print(''' 
    #7
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.mnist.load_data() #keep an eye

x_train=x_train/255.0
x_test=x_test/255.0
x_train=x_train[...,None]
x_test=x_test[...,None]
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(16, 3,activation='relu', input_shape=(28,28,1)), #keep an eye on input shape
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dense(32, activation='relu'),
    layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adagrad', loss='categorical_crossentropy', metrics=['accuracy']) #keep an eye
res=model.fit(x_train, y_train, validation_split=0.1, epochs=3) #validation_split and epochs
eval=model.evaluate(x_test, y_test) #keep an eye on evaluate not eval
print(res)

plt.plot(res.history['accuracy'])
plt.plot(res.history['val_accuracy'])
plt.show()

plt.plot(res.history['loss'])
plt.plot(res.history['val_loss'])
plt.show()
''')
    elif i==8:
        print(''' 
#8
import tensorflow as tf
from tensorflow.keras import layers, Sequential

# Load IMDB dataset (pre-tokenized as integers)
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=10000)

# Pad sequences so all reviews have equal length
x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=200)
x_test  = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=200)

# Build a simple RNN model (LSTM)
model = Sequential([
    layers.Embedding(input_dim=10000, output_dim=32, input_length=200),
    layers.LSTM(32),
    layers.Dense(1, activation="sigmoid")
])

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

# Train
model.fit(x_train, y_train, epochs=3, batch_size=64, validation_split=0.1)

# Evaluate
loss, acc = model.evaluate(x_test, y_test)
print("Test Accuracy:", acc)

''')
    elif i==9:
        print(''' 
#9
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense

# 1. Fetch data
data = yf.download("AAPL", start="2010-01-01", end="2023-01-01")[['Open']]
values = data.values

# 2. Train-test split (time-based)
train_len = int(len(values) * 0.8)
train = values[:train_len]
test  = values[train_len:]

# 3. Create sequences (60 previous days → next day)
def make_sequences(data, window=60):
    X = []
    y = []
    for i in range(window, len(data)):
        X.append(data[i-window:i])
        y.append(data[i])
    X = np.array(X).reshape((-1, window, 1))
    y = np.array(y)
    return X, y

x_train, y_train = make_sequences(train)
x_test,  y_test  = make_sequences(values[train_len-60:])

# 4. GRU model (minimal)
model = Sequential([
    GRU(32, input_shape=(60, 1)),
    Dense(1)
])

model.compile(optimizer="adam", loss="mse")
model.fit(x_train, y_train, epochs=3, batch_size=16)

# 5. Predict
pred = model.predict(x_test)

# 6. Plot results
plt.figure(figsize=(12,6))
plt.plot(data.index[train_len:], y_test, label="Actual")
plt.plot(data.index[train_len:], pred, label="Predicted")
plt.title("Minimal GRU Stock Price Prediction")
plt.legend()
plt.show()


''')
    elif i==10:
        print('''
#10
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import yfinance as yf

# fetch
data = yf.download('AAPL', start='2010-01-01', end='2023-01-01')
data = data[['Open']]
dataset = data.values

# scale
scaler = MinMaxScaler()
scaled = scaler.fit_transform(dataset)

# split
train_len = int(len(dataset) * 0.8)
train = scaled[:train_len]

# build sequences
x_train, y_train = [], []
for i in range(60, len(train)):
    x_train.append(train[i-60:i, 0])
    y_train.append(train[i, 0])

x_train, y_train = np.array(x_train), np.array(y_train)
x_train = x_train.reshape((x_train.shape[0], x_train.shape[1], 1))

# model
model = Sequential([
    LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)),
    Dropout(0.2),
    LSTM(50),
    Dropout(0.2),
    Dense(25),
    Dense(1)
])

model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train, y_train, batch_size=1, epochs=1)

# test sequences
test = scaled[train_len-60:]
x_test = []
y_test = dataset[train_len:]

for i in range(60, len(test)):
    x_test.append(test[i-60:i, 0])

x_test = np.array(x_test)
x_test = x_test.reshape((x_test.shape[0], x_test.shape[1], 1))

# predict
pred = model.predict(x_test)
pred = scaler.inverse_transform(pred)

# error
rmse = np.sqrt(mean_squared_error(y_test, pred))
print("RMSE:", rmse)

# plot
valid = data.iloc[train_len:].copy()
valid['Predictions'] = pred

plt.figure(figsize=(16,8))
plt.plot(data['Open'], label='Train')
plt.plot(valid[['Open', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'])
plt.show()

print(valid)
 ''')
    elif i==15:
        print('''
#5
#======A=======
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

# Synthetic dataset
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Dropout model
def dropout_model(rate=0.2):
    return Sequential([
        Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
        Dropout(rate),
        Dense(32, activation='relu'),
        Dropout(rate),
        Dense(1, activation='sigmoid')
    ])

m1 = dropout_model()
m1.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
h1 = m1.fit(X_train, y_train, epochs=50, batch_size=32,
            validation_data=(X_test, y_test), verbose=0)

# Gradient clipping model
def clip_model(clip_norm=1.0):
    opt = Adam(clipnorm=clip_norm)
    model = Sequential([
        Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
        Dense(32, activation='relu'),
        Dense(1, activation='sigmoid')
    ])
    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])
    return model

m2 = clip_model()
h2 = m2.fit(X_train, y_train, epochs=50, batch_size=32,
            validation_data=(X_test, y_test), verbose=0)

# Plot accuracy comparison
plt.figure(figsize=(10, 6))
plt.plot(h1.history['accuracy'], '--', label='Dropout Train')
plt.plot(h1.history['val_accuracy'], label='Dropout Val')
plt.plot(h2.history['accuracy'], '--', label='GradClip Train')
plt.plot(h2.history['val_accuracy'], label='GradClip Val')
plt.title('Dropout vs Gradient Clipping Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
plt.show()

# ========B=========

from tensorflow import keras
from tensorflow.keras import layers

# MNIST data
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Secondary task: parity (sum of digits mod 2)
y_train_parity = np.array([sum(map(int, str(i))) % 2 for i in y_train])
y_test_parity  = np.array([sum(map(int, str(i))) % 2 for i in y_test])

# Multitask model
inputs = keras.Input(shape=(28, 28))
x = layers.Flatten()(inputs)
x = layers.Dense(128, activation='relu')(x)
digit_out = layers.Dense(10, activation='softmax')(x)   # Task 1: digit classification
parity_out = layers.Dense(1, activation='sigmoid')(x)   # Task 2: even/odd

model = keras.Model(inputs=inputs, outputs=[digit_out, parity_out])
model.compile(
    optimizer='adam',
    loss=['sparse_categorical_crossentropy', 'binary_crossentropy'],
    metrics=[['accuracy'], ['accuracy']]
)

# Early stopping callback
early = keras.callbacks.EarlyStopping(
    monitor='val_loss', patience=5, restore_best_weights=True
)

# Train multitask model
history = model.fit(
    x_train, [y_train, y_train_parity],
    epochs=20, validation_split=0.2, callbacks=[early], verbose=1
)

# Find early stopping epoch
stop_epoch = np.argmin(history.history['val_loss']) + 1
print("
Early stopping occurred at epoch:", stop_epoch)

# Plot loss with early stopping mark
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.axvline(stop_epoch, color='r', linestyle='--', label='Early Stop Point')
plt.title('Multitask Learning with Early Stopping')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
              ''')
    elif i==18:
        print('''
#8
    import numpy as np
    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
    import matplotlib.pyplot as plt

    # load imdb
    max_features = 10000
    maxlen = 200
    (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)

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

    # model
    model = Sequential([
        Embedding(max_features, 50, input_length=maxlen),
        LSTM(64, dropout=0.2, recurrent_dropout=0.2),
        Dense(1, activation='sigmoid')
    ])

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

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

    loss, acc = model.evaluate(x_test, y_test)
    print("Test accuracy:", acc)

    # sentiment prediction
    def predict_sentiment(text):
        w2i = imdb.get_word_index()
        seq = [(w2i[w] if w in w2i and w2i[w] < max_features else 0)
               for w in text.lower().split()]
        seq = pad_sequences([seq], maxlen=maxlen)
        return model.predict(seq)[0][0]

    print("Positive:", predict_sentiment("this movie was fantastic and i loved it"))
    print("Negative:", predict_sentiment("this movie was awful and boring"))

    # plots
    plt.plot(history.history['accuracy'], label="train")
    plt.plot(history.history['val_accuracy'], label="val")
    plt.title("accuracy")
    plt.show()

    plt.plot(history.history['loss'], label="train")
    plt.plot(history.history['val_loss'], label="val")
    plt.title("loss")
    plt.show()
              ''')
    else:
        print("invalid Number")