NNDL Manual
NNDL Manual
AIM:
To implement simple vector addition in TensorFlow
ALGORITHM:
Step1:Importing the necessary packages for the program.
Step2:create the vectors for the addition operation.
Step3: Perform the addition operation
Step4:Print the result for the given input.
PROGRAM:
# create a vector
vector1 = tf.constant([10, 10])
vector2 = tf.constant([20, 20])
# checking the dimensions of vector
print(vector1+vector2)
(3) x = [1, 2, 3, 4, 5]
y=1
tf.add(x, y)
x = tf.convert_to_tensor([1, 2, 3, 4, 5])
y = tf.convert_to_tensor(1)
x+y
(4) x = [1, 2, 3, 4, 5]
y = tf.constant([1, 2, 3, 4, 5])
tf.add(x, y)
RESULT:
Thus the implement simple vector addition in TensorFlow was executed successfully.
Ex No: 2
AIM:
To implement a regression model in Keras
ALGORITHM:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(16, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
RESULT:
AIM:
To implement a perceptron in TensorFlow
ALGORITHM:.
PROGRAM:
import tensorflow as tf
# Define the perceptron function
def perceptron(X, weights, bias):
sum = tf.matmul(X, weights) + bias # linear combination
output = tf.math.sign(sum) # activation function
return output
# Define training data
X_train = tf.constant([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=tf.float32)
y_train = tf.constant([[-1], [-1], [-1], [1]], dtype=tf.float32)
# Define the perceptron's variables
weights = tf.Variable(tf.zeros([2, 1]), dtype=tf.float32)
bias = tf.Variable(tf.zeros([1]), dtype=tf.float32)
# Define the perceptron's training process
learning_rate = 0.1
epochs = 20
for epoch in range(epochs):
with tf.GradientTape() as tape:
y_pred = perceptron(X_train, weights, bias)
loss = tf.reduce_mean(tf.square(y_train - y_pred))
gradients = tape.gradient(loss, [weights, bias])
weights.assign_sub(learning_rate * gradients[0])
bias.assign_sub(learning_rate * gradients[1])
print('Epoch:', epoch+1, ' Loss:', loss.numpy())
# Test the perceptron's predictions
X_test = tf.constant([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=tf.float32)
y_test = tf.constant([[-1], [-1], [-1], [1]], dtype=tf.float32)
y_pred = perceptron(X_test, weights, bias)
print('Predictions:',
y_pred.numpy())
RESULT:
AIM :
To implement a perceptron in keras
ALGORITHM:
Step1: start the program.
Step2:Create the sequential model.
Step3:Add the single dense layer with a single output.
Step4:Add an activation layer with sigmoid
Step5:compile the model.
Step6:Evaluate the model and the stop the program.
PROGRAM:
import keras
from keras.models import Sequential
from keras.layers.core import Dense, Activation
# create a sequential model
model = Sequential()
# add a single dense layer with a single output and input_dim of 2
model.add(Dense(units=1, input_dim=2))
# add an activation layer with a sigmoid activation function
model.add(Activation('sigmoid'))
# compile the model
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])
# train the model on sample data
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
Y = [0, 0, 0, 1]
model.fit(X, Y, epochs=1000, batch_size=4, verbose=0)
# evaluate the model on test data
loss, accuracy = model.evaluate(X, Y, verbose=0)
print("Accuracy: ", accuracy)
RESULT:
AIM :
To implement a Feed-Forward network in TensorFlow
ALGORITHM:
PROGRAM:
import tensorflow as tf
# Load dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize data
x_train, x_test = x_train / 255.0, x_test / 255.0
# Define model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)])
# Define loss function and optimizer
loss_fn=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
optimizer = tf.keras.optimizers.Adam()
# Compile the model
model.compile(optimizer=optimizer,loss=loss_fn,metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=5)
# Evaluate the model
model.evaluate(x_test, y_test, verbose=2)
RESULT:
AIM :
To implement a Feed-Forward network in Keras
ALGORITHM:
PROGRAM
#implement a feed forward neural network in keras
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# Generate some dummy data
X = np.random.rand(100, 10) # 100 samples with 10 features each
y = np.random.randint(2, size=100) # Binary labels (0 or 1)
# Create a sequential model
model = Sequential()
# Add layers to the model
model.add(Dense(units=64, activation='relu', input_dim=10)) # Input layer with 10 input features
model.add(Dense(units=32, activation='relu')) # Hidden layer with 32 units
model.add(Dense(units=1, activation='sigmoid')) # Output layer with 1 unit and sigmoid activation
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=10, batch_size=32)
# Make predictions
sample_input = np.random.rand(1, 10) # Input for a single sample
prediction = model.predict(sample_input)
print("Prediction:", prediction)
RESULT:
AIM:
To implement an image classifier using CNN in TensorFlow
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
# Compile the model with appropriate loss function, optimizer and metrics
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
RESULT:
Thus the implement an image classifier using CNN in TensorFlow was executed successfully
Ex No: 5(b)
IMPLEMENT AN IMAGE CLASSIFIER USING CNN IN KERAS
Date:
AIM:
To implement an image classifier using CNN in Keras
.
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Load the dataset
(train_images, train_labels), (test_images, test_labels) = keras.datasets.cifar10.load_data()
# Normalize pixel values between 0 and 1
train_images = train_images.astype('float32') / 255.0
test_images = test_images.astype('float32') / 255.0
# Define the model using CNN
model = keras.Sequential([
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'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
# Compile the model with appropriate loss function, optimizer and metrics
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the model on the training set
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)
RESULT:
Thus the implement an image classifier using CNN in Keras was executed successfully.
Ex No:9
PERFORM SENTIMENT ANALYSIS USING RNN
Date:
AIM:
To Perform sentiment analysis using RNN
ALGORITHM:
Step1: Import the packages.
Step2:Set the hyperparameters and load the dataset.
Step3:Pad the sequences to make them same length.
Step4:Define and compile the model.
Step5:Train and evaluate the model.
PROGRAM:
import keras
from keras.datasets import imdb
from keras.layers import Dense, Embedding, SimpleRNN
from keras.models import Sequential
from keras.preprocessing import sequence
# Set hyperparameters
model = Sequential()
model.add(Embedding(max_features, 32))
model.add(SimpleRNN(32))
model.add(Dense(1, activation='sigmoid'))
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test))
RESULT:
Thus Perform sentiment analysis using RNN was executed successfully.
Ex No:10(a)
IMPLEMENT AN LSTM BASED AUTOENCODER IN
Date:
TENSORFLOW
AIM:
To implement an LSTM based autoencoder in TensorFlow.
ALGORITHM:
Step1:Import the necessary packages.
Step2:Set the hyperparameters.
Step3:Define the autoencoder model.
Step4:Compile the autoencoder.
Step5:Train the autoencoder using random data.
Step6:Test the autoencoder and then stop.
PROGRAM:
import tensorflow as tf
from tensorflow.keras.layers import Input, LSTM, RepeatVector, TimeDistributed, Dense
from tensorflow.keras.models import Model
# Set hyperparameters
autoencoder.compile(optimizer='adam', loss='mse')
import numpy as np
RESULT:
AIM:
ALGORITHM:
Step1:Import the packages for the program.
Step2:Set the hyperparameters.
Step3:Define the autoencoder model.
Step4:Compile the autoencoder.
Step5:Train the autoencoder using random data.
Step6: Test the autoencoder and then stop the program.
PROGRAM:
# Set hyperparameters
autoencoder.compile(optimizer='adam', loss='mse')
import numpy as np
RESULT:
AIM:
To implement image generation using GAN .
ALGORITHM:
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def build_generator():
model = keras.Sequential([
layers.Dense(7 * 7 * 256, input_shape=(100,)),
layers.LeakyReLU(alpha=0.2),
layers.Reshape((7, 7, 256)),
layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same'),
layers.LeakyReLU(alpha=0.2),
layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same'),
layers.LeakyReLU(alpha=0.2),
layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', activation='tanh'),
])
return model
def build_discriminator():
model = keras.Sequential([
layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=(28, 28, 1)),
layers.LeakyReLU(alpha=0.2),
layers.Dropout(0.3),
layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'),
layers.LeakyReLU(alpha=0.2),
layers.Dropout(0.3),
layers.Flatten(),
layers.Dense(1, activation='sigmoid'),
])
return model
generator = build_generator()
discriminator=build_discriminator()
num_images = 10
noise = np.random.normal(0, 1, (num_images, 100))
generated_images = generator.predict(noise)
for i in range(num_images):
plt.subplot(1, num_images, i + 1)
plt.imshow(generated_images[i, :, :, 0], cmap='gray')
plt.axis('off')
plt.show()
RESULT: