PROGRAM-1
Q. Write a program for creating a perceptron.
CODE:
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, epochs=100):
[Link] = learning_rate
[Link] = epochs
[Link] = None
[Link] = None
def activation_func(self, x):
# Heaviside Step Function
return [Link](x >= 0, 1, 0)
def fit(self, X, y):
n_samples, n_features = [Link]
# Step 1: Initialize weights and bias to zero
[Link] = [Link](n_features)
[Link] = 0
# Step 2: Training loop
for _ in range([Link]):
for idx, x_i in enumerate(X):
# Linear output
linear_output = [Link](x_i, [Link]) + [Link]
# Apply activation function
y_predicted = self.activation_func(linear_output)
# Step 3: Update weights and bias (Perceptron Learning Rule)
update = [Link] * (y[idx] - y_predicted)
[Link] += update * x_i
[Link] += update
def predict(self, X):
linear_output = [Link](X, [Link]) + [Link]
return self.activation_func(linear_output)
# --- Example Usage (Solving the AND Logic Gate) ---
if __name__ == "__main__":
# Inputs for AND gate
X = [Link]([[0, 0], [0, 1], [1, 0], [1, 1]])
# Targets (Outputs)
y = [Link]([0, 0, 0, 1])
p = Perceptron(learning_rate=0.1, epochs=10)
[Link](X, y)
print(f"Final Weights: {[Link]}")
print(f"Final Bias: {[Link]}")
print(f"Predictions: {[Link](X)}")
OUTPUT
PROGRAM-2
Write a program to implement a multi-layer perceptron using TensorFlow. Apply a multi-layer
perceptron (MLP) on the Iris dataset.
CODE:
import tensorflow as tf
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler, OneHotEncoder
import numpy as np
# 1. Load and Preprocess the Data
iris = load_iris()
X = [Link]
y = [Link](-1, 1)
# One-hot encode the target (3 species = 3 output nodes)
encoder = OneHotEncoder(sparse_output=False)
y = encoder.fit_transform(y)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
# Scale features (MLPs are sensitive to feature scales)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = [Link](X_test)
# 2. Build the MLP Architecture
model = [Link]([
# Input layer + First Hidden Layer
[Link](16, activation='relu',
input_shape=(4,)),
# Second Hidden Layer
[Link](8, activation='relu'),
# Output Layer (3 nodes for 3 classes, Softmax for
probability)
[Link](3, activation='softmax')
])
# 3. Compile the Model
[Link](
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 4. Train the Model
print("Training the MLP...")
history = [Link](X_train, y_train, epochs=50, batch_size=8,
verbose=0, validation_split=0.1)
# 5. Evaluate the Model
loss, accuracy = [Link](X_test, y_test, verbose=0)
print(f"\nTest Accuracy: {accuracy:.4f}")
# Example Prediction
sample = [Link]([[5.1, 3.5, 1.4, 0.2]]) # A typical Setosa
scaled_sample = [Link](sample)
prediction = [Link](scaled_sample, verbose=0)
print(f"Predicted Class Probabilities: {prediction}")
print(f"Predicted Species:
{iris.target_names[[Link](prediction)]}")
OUTPUT
PROGRAM -3
Write a program to demonstrate different activation functions.
CODE:
import numpy as np
import [Link] as plt
# Define the range of inputs (x-axis)
x = [Link](-5, 5, 100)
# 1. Sigmoid Function: Scales output between 0 and 1
def sigmoid(x):
return 1 / (1 + [Link](-x))
# 2. Tanh (Hyperbolic Tangent): Scales output between -1 and 1
def tanh(x):
return [Link](x)
# 3. ReLU (Rectified Linear Unit): Returns 0 for negative, x for
positive
def relu(x):
return [Link](0, x)
# 4. Leaky ReLU: Allows a small gradient for negative values
def leaky_relu(x, alpha=0.1):
return [Link](x > 0, x, x * alpha)
# --- Plotting the Functions ---
[Link](figsize=(12, 8))
# Sigmoid
[Link](2, 2, 1)
[Link](x, sigmoid(x), 'b', lw=2)
[Link]("Sigmoid")
[Link](True)
# Tanh
[Link](2, 2, 2)
[Link](x, tanh(x), 'r', lw=2)
[Link]("Tanh")
[Link](True)
# ReLU
[Link](2, 2, 3)
[Link](x, relu(x), 'g', lw=2)
[Link]("ReLU")
[Link](True)
# Leaky ReLU
[Link](2, 2, 4)
[Link](x, leaky_relu(x), 'm', lw=2)
[Link]("Leaky ReLU")
[Link](True)
plt.tight_layout()
[Link]()
OUTPUT
PROGRAM-4
Write a program in TensorFlow to demonstrate different loss functions.
CODE:
import tensorflow as tf
import numpy as np
# 1. Regression Context: Mean Squared Error (MSE)
# Predicted values vs. Actual continuous values
y_true_reg = [Link]([10.0, 15.0, 20.0])
y_pred_reg = [Link]([12.0, 14.0, 21.0])
mse_loss = [Link]()
loss_mse = mse_loss(y_true_reg, y_pred_reg).numpy()
# 2. Binary Classification: Binary Cross-Entropy
# Predicted probabilities (0 to 1) for a single class
y_true_bin = [Link]([1, 0, 1, 1])
y_pred_bin = [Link]([0.9, 0.1, 0.2, 0.8]) # The 0.2 is a
"confident" mistake
bce_loss = [Link]()
loss_bce = bce_loss(y_true_bin, y_pred_bin).numpy()
# 3. Multiclass Classification: Categorical Cross-Entropy
# Predicted probabilities for multiple classes (should sum to
1.0)
# Example: [Cat, Dog, Bird]
y_true_multi = [Link]([[0, 1, 0]]) # Actual is 'Dog'
y_pred_multi = [Link]([[0.1, 0.7, 0.2]]) # Predicted 70% 'Dog'
cce_loss = [Link]()
loss_cce = cce_loss(y_true_multi, y_pred_multi).numpy()
# --- Display Results ---
print(f"--- Loss Function Results ---")
print(f"Mean Squared Error (Regression): {loss_mse:.4f}")
print(f"Binary Cross-Entropy (Binary): {loss_bce:.4f}")
print(f"Categorical Cross-Entropy (Multi): {loss_cce:.4f}")
OUTPUT:
PROGRAM-5
Write a program to implement a Convolution Neural Network (CNN) in Keras. Perform
predictions using the trained Convolution Neural Network (CNN).
CODE:
import tensorflow as tf
from [Link] import layers, models
import numpy as np
# 1. Load and Preprocess the Data
mnist = [Link]
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize pixel values to be between 0 and 1
X_train, X_test = X_train / 255.0, X_test / 255.0
# Reshape data to include the channel dimension (28x28x1)
X_train = X_train.reshape((-1, 28, 28, 1))
X_test = X_test.reshape((-1, 28, 28, 1))
# 2. Build the CNN Architecture
model = [Link]([
# Convolutional Layer: 32 filters, 3x3 kernel size
layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(28, 28, 1)),
# Max Pooling: Reduces spatial dimensions
layers.MaxPooling2D((2, 2)),
# Second Convolutional Layer
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
# Flatten the 2D maps into a 1D vector
[Link](),
# Fully Connected Layer
[Link](64, activation='relu'),
# Output Layer (10 digits = 10 nodes)
[Link](10, activation='softmax')
])
# 3. Compile and Train
[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("Training CNN on MNIST...")
[Link](X_train, y_train, epochs=3, batch_size=64,
validation_split=0.1)
# 4. Perform Predictions
print("\n--- Making Predictions ---")
# Take the first 5 images from the test set
sample_images = X_test[:5]
sample_labels = y_test[:5]
predictions = [Link](sample_images)
for i in range(5):
predicted_digit = [Link](predictions[i])
actual_digit = sample_labels[i]
print(f"Sample {i+1}: Predicted {predicted_digit}, Actual
{actual_digit}")
OUTPUT:
PROGRAM-6
Write a program to build an Image Classifier with CIFAR-10 Data.
CODE:
import tensorflow as tf
from [Link] import datasets, layers, models
import [Link] as plt
# 1. Load and Normalize Data
(train_images, train_labels), (test_images, test_labels) =
datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images /
255.0
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
# 2. Build the Model
model = [Link]([
# Convolutional Base
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'),
# Dense Layers for Classification
[Link](),
[Link](64, activation='relu'),
[Link](0.2), # Helps prevent overfitting
[Link](10, activation='softmax')
])
# 3. Compile the Model
[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 4. Train the Model
print("Training on CIFAR-10...")
history = [Link](train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
# 5. Evaluate and Predict
test_loss, test_acc = [Link](test_images, test_labels,
verbose=2)
print(f'\nTest Accuracy: {test_acc:.4f}')
# Predict a single image
img_idx = 0 # Change this to test different images
prediction = [Link](test_images[img_idx:1])
predicted_class = class_names[[Link]()]
actual_class = class_names[test_labels[img_idx][0]]
print(f"\nPrediction: {predicted_class} | Actual:
{actual_class}")
OUTPUT:
PROGRAM-7
Write a program to demonstrate hyperparameter tuning in CNN.
CODE:
import tensorflow as tf
from tensorflow import keras
from [Link] import layers
import keras_tuner as kt
import numpy as np
# 1. Load and subset the data (Using 10,000 images instead of
60,000 for speed)
(img_train, label_train), (img_test, label_test) =
[Link].load_data()
img_train = img_train[:10000].astype('float32') / 255.0
label_train = label_train[:10000]
img_test = img_test[:2000].astype('float32') / 255.0
label_test = label_test[:2000]
# 2. Define the Model-Building Function
def model_builder(hp):
model = [Link]()
# Tune number of filters (Choice between 32 and 64 for
speed)
hp_filters = [Link]('filters', values=[32, 64])
[Link](layers.Conv2D(filters=hp_filters, kernel_size=(3,
3),
activation='relu', input_shape=(28,
28, 1)))
[Link](layers.MaxPooling2D(pool_size=(2, 2)))
[Link]([Link]())
# Tune Dense units
hp_units = [Link]('units', min_value=32, max_value=64,
step=32)
[Link]([Link](units=hp_units, activation='relu'))
[Link]([Link](10, activation='softmax'))
# Tune learning rate
hp_lr = [Link]('learning_rate', values=[1e-2, 1e-3])
[Link](optimizer=[Link](learning_rate=hp_l
r),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# 3. Initialize the Tuner (RandomSearch is often faster to see
initial progress)
tuner = [Link](
model_builder,
objective='val_accuracy',
max_trials=3, # Limits the total number of models to
build
executions_per_trial=1,
directory='tuning_results',
project_name='mnist_fast_tune'
)
# 4. Run the Search
print("--- STARTING TUNING ---")
[Link](img_train, label_train,
epochs=3,
validation_split=0.2,
verbose=1) # Verbose=1 shows the progress bars!
# 5. Summary of Best Results
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print("\n--- TUNING COMPLETE ---")
print(f"Best Filters: {best_hps.get('filters')}")
print(f"Best Units: {best_hps.get('units')}")
print(f"Best LR: {best_hps.get('learning_rate')}")
# 6. Build and Train the final model with best params
final_model = [Link](best_hps)
final_model.fit(img_train, label_train, epochs=5,
validation_split=0.2)
OUTPUT:
PROGRAM-8
Write a program to perform face detection using a CNN.
CODE:
import cv2
from mtcnn import MTCNN
import [Link] as plt
import [Link]
import numpy as np
def detect_faces_from_url(url):
print("Downloading image...")
try:
# Create a request object with a "User-Agent" header to
avoid 403 Forbidden
req_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT
10.0; Win64; x64)'}
req = [Link](url, headers=req_headers)
with [Link](req) as response:
arr = [Link](bytearray([Link]()),
dtype=np.uint8)
img = [Link](arr, -1)
except Exception as e:
print(f"Failed to download image: {e}")
return
if img is None:
print("Error: Could not decode image data.")
return
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)
# Initialize CNN Detector
detector = MTCNN()
# Detect
print("CNN is analyzing...")
results = detector.detect_faces(img_rgb)
# Draw Boxes
if len(results) > 0:
for face in results:
x, y, width, height = face['box']
[Link](img_rgb, (x, y), (x + width, y +
height), (0, 255, 0), 5)
print(f"Done! Found {len(results)} faces.")
else:
print("No faces found.")
# Show Output
[Link](figsize=(10, 8))
[Link](img_rgb)
[Link]('off')
[Link]()
# Sample URL
sample_url =
"[Link]
arack_Obama.jpg"
detect_faces_from_url(sample_url)
OUTPUT:
PROGRAM-9
Write a program to perform object detection using Deep Learning.
CODE:
from ultralytics import YOLO
import cv2
import [Link] as plt
import [Link]
import numpy as np
def run_object_detection(url):
# 1. Load a pre-trained YOLOv8 model (n = nano, the fastest
version)
model = YOLO('[Link]')
# 2. Download a sample image from the internet
print("Downloading image...")
req_headers = {'User-Agent': 'Mozilla/5.0'}
req = [Link](url, headers=req_headers)
with [Link](req) as response:
arr = [Link](bytearray([Link]()),
dtype=np.uint8)
img = [Link](arr, -1)
# 3. Perform Detection
print("YOLO is detecting objects...")
results = model(img) # This handles the CNN processing
# 4. Visualize Results
# YOLOv8 has a built-in method to draw boxes and labels
annotated_img = results[0].plot()
# Convert BGR to RGB for matplotlib
img_rgb = [Link](annotated_img, cv2.COLOR_BGR2RGB)
[Link](figsize=(12, 8))
[Link](img_rgb)
[Link]('off')
[Link]("YOLOv8 Object Detection")
[Link]()
# Sample URL: A busy street scene
sample_url = "[Link]
3747c53c99b4?q=80&w=1000"
run_object_detection(sample_url)
OUTPUT:
PROGRAM-10
Predicting Bike-Sharing Patterns – Build and train neural networks from scratch to predict the
number of bike share users on a given day.
CODE:
import numpy as np
class BikeRegressionNet:
def __init__(self, input_nodes, hidden_nodes, output_nodes,
learning_rate):
# Initialize weights with random values
self.weights_input_to_hidden = [Link](0.0,
input_nodes**-0.5,
(input_nodes,
hidden_nodes))
self.weights_hidden_to_output = [Link](0.0,
hidden_nodes**-0.5,
(hidden_nodes,
output_nodes))
[Link] = learning_rate
# Activation function: Sigmoid
self.activation_function = lambda x : 1 / (1 + [Link](-
x))
def train(self, features, targets):
n_records = [Link][0]
delta_w_i_h =
[Link](self.weights_input_to_hidden.shape)
delta_w_h_o =
[Link](self.weights_hidden_to_output.shape)
for X, y in zip(features, targets):
# --- Forward Pass ---
hidden_inputs = [Link](X,
self.weights_input_to_hidden)
hidden_outputs =
self.activation_function(hidden_inputs)
# For regression, the output layer usually has no
activation (linear)
final_inputs = [Link](hidden_outputs,
self.weights_hidden_to_output)
final_outputs = final_inputs
# --- Backward Pass (Backpropagation) ---
error = y - final_outputs
# Output error gradient
output_error_term = error # Derivative of linear
activation is 1
# Calculate hidden layer's contribution to the error
hidden_error = [Link](self.weights_hidden_to_output,
output_error_term)
hidden_error_term = hidden_error * hidden_outputs *
(1 - hidden_outputs)
# Accumulate weight changes
delta_w_h_o += output_error_term * hidden_outputs[:,
None]
delta_w_i_h += hidden_error_term * X[:, None]
# --- Update Weights ---
self.weights_hidden_to_output += [Link] * delta_w_h_o /
n_records
self.weights_input_to_hidden += [Link] * delta_w_i_h /
n_records
def run(self, features):
# Predict values
hidden_inputs = [Link](features,
self.weights_input_to_hidden)
hidden_outputs = self.activation_function(hidden_inputs)
final_inputs = [Link](hidden_outputs,
self.weights_hidden_to_output)
return final_inputs
# --- Simulation for testing ---
# 10 features (temp, humidity, etc.), 5 hidden nodes, 1 output
(riders)
network = BikeRegressionNet(10, 5, 1, 0.1)
# Dummy training data
X_train = [Link](100, 10)
y_train = [Link](100, 1)
print("Training started...")
for e in range(1000):
[Link](X_train, y_train)
if e % 200 == 0:
print(f"Epoch {e} completed")
print(f"Prediction for first sample: {[Link](X_train[0])}")
OUTPUT:
PROGRAM-11
Write a program to implement a Recurrent Neural Network.
CODE:
import tensorflow as tf
from [Link] import layers, models, datasets
from [Link] import sequence
# 1. Load the IMDB Dataset (Top 10,000 most frequent words)
max_features = 10000
maxlen = 500 # Cut off reviews after 500 words
batch_size = 32
print("Loading data...")
(X_train, y_train), (X_test, y_test) =
[Link].load_data(num_words=max_features)
# 2. Pad sequences (Ensure all reviews are the same length)
X_train = sequence.pad_sequences(X_train, maxlen=maxlen)
X_test = sequence.pad_sequences(X_test, maxlen=maxlen)
# 3. Build the RNN Architecture
model = [Link]([
# Embedding layer: Turns word integers into dense vectors of
fixed size
[Link](max_features, 32),
# Simple RNN layer with 32 memory units
[Link](32),
# Final classification layer
[Link](1, activation='sigmoid')
])
# 4. Compile the Model
[Link](optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['acc'])
# 5. Train the Model
print("Training RNN...")
history = [Link](X_train, y_train,
epochs=5,
batch_size=batch_size,
validation_split=0.2)
# 6. Evaluate
test_loss, test_acc = [Link](X_test, y_test)
print(f"\nTest Accuracy: {test_acc:.4f}")
OUTPUT:
PROGRAM-12
Write a program to implement LSTM and perform time series analysis using LSTM.
CODE:
import numpy as np
import tensorflow as tf
from [Link] import Sequential
from [Link] import LSTM, Dense
import [Link] as plt
from [Link] import MinMaxScaler
# 1. Generate Synthetic Time Series Data (a sine wave with
noise)
t = [Link](0, 1000)
data = [Link](0.05 * t) + [Link](0, 0.1, 1000)
data = [Link](-1, 1)
# 2. Preprocessing: Scaling data to [0, 1] is crucial for LSTMs
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 3. Create Windows (Lookback)
# Use the last 50 steps to predict the 51st
def create_dataset(dataset, look_back=50):
X, y = [], []
for i in range(len(dataset) - look_back - 1):
[Link](dataset[i:(i + look_back), 0])
[Link](dataset[i + look_back, 0])
return [Link](X), [Link](y)
look_back = 50
X, y = create_dataset(scaled_data, look_back)
# Reshape input to be [samples, time steps, features] - Required
by LSTM
X = [Link](X, ([Link][0], [Link][1], 1))
# Split into Train and Test
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# 4. Build the LSTM Model
model = Sequential([
# First LSTM layer
LSTM(50, return_sequences=True, input_shape=(look_back, 1)),
# Second LSTM layer (return_sequences=False because next
layer is Dense)
LSTM(50, return_sequences=False),
Dense(25),
Dense(1) # Final output (the prediction)
])
# 5. Compile and Train
[Link](optimizer='adam', loss='mean_squared_error')
print("Training LSTM on Time Series...")
[Link](X_train, y_train, batch_size=16, epochs=10, verbose=1)
# 6. Predict and Visualize
predictions = [Link](X_test)
predictions = scaler.inverse_transform(predictions) # Scale back
to original values
y_test_unscaled = scaler.inverse_transform(y_test.reshape(-1,
1))
[Link](figsize=(12, 6))
[Link](y_test_unscaled, label='Actual Data')
[Link](predictions, label='LSTM Prediction')
[Link]("Time Series Prediction using LSTM")
[Link]()
[Link]()
OUTPUT:
PROGRAM-13
Dog-Breed Classifier – Design and train a convolutional neural network to analyze images of
dogs and correctly identify their breeds. Use transfer learning and well-known architectures to
improve this model.
CODE:
import tensorflow as tf
from tensorflow import keras
import numpy as np
from [Link] import image
# Step 1: Load Pre-trained Model
base_model = [Link].MobileNetV2(
input_shape=(224,224,3),
include_top=False,
weights='imagenet'
)
base_model.trainable = False
model = [Link]([
base_model,
[Link].GlobalAveragePooling2D(),
[Link](128, activation='relu'),
[Link](10, activation='softmax') # 10 breeds
])
[Link](
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
print("Model ready")
# Step 2: Define Class Labels
class_names = [
"Labrador", "Pug", "German Shepherd", "Golden Retriever",
"Bulldog", "Beagle", "Rottweiler", "Dachshund",
"Husky", "Doberman"
]
# Step 3: Load and Preprocess Image
img_path = "[Link]"
img = image.load_img(img_path, target_size=(224,224))
img_array = image.img_to_array(img)
# Normalize for MobileNetV2
img_array =
[Link].mobilenet_v2.preprocess_input(img_array)
# Add batch dimension
img_array = np.expand_dims(img_array, axis=0)
# Step 4: Predict
predictions = [Link](img_array)
predicted_index = [Link](predictions[0])
predicted_breed = class_names[predicted_index]
confidence = [Link](predictions[0])
# Step 5: Output
print("Predicted Breed:", predicted_breed)
print("Confidence:", confidence*100, "%")
OUTPUT:
PROGRAM-14
Write a program to build an Artificial Neural Network by implementing the Back propagation
algorithm and test the same using appropriate data sets.
CODE:
import numpy as np
# 1. Activation Function: Sigmoid
def sigmoid(x):
return 1 / (1 + [Link](-x))
# 2. Derivative of Sigmoid (used for Backpropagation)
def sigmoid_derivative(x):
return x * (1 - x)
# --- DATASET (XOR Gate) ---
# Input: 4 samples with 2 features each
X = [Link]([[0, 0], [0, 1], [1, 0], [1, 1]])
# Expected Output: 4 samples
y = [Link]([[0], [1], [1], [0]])
# --- HYPERPARAMETERS ---
input_layer_neurons = 2
hidden_layer_neurons = 3
output_neurons = 1
learning_rate = 0.1
epochs = 10000
# --- WEIGHT & BIAS INITIALIZATION ---
# Weights from Input to Hidden
wh = [Link](size=(input_layer_neurons,
hidden_layer_neurons))
bh = [Link](size=(1, hidden_layer_neurons))
# Weights from Hidden to Output
wout = [Link](size=(hidden_layer_neurons,
output_neurons))
bout = [Link](size=(1, output_neurons))
# --- TRAINING LOOP ---
print("Training started...")
for i in range(epochs):
# --- FORWARD PROPAGATION ---
hidden_layer_input = [Link](X, wh) + bh
hidden_layer_activations = sigmoid(hidden_layer_input)
output_layer_input = [Link](hidden_layer_activations, wout)
+ bout
predicted_output = sigmoid(output_layer_input)
# --- BACKWARD PROPAGATION ---
# 1. Calculate error at Output Layer
error = y - predicted_output
d_predicted_output = error *
sigmoid_derivative(predicted_output)
# 2. Calculate error at Hidden Layer
error_hidden_layer = d_predicted_output.dot(wout.T)
d_hidden_layer = error_hidden_layer *
sigmoid_derivative(hidden_layer_activations)
# --- UPDATING WEIGHTS AND BIASES ---
wout += hidden_layer_activations.[Link](d_predicted_output) *
learning_rate
bout += [Link](d_predicted_output, axis=0, keepdims=True) *
learning_rate
wh += [Link](d_hidden_layer) * learning_rate
bh += [Link](d_hidden_layer, axis=0, keepdims=True) *
learning_rate
if i % 2000 == 0:
loss = [Link]([Link](y - predicted_output))
print(f"Epoch {i} - Loss: {loss:.4f}")
# --- TESTING ---
print("\nFinal Predicted Output after 10,000 epochs:")
print(predicted_output)
OUTPUT:
PROGRAM-15
Write a program to build an autoencoder in Keras.
CODE:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from [Link] import layers
# Step 1: Load dataset
(x_train, _), (x_test, _) = [Link].load_data()
# Normalize data
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Flatten images (28x28 -> 784)
x_train = x_train.reshape((len(x_train), 784))
x_test = x_test.reshape((len(x_test), 784))
# Step 2: Build Autoencoder
input_img = [Link](shape=(784,))
# Encoder
encoded = [Link](128, activation='relu')(input_img)
encoded = [Link](64, activation='relu')(encoded)
# Decoder
decoded = [Link](128, activation='relu')(encoded)
decoded = [Link](784, activation='sigmoid')(decoded)
# Autoencoder model
autoencoder = [Link](input_img, decoded)
# Step 3: Compile model
[Link](
optimizer='adam',
loss='binary_crossentropy'
)
# Step 4: Train model
[Link](
x_train,
x_train,
epochs=10,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test)
)
# Step 5: Test reconstruction
decoded_imgs = [Link](x_test)
print("Autoencoder training complete.")
OUTPUT:
PROGRAM-16
Write a program to implement basic reinforcement learning algorithm to teach a bot to reach its
destination.
CODE
import numpy as np
import random
# --- SETTINGS ---
GRID_SIZE = 4
ACTIONS = ['up', 'down', 'left', 'right']
NUM_ACTIONS = len(ACTIONS)
ALPHA = 0.1 # Learning rate
GAMMA = 0.9 # Discount factor (importance of future rewards)
EPSILON = 0.1 # Exploration rate (chance of taking a random move)
EPOCHS = 1000 # Number of training games
# --- INITIALIZE Q-TABLE ---
# State is (row, col). We flatten it to a single index for the table.
q_table = [Link]((GRID_SIZE * GRID_SIZE, NUM_ACTIONS))
def get_state_index(row, col):
return row * GRID_SIZE + col
def get_next_state(row, col, action):
if action == 'up': row = max(0, row - 1)
elif action == 'down': row = min(GRID_SIZE - 1, row + 1)
elif action == 'left': col = max(0, col - 1)
elif action == 'right': col = min(GRID_SIZE - 1, col + 1)
return row, col
# --- TRAINING ---
print("Bot is learning...")
for _ in range(EPOCHS):
row, col = 0, 0 # Start position
while (row, col) != (3, 3): # Goal position
state = get_state_index(row, col)
# Epsilon-greedy action selection
if [Link](0, 1) < EPSILON:
action_idx = [Link](0, NUM_ACTIONS - 1)
else:
action_idx = [Link](q_table[state])
action = ACTIONS[action_idx]
new_row, new_col = get_next_state(row, col, action)
new_state = get_state_index(new_row, new_col)
# Reward Logic
if (new_row, new_col) == (3, 3):
reward = 10
else:
reward = -1 # Penalty for each step to find shortest path
# Bellman Equation (Q-update)
best_future_q = [Link](q_table[new_state])
q_table[state, action_idx] += ALPHA * (reward + GAMMA * best_future_q - q_table[state,
action_idx])
row, col = new_row, new_col
print("Learning complete!\n")
# --- TESTING THE BOT ---
row, col = 0, 0
path = [(0, 0)]
while (row, col) != (3, 3):
state = get_state_index(row, col)
action_idx = [Link](q_table[state])
action = ACTIONS[action_idx]
row, col = get_next_state(row, col, action)
[Link]((row, col))
print(f"Optimal Path found by bot: {path}")
OUTPUT: