CCS355 Neural Networks and Deep Learning Lab
CCS355 Neural Networks and Deep Learning Lab
CODE:
# Import necessary packages
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import tensorflow as tf
# Get user input for vector 1
in1 = input("Enter space-separated values for vector 1: ")
vector1_values = [float(x) for x in in1.split()]
# Get user input for vector 2
in2 = input("Enter space-separated values for vector 2: ")
vector2_values = [float(x) for x in in2.split()]
# Define TensorFlow constants for the input vectors
vector1 = tf.constant(vector1_values, dtype=tf.float32)
vector2 = tf.constant(vector2_values, dtype=tf.float32)
# Perform vector addition
result_vector = tf.add(vector1, vector2)
AIM:
To implement a regression model in keras.
ALGORITHM:
Step 1: Import all necessary packages.
Step 2: Load the dataset from either packages or generate user data.
Step 3: Split the dataset into features(x) and target(y).
Step 4: Again split the dataset into training data(train_x,train_y) and testing
data(test_x,test_y) using traintestsplit().
Step 5: Define the model by creating sequential model with Dense layer and
linear activation function for regression.
Step 6: Compile the model with optimizer, loss function, and metrices.
Step 7: Train the model with training dataset using fit().
Step 8: Evaluate the model with test dataset using evaluate method.
Step 9: By using the trained model make predictions on new data or compare
prediction with ground truth.
CODE:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Make predictions
new_data = np.array([[0.5], [0.8], [1.0], [2.1]]) # New data for prediction
predictions = model.predict(new_data)
print("Predictions:", predictions)
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
AIM:
To implement a perceptron in tensorflow/keras environment.
ALGORITHM:
Step 1: Import all necessary packages.
Step 2: Load the dataset from either packages or generate user data.
Step 3: Split the dataset into features(x) and target(y).
Step 4: Again split the dataset into training data(train_x,train_y) and testing
data(test_x,test_y) using traintestsplit().
Step 5: Define the model by creating sequential model with Dense layer and
activation function for perceptron.
Step 6: Compile the model with optimizer, loss function, and metrices.
Step 7: Train the model with training dataset using fit().
Step 8: Evaluate the model with test dataset using evaluate method.
Step 9: By using the trained model make predictions on new data or compare
prediction with ground truth.
CODE:
import os
from keras.activations import sigmoid
from keras.losses import mean_squared_error
from keras.saving.saved_model.load import metrics
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
import numpy as np
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
AIM:
To implement a feed-forward network in tensorflow/ keras.
ALGORITHM:
Step 1: Import all necessary packages.
Step 2: Load the dataset from either packages or generate user data.
Step 3: Split the dataset into features(x) and target(y).
Step 4: Again split the dataset into training data(train_x,train_y) and testing
data(test_x,test_y) using traintestsplit().
Step 5: Define the model by creating sequential model with Dense layer and
activation function for feed forward network.
- Input Layer: Set the values of the input layer to the values of the input data.
- Hidden Layers: For each hidden layer, compute the weighted sum of inputs
and apply the activation function to produce the output of the layer.
- Output Layer: Compute the weighted sum of inputs for the output layer and
apply the activation function.
Step 6: Compile the model with optimizer, loss function, and metrices.
Step 7: Train the model with training dataset using fit().
Step 8: Evaluate the model with test dataset using evaluate method.
Step 9: By using the trained model make predictions on new data or compare
prediction with ground truth.
CODE:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense
import numpy as np
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
# Load and preprocess the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# Build the CNN model
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
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, activation='softmax'))
CCS355 NNDL MCE/CSE
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
Step 13: Evaluate the model with test dataset using evaluate method.By using
the trained model make predictions on new data or compare prediction with
ground truth
CODE:
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import matplotlib.pyplot as plt
# Load and preprocess the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# Build the CNN model with hyperparameter tuning
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
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(128, (3, 3), activation='relu')) # Increased filters
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu')) # Increased units
model.add(layers.Dense(10, activation='softmax'))
# Compile the model with fine-tuned hyperparameters
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.applications import VGG16
from tensorflow.keras.utils import to_categorical
# Load CIFAR-10 dataset and normalize pixel values
CCS355 NNDL MCE/CSE
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CCS355 NNDL MCE/CSE
CODE:
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.applications import VGG16
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import layers, models, optimizers
# Load the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize pixel values to be between 0 and 1
x_train, x_test = x_train / 255.0, x_test / 255.0
# Load the pretrained VGG16 model without the top (fully connected) layers
base_model = VGG16(weights='imagenet', include_top=False,input_shape=(32, 32,3))
# Freeze the weights of the pretrained layers
for layer in base_model.layers:
layer.trainable = False
# Create your own model by adding custom top layers
model = models.Sequential()
model.add(base_model)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(10, activation='softmax')) # CIFAR-10 has 10 classes
# Compile the model
model.compile(optimizer=optimizers.Adam(lr=1e-4),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Display the model architecture
model.summary()
# Set up data generator with validation split
datagen = ImageDataGenerator(validation_split=0.2) # 20% of data for validation
batch_size = 32
# Use 'flow' method for image data augmentation
train_generator = datagen.flow(x_train, y_train, batch_size=batch_size,
subset='training')
validation_generator = datagen.flow(x_train, y_train, batch_size=batch_size,
subset='validation')
# Train the model
epochs = 10 # Adjust the number of epochs based on your needs
history = model.fit(train_generator,
steps_per_epoch=len(train_generator),
epochs=epochs,
validation_data=validation_generator,
validation_steps=len(validation_generator))
# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_acc * 100:.2f}%')
CCS355 NNDL MCE/CSE
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
CCS355 NNDL MCE/CSE
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Hyperparameters
vocab_size = 1000
embedding_dim = 16
max_length = 10
trunc_type = 'post'
padding_type = 'post'
oov_token = '<OOV>'
epochs = 10
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, LSTM, RepeatVector, TimeDistributed
from tensorflow.keras.models import Model
# Hyperparameters
latent_dim = 2 # Dimensionality of the latent space
# Encoder
encoder = LSTM(latent_dim, activation='relu', return_sequences=False)(input_sequence)
# Repeat the encoded representation for each time step in the input sequence
encoded_sequence = RepeatVector(10)(encoder)
# Decoder
decoder = LSTM(1, activation='relu', return_sequences=True)(encoded_sequence)
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
a. After training, you can generate new images by sampling random noise
vectors from a normal distribution and passing them through the
trained generator network.
Step 7: Evaluation:
a. Evaluate the generated images using metrics like Inception Score,
Frechet Inception Distance, or visual inspection by humans to assess
the quality and diversity of the generated images.
Step 8:
CODE:
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers
import numpy as np
import matplotlib.pyplot as plt
# Set up models
input_shape = (100,)
generator = build_generator(input_shape)
discriminator = build_discriminator((28, 28, 1))
gan = build_gan(generator, discriminator)
# Compile models
discriminator.compile(loss='binary_crossentropy',
optimizer=optimizers.Adam(learning_rate=0.0002), metrics=['accuracy'])
gan.compile(loss='binary_crossentropy', optimizer=optimizers.Adam(learning_rate=0.0002))
# Training loop
epochs = 100
batch_size = 64
num_batches = train_images.shape[0] // batch_size
# Train Generator
noise = np.random.normal(0, 1, (batch_size, 100))
y = np.ones((batch_size, 1))
g_loss = gan.train_on_batch(noise, y)
# Generate images
noise = np.random.normal(0, 1, (10, 100))
generated_images = generator.predict(noise)
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.models import Model
from keras.layers import Input, Embedding, Flatten, Dot, Dense
from keras.callbacks import EarlyStopping
SAMPLE OUTPUT:
CCS355 NNDL MCE/CSE
CODE:
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
ALGORITHM:
CODE:
import numpy as np
def reset(self):
self.state = np.random.choice(self.vocab, size=self.window_size).tolist()
return self.state
def calculate_reward(self):
context = ''.join(self.state)
next_char_index = self.text.find(context)
if next_char_index != -1 and next_char_index + len(context) < len(self.text) - 1:
next_char = self.text[next_char_index + len(context)]
return 1 if next_char in self.state else -1
else:
return -1
return np.random.choice(self.env.vocab)
else:
return max(self.env.vocab, key=lambda action: self.q_table.get((tuple(state), action),
0))
SAMPLE OUTPUT: