0% found this document useful (0 votes)
7 views3 pages

DL Program 2

Uploaded by

Aishwarya J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

DL Program 2

Uploaded by

Aishwarya J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

2.

write a program to demonstrate the working of


Deep Neural Network for Classification in PyTorch

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import numpy as np

# 1. Load and preprocess the dataset


iris = load_iris()
X = iris.data # Features: sepal length, sepal width, petal length, petal width
y = iris.target # Classes: 0, 1, 2

# Scale features for better training


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

# Convert to tensors
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.long)

# Split into train and test sets


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

# 2. Define the deep neural network model


class DeepNN(nn.Module):
def __init__(self, input_size, hidden1, hidden2, output_size):
super(DeepNN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden1) # First hidden layer
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(hidden1, hidden2) # Second hidden layer
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(hidden2, output_size) # Output layer

def forward(self, x):


out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
out = self.relu2(out)
out = self.fc3(out)
return out

# 3. Initialize model, loss function, and optimizer


model = DeepNN(input_size=4, hidden1=16, hidden2=8, output_size=3)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

# 4. Training loop
epochs = 100
for epoch in range(epochs):
model.train()

# Forward pass
outputs = model(X_train)
loss = criterion(outputs, y_train)

# Backward pass and optimization


optimizer.zero_grad()
loss.backward()
optimizer.step()

if (epoch+1) % 10 == 0:
print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")

# 5. Evaluation
model.eval()
with torch.no_grad():
test_outputs = model(X_test)
_, predicted = torch.max(test_outputs, 1)
accuracy = (predicted == y_test).sum().item() / y_test.size(0)

print(f"\nTest Accuracy: {accuracy*100:.2f}%")

# 6. Show some predictions


print("\nSample Predictions:")
for i in range(5):
print(f"Features: {X_test[i].numpy()}, Predicted: {predicted[i].item()}, Actual:
{y_test[i].item()}")

You might also like