Ex.No.2.
Installing Keras, Tensorflow and Pytorch libraries and making use of them
Aim:
To install Keras, Tensorflow and Pytorch libraries and making use of them.
Installation:
Installing Keras Library:
To install Keras, type the below command in terminal
pip install Keras
Installing Tensorflow Library:
To install tensorflow, type the below command in terminal
pip install tensorflow
Installing PyTorch Library:
To install PyTorch, type the below command in terminal
pip install torch
Tensorflow & Keras Program:
Aim:
To write a python program in Tensorflow & Keras.
Algorithm
1. Import numpy for data manipulation.
2. Import necessary classes from tensorflow.kerasm for building and training the neural
network.
3. Create a dataset with 100 samples, each having 8 features. The features are generated as
random numbers between 0 and 1.
4. Create binary target values (0 or 1) corresponding to each sample.
5. Create an empty neural network model using the Sequential API.
6. Add a Dense layer with 12 neurons, using the ReLU (Rectified Linear Unit) activation
function. This layer will take input with 8 features.
7. Add another Dense layer with 8 neurons, using the ReLU activation function.
8. Add an output Dense layer with 1 neuron, using the Sigmoid activation function to
produce a probability value for binary classification.
9. Set the optimizer to Adam, which adjusts the learning rate during training.
10. Use binary cross-entropy as the loss function, appropriate for binary classification tasks.
11. Specify accuracy as the evaluation metric to monitor the model's performance.
12. Fit the model on the generated data for 10 epochs with a batch size of 10.
13. During training, the model will learn to map features to the binary target values.
14. Generate 10 new samples with 8 features each for which predictions will be made.
15. Use the trained model to predict the probabilities of the new samples belonging to the
positive class (1).
16. Print the predicted probabilities for the new data.
Program:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Generate random data (replace with your own data)
X = np.random.rand(100, 8)
y = np.random.randint(2, size=100)
# Create a sequential model
model = Sequential()
model.add(Dense(units=12, input_dim=8, activation='relu'))
model.add(Dense(units=8, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=10, batch_size=10)
# Make predictions (replace with your own data)
new_data = np.random.rand(10, 8)
predictions = model.predict(new_data)
print(predictions)
Output:
Epoch 1/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 14s 6ms/step - accuracy: 0.8588 - loss: 0.4773
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 20s 6ms/step - accuracy: 0.9564 - loss: 0.1512
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 19s 5ms/step - accuracy: 0.9672 - loss: 0.1078
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 9s 5ms/step - accuracy: 0.9728 - loss: 0.0886
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.9766 - loss: 0.0740
313/313 - 1s - 3ms/step - accuracy: 0.9768 - loss: 0.0797
[0.07969701290130615, 0.9768000245094299]
PyTorch Program:
Aim:
To write a python program in PyTorch.
Algorithm:
1.Load the training and test datasets.
2.Apply appropriate transformations (e.g., converting to tensors).
3.Create a feedforward neural network with two fully connected layers (28x28 -> 128, 128 -> 10).
4.Create an instance of the SimpleNet model.
5.Define a loss function (e.g., CrossEntropyLoss).
6.Choose an optimization algorithm (e.g., Adam).
7.Iterate through a specified number of epochs.
8.For each epoch, iterate through each batch in the training data.
9.Calculate the model's output for the batch.
10.Compute the loss between the model's output and the true labels.
11.Backpropagate the loss to update the model's parameters.
12.Disable gradient calculation (with torch.no_grad()).
13.Iterate through each batch in the test data.
14.Calculate the model's output for the batch.
15.Calculate the accuracy by comparing the model's predictions to the true labels.
Program:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# Define the neural network architecture
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(28*28, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = torch.flatten(x, 1)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# Load the MNIST dataset
train_dataset = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.ToTensor())
test_dataset = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
# Initialize the model, loss function, and optimizer
model = SimpleNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
num_epochs = 5
for epoch in range(num_epochs):
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# Evaluate the model
correct = 0
total = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
accuracy = 100 * correct / total
print('Accuracy on test set: {}%'.format(accuracy))
Output:
Accuracy on test set: 97.27%
Result:
Thus the installation of the Keras, TensorFlow, and PyTorch libraries was completed, and they were
put to use.