def dl(i):
    if i==1:
        print('''
#1
#Lab-01
import numpy as np
import matplotlib.pyplot as plt
class Neuron:
 def __init__(self, input_size):
 # Initialize random weights and bias
 self.weights = np.random.rand(input_size)
 self.bias = np.random.rand()
 def sigmoid(self, x):
 return 1 / (1 + np.exp(-x))
 def tanh(self, x):
 return np.tanh(x)
 def relu(self, x):
 return np.maximum(0,x)
 def softmax(self, x):
 return np.exp(x)/np.sum(np.exp(x))
 def forward(self, inputs):
 # Math: (inputs * weights) + bias
 z = np.dot(inputs, self.weights) + self.bias
 return self.sigmoid(z)
# Driver Code
input_size = 5
inputs = np.random.rand(10, input_size) # 10 samples
neuron = Neuron(input_size)
for i in range(len(inputs)):
 print(f"Output {i}: {neuron.forward(inputs[i])}")
#Sigmoid graph
x = np.linspace(-10, 10, 100)
sigmoid_values = neuron.sigmoid(x)
plt.plot(x, sigmoid_values)
plt.title('Sigmoid Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.grid(True)
plt.show()
#Hyperbolic tan graph
t = np.linspace(-5, 5,1000)
hyperbolictanh_values = neuron.tanh(t)
plt.plot(t, hyperbolictanh_values, )
plt.title('Hyperbolic Tan Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.grid(True)
plt.show()
#Relu graph
r = np.linspace(-5,5)
relu_values = neuron.relu(r)
plt.plot(r, relu_values)
plt.title('Relu Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.grid(True)
plt.show()
#Softmax graph
s = np.linspace(-5,5)
softmax_values = neuron.softmax(s)
plt.plot(s, softmax_values)
plt.title('Softmax Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.grid(True)
plt.show()
              ''')
    elif i==2:
        print('''
#Lab-02
import numpy as np
class Perceptron:
 def __init__(self, learning_rate=0.01, epochs=100):
 # Hyperparameters
 self.lr = learning_rate
 self.epochs = epochs
 self.weights = None
 self.bias = 0
 def fit(self, X, y):
 # Initialize weights to zeros based on number of inputs
 self.weights = np.zeros(X.shape[1])
 # Training Loop
 for epoch in range(self.epochs):
 for i in range(X.shape[0]):
 # 1. Prediction (Step Function)
 linear_output = np.dot(X[i], self.weights) + self.bias
 y_pred = 1 if linear_output >= 0 else 0
 # 2. Calculate Error
 error = y[i] - y_pred
 # 3. Update Weights and Bias
 self.weights += self.lr * error * X[i]
 self.bias += self.lr * error
 print(f'Epoch {epoch+1}, Sample {i+1}: Weights:
{self.weights}, Bias: {self.bias}')
 def predict(self, x):
 # Predict for a single input
 linear_output = np.dot(x, self.weights) + self.bias
 return 1 if linear_output >= 0 else 0
# --- Driver Code ---
# Data: AND Gate Logic
X_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_train = np.array([0, 0, 0, 1])
# Create and Train Perceptron
print("Training Perceptron on AND Gate...")
model = Perceptron(learning_rate=0.1, epochs=10)
model.fit(X_train, y_train)
# Test the model
test_point = np.array([1, 1])
prediction = model.predict(test_point)
print(f"\nPrediction for {test_point}: {prediction}")
              ''')
    elif i==3:
        print('''
#LAb-03
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
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# --- 1. Data Preparation ---
iris = load_iris()
X = iris.data
y = iris.target
# Split and Scale (Crucial for Neural Networks)
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)
# --- 2. Model Architecture ---
model = Sequential([
 # Input Layer (4 features) -> Hidden Layer 1
 Dense(64, activation='relu', input_shape=(4,)),
 # Hidden Layer 2
 Dense(32, activation='relu'),
 # Output Layer (3 classes for Iris) -> Softmax
 Dense(3, activation='softmax')
])
# --- 3. Compile and Train ---
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy', metrics=['accuracy'])
print("Training MLP...")
history = model.fit(X_train, y_train, epochs=50, validation_split=0.1,
verbose=0)
# --- 4. Evaluation ---
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy}")
# --- 5. Plotting ---
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Model Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
              ''')
    elif i==4:
        print('''
#Lab-04
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
import matplotlib.pyplot as plt
# --- 1. Data Preparation ---
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target, test_size=0.2)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test) # Scale X_test as well
# --- 2. Helper Function ---
def run_experiment(batch_size, label_name):
 # Define simple model
 model = Sequential([
 Dense(10, activation='relu', input_shape=(4,)),
 Dense(3, activation='softmax')
 ])
 # Use SGD Optimizer
 model.compile(optimizer=SGD(learning_rate=0.01),
 loss='sparse_categorical_crossentropy',
 metrics=['accuracy'])
 # Train with validation split to get val_loss and val_accuracy
 history = model.fit(X_train, y_train, epochs=20,
batch_size=batch_size, verbose=0, validation_split=0.1)
 return history
# Experiment A: Gradient Descent (Batch Size = Total Samples)
print("Running Gradient Descent...")
history_gd = run_experiment(len(X_train), 'Gradient Descent
(Batch=All)')
# Experiment B: Stochastic Gradient Descent (Batch Size = 1)
print("Running Stochastic Gradient Descent...")
history_sgd = run_experiment(1, 'Stochastic GD (Batch=1)')
# --- 4. Plotting ---
# Plot 1: Loss (Train vs Val) for GD and SGD
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(history_gd.history['loss'], label='Train Loss')
plt.plot(history_gd.history['val_loss'], label='Val Loss')
plt.title('Batch GD Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history_sgd.history['loss'], label='Train Loss')
plt.plot(history_sgd.history['val_loss'], label='Val Loss')
plt.title('SGD Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Plot 2: Accuracy (Train vs Val) for GD and SGD
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(history_gd.history['accuracy'], label='Train Acc')
plt.plot(history_gd.history['val_accuracy'], label='Val Acc')
plt.title('Batch GD Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history_sgd.history['accuracy'], label='Train Acc')
plt.plot(history_sgd.history['val_accuracy'], label='Val Acc')
plt.title('SGD Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# Plot 3: GD vs SGD Loss
plt.figure(figsize=(10, 6))
plt.plot(history_gd.history['loss'], label='Gradient Descent')
plt.plot(history_sgd.history['loss'], label='Stochastic GD')
plt.title('Gradient Descent vs SGD Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()

              ''')
    elif i==5:
        print('''
#Lab-05
import numpy as np, matplotlib.pyplot as plt, tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout, Flatten, Input
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping
from sklearn.datasets import make_classification, load_digits
from sklearn.model_selection import train_test_split
# Dropout vs Clipping
# 1. Data
X, y = make_classification(1000, 20, n_classes=2)
X_tr, X_te, y_tr, y_te = train_test_split(X, y)
# 2. Reusable Model Builder
def train_model(name, opt, use_drop=False):
 model = Sequential()
 model.add(Dense(64, 'relu', input_shape=(20,)))
 if use_drop: model.add(Dropout(0.2)) # Add Dropout if requested
 model.add(Dense(1, 'sigmoid'))
 # Fix: Use explicit keyword arguments for compile
 model.compile(optimizer=opt, loss='binary_crossentropy',
metrics=['accuracy'])
 h = model.fit(X_tr, y_tr, epochs=20, validation_data=(X_te, y_te),
verbose=0)
 plt.plot(h.history['val_accuracy'], label=name)
# 3. Execute Comparison
plt.figure(figsize=(10,4))
plt.subplot(1,2,1); plt.title("Dropout vs Clipping")
train_model("Dropout", Adam(), use_drop=True)
train_model("Clipping", Adam(clipnorm=1.0))
plt.legend()
# Multitask & Early Stopping
# 1. Data (Digits + Parity)
d = load_digits()
X, y = d.images/16.0, d.target
y_par = y % 2 # Parity (Even=0, Odd=1)
X_tr, X_te, y_tr, y_te, yp_tr, yp_te = train_test_split(X, y, y_par)
# 2. Functional API Model
inp = Input((8,8))
z = Flatten()(inp)
z = Dense(32, 'relu')(z)
out_digit = Dense(10, 'softmax')(z) # Task 1: Classify Digit
out_parity = Dense(1, 'sigmoid')(z) # Task 2: Classify Even/Odd
model = Model(inp, [out_digit, out_parity])
# This line was previously fixed, ensuring it uses Adam() explicitly
model.compile(optimizer=Adam(),
loss=['sparse_categorical_crossentropy', 'binary_crossentropy'])
# 3. Train with Early Stopping
es = EarlyStopping(monitor='val_loss', patience=3)
h = model.fit(X_tr, [y_tr, yp_tr], epochs=30, callbacks=[es],
validation_split=0.2, verbose=0)
# 4. Plot Loss
plt.subplot(1,2,2); plt.title("Early Stopping Loss")
plt.plot(h.history['loss'], label='Total Loss')
plt.plot(h.history['val_loss'], label='Val Loss')
plt.legend(); plt.show()

              ''')
    elif i==6:
        print(''' 
#Lab-06
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# --- 1. Data Preparation ---
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)
# --- 2. Augmentation Helper ---
def augment_data(data, labels, epsilon, mode):
 if epsilon == 0: return data, labels # Baseline (Tangent Distance
Reference)
 noise = np.random.randn(*data.shape)
 if mode == 'sign':
 perturbation = np.sign(noise) # Adversarial (Direction only)
 else:
 perturbation = noise # Tangent (Gaussian
distribution)
 x_aug = data + epsilon * perturbation
 # Combine original + augmented
 return np.concatenate([data, x_aug]), np.concatenate([labels,
labels])
# --- 3. Training Loop (4 Models) ---
# Configurations: (Epsilon, Noise Type)
experiments = {
 "Adversarial Training": (0.1, 'sign'),
 "Tangent Prop": (0.1, 'normal'),
 "Tangent Classifier": (0.01, 'normal'), # Smaller noise for
classifier invariance
 "Tangent Distance": (0.0, None) # Baseline/Reference
}
history_dict = {}
results = {}
print("Training Models...")
for name, (eps, mode) in experiments.items():
 # A. Augment Data
 x_tr_aug, y_tr_aug = augment_data(X_train, y_train, eps, mode)
 # [cite_start]B. Define Model (Fresh for each iteration) [cite:
266-271]
 model = Sequential([
 Dense(64, activation='relu', input_shape=(20,)),
 Dense(1, activation='sigmoid')
 ])
 model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
 # C. Train
 print(f" -> Training {name}...")
 hist = model.fit(x_tr_aug, y_tr_aug, epochs=20, batch_size=32,
verbose=0)
 history_dict[name] = hist
 # D. Evaluate
 loss, acc = model.evaluate(X_test, y_test, verbose=0)
 results[name] = (loss, acc)
# --- 4. Print Results ---
print("\n--- Final Results ---")
for name, (loss, acc) in results.items():
 print(f"{name}: Loss = {loss:.4f}, Accuracy = {acc:.4f}")
# --- 5. Plotting (Loss & Accuracy) ---
plt.figure(figsize=(14, 6))
# Subplot 1: Loss
plt.subplot(1, 2, 1)
for name, hist in history_dict.items():
 plt.plot(hist.history['loss'], label=name)
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
# Subplot 2: Accuracy
plt.subplot(1, 2, 2)
for name, hist in history_dict.items():
 plt.plot(hist.history['accuracy'], label=name)
plt.title('Training Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
plt.show()
    ''')
    elif i==7:
        print(''' 
   #Lab-07
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense
from tensorflow.keras.utils import to_categorical
# --- 1. Data Preparation ---
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# CRITICAL: Reshape to (Samples, Height, Width, Channels)
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
# One-hot encode labels (e.g., 5 -> [0,0,0,0,0,1,0,0,0,0])
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# --- 2. CNN Architecture ---
model = Sequential([
 # Convolution Layer: Extracts features
 Conv2D(32, kernel_size=(3,3), activation='relu',
input_shape=(28,28,1)),
 # Pooling Layer: Reduces size
 MaxPooling2D(pool_size=(2,2)),
 # Flatten: 2D -> 1D
 Flatten(),
 # Dense Layers: Classification
 Dense(128, activation='relu'),
 Dense(10, activation='softmax')
])
# --- 3. Training ---
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
print("Training CNN...")
history = model.fit(x_train, y_train, epochs=3, batch_size=64,
validation_split=0.1)
predictions = model.predict(x_test)
predicted_labels = [tf.argmax(prediction).numpy() for prediction in
predictions]
# --- 4. Plotting ---
plt.plot(history.history['accuracy'], label='Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.title('CNN Accuracy')
plt.legend()
plt.show()
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('CNN Loss')
plt.legend()
plt.show()
plt.figure(figsize=(10, 4))
num_images = 3
for i in range(num_images):
 plt.subplot(1, num_images, i + 1)
 plt.imshow(x_test[i].reshape(28,28), cmap="gray")
 plt.title(f"Predicted: {predicted_labels[i]}, True:
{tf.argmax(y_test[i]).numpy()}")
 plt.axis('off')
plt.show()

''')
    elif i==8:
        print(''' 
#Lab-08
import matplotlib.pyplot as plt
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, SimpleRNN, Dense
# --- 1. Data Loading ---
max_features = 10000
maxlen = 100
print("Loading IMDB data...")
(x_train, y_train), (x_test, y_test) =
imdb.load_data(num_words=max_features)
# Pad sequences so all reviews are same length
x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)
# --- 2. Model Architecture ---
model = Sequential([
 Embedding(max_features, 50, input_length=maxlen),
 SimpleRNN(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_data=(x_test, y_test), verbose=2)
loss, acc = model.evaluate(x_test, y_test, verbose=0)
print("Test Accuracy:", acc)
plt.figure(figsize=(10,4))
plt.subplot(1,2,1); plt.plot(history.history['accuracy']);
plt.plot(history.history['val_accuracy']); plt.title("Accuracy")
plt.subplot(1,2,2); plt.plot(history.history['loss']);
plt.plot(history.history['val_loss']); plt.title("Loss")
plt.tight_layout(); plt.show()
''')
    elif i==9:
        print(''' 
#Lab-09
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense
# 1. Load Data
df = yf.download("AAPL", period="5y")["Close"].values.reshape(-1,1)
# --- 2. Scale Data (Manual Math) ---
mn, mx = df.min(), df.max()
data = (df - mn) / (mx - mn)
# --- 3. Sequence Creation ---
X, y = [], []
seq_len = 60
for i in range(len(data) - seq_len):
 X.append(data[i : i+seq_len])
 y.append(data[i+seq_len])
# Reshape for GRU: (Samples, TimeSteps, Features)
X, y = np.array(X), np.array(y)
# --- 4. Build Model ---
model = Sequential([
 # Simplified to 1 layer.
 GRU(64, input_shape=(seq_len, 1)),
 Dense(1)
])
# --- 5. Train ---
model.compile(optimizer='adam', loss='mse')
model.fit(X, y, epochs=5, batch_size=32, verbose=1)
# --- 6. Plot Results ---
# Inverse Scale the predictions manually
pred = model.predict(X) * (mx - mn) + mn
actual = y * (mx - mn) + mn
plt.plot(actual, label="Actual Price")
plt.plot(pred, label="Predicted Price")
plt.legend()
plt.show()

''')
    elif i==10:
        print('''
#LAb-10
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense # <--- ONLY CHANGE
HERE
# --- 1. Load Data ---
# Download 5 years of Apple stock data
df = yf.download("AAPL", period="5y")["Close"].values.reshape(-1,1)
# --- 2. Scale Data (Manual Math) ---
# Normalize data to be between 0 and 1
mn, mx = df.min(), df.max()
data = (df - mn) / (mx - mn)
# --- 3. Sequence Creation ---
X, y = [], []
seq_len = 60 # Look back 60 days
for i in range(len(data) - seq_len):
 X.append(data[i : i+seq_len])
 y.append(data[i+seq_len])
# Reshape for LSTM: (Samples, TimeSteps, Features)
X, y = np.array(X), np.array(y)
# --- 4. Build Model ---
model = Sequential([
 # LSTM Layer
 LSTM(64, input_shape=(seq_len, 1)),
 Dense(1) # Output: Predicted Price
])
# --- 5. Train ---
model.compile(optimizer='adam', loss='mse')
print("Training LSTM...")
model.fit(X, y, epochs=5, batch_size=32, verbose=1)
# --- 6. Plot Results ---
# Inverse Scale to get actual prices back
pred = model.predict(X) * (mx - mn) + mn
actual = y * (mx - mn) + mn
plt.plot(actual, label="Actual Price")
plt.plot(pred, label="Predicted Price")
plt.title("Stock Prediction (LSTM)")
plt.legend()
plt.show()

 ''')
    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")


def dav(i):
    if i==1:
        print('''
        #1
import numpy as np
import pandas as pd
df=pd.read_csv('/content/dav1.csv')
df.head()

#a check for null
df.isnull()
df.notnull()
#b cuntinious to binary mapping using .apply()
df['sat_bin']=df['satisfaction level'].apply(lambda x: "High" if x>0.7 else "Low")
#c value mapping using.map()
df["purchase_num"]=df["purchase history"].map({"high":2,"med":1,"low":0})
#d outliers using z score (y - y')/ std(y)
df["z_score"] = (df["income"] - df["income"].mean()) / df["income"].std()
outliers = df[df["z_score"].abs() > 2]
print(outliers[['id','income','z_score']])
#e .fillna()
df["yoe"]=df["yoe"].fillna(df["yoe"].mean())

print(df.head())
        ''')
    elif i==2:
        print('''
            #2
df=pd.read_csv('/content/dav2.csv')
df.head()

#a .fillna()
df['city']=df['city'].fillna('unknown')
df['age']=df['age'].fillna(df['age'].mean())
#b column drop duplicates
df=df.drop_duplicates()
#c .map()
df['gender']=df['gender'].map({'m':'male','f':'female'})
#d np.cut(to group with labels)
bins=[18,30,40,50]
labels=["18-30","30-40","40-50"]
df["age_group"]=pd.cut(df.age,bins=bins,labels=labels)
#e create dummies
city_dummies = pd.get_dummies(df["city"])
df = pd.concat([df, city_dummies], axis=1) # dont forget
print(df.head())
            ''')
    elif i==3:
        print('''
              #3
df1=pd.read_csv('/content/dav3_df1.csv')
df2=pd.read_csv('/content/dav3_df2.csv')
print(df1.head())
print(df2.head())

#a multi/hierarchial index
df1_multi = df1.set_index(["product","month"])
#b merge
inner_join  = df1.merge(df2, on="orderid", how="inner")
left_join   = df1.merge(df2, on="orderid", how="left")
right_join  = df1.merge(df2, on="orderid", how="right")
outer_join  = df1.merge(df2, on="orderid", how="outer")
#c concat
vertical_concat   = pd.concat([df1, df1], axis=0)
horizontal_concat = pd.concat([df1, df1], axis=1)
#d merge to fillna of feedback
combined = df1.reset_index().merge(df2, on="orderid", how="left")
combined["feedback"] = combined["feedback"].fillna(combined["feedback"].mean())
#e pivot table / multi index.unstack
pivot_sales = df1.pivot_table(index="product", columns="month", values="sales", aggfunc="sum")
print(df.head())

''')
    elif i==4:
        print('''
              #4
df=pd.read_csv('/content/dav4.csv')
df.head()

#a pd / np opertation
pop_mean = df["population"].mean()
pop_sum  = df["population"].sum()
pop_max  = df["population"].max()
pop_min  = df["population"].min()
#b whole update
df["gdp"] = df["gdp"] * 1.10
#c mulit index - swap and sort
df_mi = df.set_index(["country","year"])
df_swap_sorted = df_mi.swaplevel().sort_index()
#d mulit index.unstack / pivot_table
df_unstacked = df_mi.unstack(level="year")
#e multi index
df_hier = df.set_index(["country","year"])
usa_pop_trend = df_hier.loc["usa","population"] #thesse 2 idt are
china_pop_trend = df_hier.loc["china","population"] #really necessary
print(df.head())
''')
    elif i==5:
        print('''
            #5
import pandas as pd
df = pd.read_csv("/content/dav5.csv")
print(df.head())
#a pivot_table
p1 = df.pivot_table(index="salesperson", columns="date", values="revenue", aggfunc="sum")
#b group by
p2 = df.groupby("products")["revenue"].mean()
#c
p3 = df.groupby("salesperson")["units sold"].max()
#d
p4 = (df.groupby("region")["revenue"].sum() / df["revenue"].sum()) * 100
#e value_counts to max
p5 = df["salesperson"].value_counts().idxmax()
#f pivot_table
p6 = df.pivot_table(index="salesperson", columns="products",
                    values=["revenue","units sold"], aggfunc="sum")
#g
p7 = df.pivot_table(index="region", columns="date", values="units sold", aggfunc="sum")
print(df.head())

              ''')
    elif i==6:
        print(''' 
              #6
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df=pd.read_csv("/content/dav6.csv")
print(df.head())
#a game vs points scored
plt.plot(df["game"], df["points scored"])
plt.show()
#b game vs avg attendence
plt.plot(df["game"], df["attendance"])
average_attendance = df['attendance'].mean()
plt.axhline(average_attendance)
plt.show()
#c player score
player_points = {'Alice': 120,'Bob': 150,'Charlie': 100,'Diana': 180}
plt.bar(player_points.keys(), player_points.values())
plt.show()
#d score above thereshold
bins = [0,80,100,120]
labels = ["<80","80-100",">100"]
df["range"] = pd.cut(df["points scored"], bins=bins, labels=labels, include_lowest=True)
score_range_counts = df['range'].value_counts().sort_index()
plt.bar(score_range_counts.index, score_range_counts.values, color='skyblue')
plt.show()
#e points vs opponent points
plt.bar(df['points scored'], df['opponent points'])
#f attendance vs opponend
attendance_vs_opponent = df.groupby('opponent points')['attendance'].mean()
attendance_vs_opponent.plot(kind='bar', color='mediumseagreen')
plt.show()
#g win loss ratio
df['Result'] = df.apply(lambda row: 'Win' if row['points scored'] > row['opponent points'] else 'Loss', axis=1)
avg_points = df.groupby('Result')['points scored'].mean()
win_loss_counts = df['Result'].value_counts()
summary = pd.DataFrame({
    'Games': win_loss_counts,
    'Average Points Scored': avg_points
})
summary.plot(kind='bar')
plt.show()
              ''')
    elif i==7:
        print(''' 
              #7 wont work
df=pd.read_csv('/content/dav7.csv')
df.head()
df["Date/Time"] = pd.to_datetime(df["Date"] + " " + df["Time"]) #maybe
df["Date/Time"] = pd.to_datetime(df["Date/Time"])
df["hour"] = df["Date/Time"].dt.hour
df["day"] = df["Date/Time"].dt.day_name()
df["month"] = df["Date/Time"].dt.month

#a
pivot_heat = df.groupby(["day","hour"]).size().unstack(fill_value=0)
plt.figure(figsize=(6,4))
sns.heatmap(pivot_heat)
plt.show()
#b
daily_counts = df.groupby(df["Date"].dt.date).size()
plt.plot(daily_counts.index, daily_counts.values)
plt.show()
#c
region_counts = df["PuFrom"].value_counts()
plt.scatter(region_counts.index, region_counts.values, s=region_counts.values*50)
plt.show()
              ''')
    elif i==8:
        print(''' 
              #8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df=pd.read_csv('/content/dav8.csv')

#a
survival_rate = df.groupby("Pclass")["Survived"].mean()
plt.bar(survival_rate.index, survival_rate.values)
plt.show()

#b
counts=df['Survived'].value_counts()
plt.pie(counts.values, labels=['Alive', 'Ded'])
plt.show()

#c
temp=df.groupby([ 'Pclass'])['Survived'].value_counts().unstack()
temp.plot(kind='bar', stacked=True)
              ''')
    elif i==9:
        print(''' 
              #9
df=pd.read_csv('dav9.csv')
df.head()
#a
plt.scatter(df["GrLivArea"], df["SalePrice"])
plt.show()
#b
cols=["GrLivArea","OverallQual","TotalBsmtSF","SalePrice"]
corr=df[cols].corr()
sns.heatmap(corr)
#c
plt.scatter(df["GrLivArea"], df["SalePrice"],c=df["YearBuilt"], s=df["OverallQual"]*20)
plt.show()
              ''')
    elif i==10:
        print(''' 
              #10
# !pip install squarify
import squarify
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df=pd.read_csv('/content/dav10.csv')

position=(df['player_positions'].str.split(', ').explode()).value_counts()
# position= df.groupby(df['player_positions'].str.split(',')) ['overall'].mean() #bharath
plt.bar(position.index, position.values)
plt.show()

rating=(df['player_positions'].str.split(', ').explode()).value_counts()
plt.pie(rating.values, labels=rating.index,  wedgeprops={'width':0.4})
plt.show()

squarify.plot(sizes=rating.values, label=rating.index)
              ''')