0% found this document useful (0 votes)
57 views15 pages

Deep Learning with TensorFlow Lab Manual

The document outlines 10 experiments using deep learning and TensorFlow: [1] Implementing a multilayer perceptron for MNIST digit classification; [2] Designing a neural network for binary IMDB movie review classification; [3] Designing a neural network for multi-class Reuters news classification; [4] Designing a neural network for Boston housing price prediction; [5] Building a CNN for MNIST digit classification; [6] Building a CNN for image classification; [7] Using a pre-trained CNN for image classification; [8] Implementing one-hot encoding; [9] Implementing word embeddings; [10] Implementing an RNN for IMDB classification. Code snippets are provided for experiments 1, 2
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)
57 views15 pages

Deep Learning with TensorFlow Lab Manual

The document outlines 10 experiments using deep learning and TensorFlow: [1] Implementing a multilayer perceptron for MNIST digit classification; [2] Designing a neural network for binary IMDB movie review classification; [3] Designing a neural network for multi-class Reuters news classification; [4] Designing a neural network for Boston housing price prediction; [5] Building a CNN for MNIST digit classification; [6] Building a CNN for image classification; [7] Using a pre-trained CNN for image classification; [8] Implementing one-hot encoding; [9] Implementing word embeddings; [10] Implementing an RNN for IMDB classification. Code snippets are provided for experiments 1, 2
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

Deep learning With Tensor Flow Lab Manual

DEPARTMENT OF
Computer Science And Engineering
Artificial Intelligence And Data Science

III B Tech II Sem

DEEP LEARNING WITH TENSORFLOW

PITM [Link]
Deep learning With Tensor Flow Lab Manual

List of Experiments:

1. Implement multilayer perceptron algorithm for MNIST Hand written Digit Classification.

2. Design a neural network for classifying movie reviews (Binary Classification) using IMDB
dataset.

3. Design a neural Network for classifying news wires (Multi class classification) using Reuters
dataset.

4. Design a neural network for predicting house prices using Boston Housing Price dataset.

5. Build a Convolution Neural Network for MNIST Hand written Digit Classification.

6. Build a Convolution Neural Network for simple image (dogs and Cats) Classification

7. Use a pre-trained convolution neural network (VGG16) for image classification.

8. Implement one hot encoding of words or characters.

9. Implement word embeddings for IMDB dataset.

10. Implement a Recurrent Neural Network for IMDB movie review classification problem.

PITM [Link]
Deep learning With Tensor Flow Lab Manual

3
[Link] multilayer perceptron algorithm for MNIST Hand written Digit Classification

import numpy as np

from tensorflow import keras

from [Link] import mnist

from [Link] import Sequential

from [Link] import Dense, Flatten

# Load and preprocess the MNIST dataset

(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize the pixel values to the range [0, 1]

x_train = x_train / 255.0

x_test = x_test / 255.0

# Flatten the images into 1D arrays

x_train = x_train.reshape((-1, 28*28))

x_test = x_test.reshape((-1, 28*28))

# Convert labels to one-hot encoding

num_classes = 10

y_train = [Link].to_categorical(y_train, num_classes)

y_test = [Link].to_categorical(y_test, num_classes)

# Define the MLP model

model = Sequential([

Dense(128, activation='relu', input_shape=(784,)),

Dense(64, activation='relu'),

Dense(10, activation='softmax')

])

PITM [Link]
Deep learning With Tensor Flow Lab Manual

# Compile the model


4
[Link](optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Train the model

[Link](x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)

# Evaluate the model

test_loss, test_acc = [Link](x_test, y_test)

print(f'Test accuracy: {test_acc}')

[Link] a neural network for classifying movie reviews (Binary Classification) using IMDB dataset.

from [Link] import Sequential

from [Link] import Embedding, LSTM, Dense

vocab_size = 10000 # Assuming vocabulary size

embedding_dim = 128

max_length = 200 # Maximum length of input sequences

model = Sequential([

Embedding(vocab_size, embedding_dim, input_length=max_length),

LSTM(128),

Dense(1, activation='sigmoid')

])

[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

[Link](X_train, y_train, epochs=5, batch_size=32, validation_data=(X_val, y_val))

loss, accuracy = [Link](X_test, y_test)

print("Test Accuracy:", accuracy)

[Link] a neural Network for classifying news wires (Multi class classification) using Reuters dataset.

PITM [Link]
Deep learning With Tensor Flow Lab Manual

import numpy as np
5
from [Link] import reuters

from [Link] import Sequential

from [Link] import Dense, Dropout, Activation

from [Link] import to_categorical

# Load Reuters dataset

(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=10000)

# Pad sequences to a fixed length

from [Link] import pad_sequences

maxlen = 200

x_train = pad_sequences(x_train, maxlen=maxlen)

x_test = pad_sequences(x_test, maxlen=maxlen)

# Convert labels to one-hot encoding

num_classes = [Link](y_train) + 1

y_train = to_categorical(y_train, num_classes)

y_test = to_categorical(y_test, num_classes)

# Define model

model = Sequential()

[Link](Dense(512, input_shape=(maxlen,)))

[Link](Activation('relu'))

[Link](Dropout(0.5))

[Link](Dense(num_classes))

[Link](Activation('softmax'))

# Compile model

[Link](loss='categorical_crossentropy',

optimizer='adam',

PITM [Link]
Deep learning With Tensor Flow Lab Manual

metrics=['accuracy'])
6
# Train model

batch_size = 32

epochs = 10

[Link](x_train, y_train,

batch_size=batch_size,

epochs=epochs,

validation_data=(x_test, y_test))

# Evaluate model

score = [Link](x_test, y_test, batch_size=batch_size)

print('Test loss:', score[0])

print('Test accuracy:', score[1])

4. Design a neural network for predicting house prices using Boston Housing Price dataset.

import numpy as np

import pandas as pd

from [Link] import load_boston

from sklearn.model_selection import train_test_split

from [Link] import StandardScaler

from [Link] import Sequential

from [Link] import Dense

# Load the Boston Housing Price dataset

boston = load_boston()

X = [Link]

y = [Link]

# Split the dataset into training and testing sets

PITM [Link]
Deep learning With Tensor Flow Lab Manual

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


7
# Standardize the features

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)

X_test_scaled = [Link](X_test)

# Define the neural network architecture

model = Sequential()

[Link](Dense(64, activation='relu', input_shape=(X_train.shape[1],)))

[Link](Dense(32, activation='relu'))

[Link](Dense(1))

# Compile the model

[Link](optimizer='adam', loss='mean_squared_error')

# Train the model

history = [Link](X_train_scaled, y_train, epochs=100, batch_size=32, validation_split=0.1, verbose=1)

# Evaluate the model

train_loss = [Link](X_train_scaled, y_train, verbose=0)

test_loss = [Link](X_test_scaled, y_test, verbose=0)

print(f"Train Loss: {train_loss:.4f}")

print(f"Test Loss: {test_loss:.4f}")

5. Build a Convolution Neural Network for MNIST Hand written Digit Classification.

import tensorflow as tf

from [Link] import layers, models

from [Link] import mnist

# Load the MNIST dataset

PITM [Link]
Deep learning With Tensor Flow Lab Manual

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


8
# Reshape and normalize the images

train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255

test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255

# Convert labels to categorical one-hot encoding

train_labels = [Link].to_categorical(train_labels)

test_labels = [Link].to_categorical(test_labels)

# Define the CNN architecture

model = [Link]()

[Link](layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))

[Link](layers.MaxPooling2D((2, 2)))

[Link](layers.Conv2D(64, (3, 3), activation='relu'))

[Link](layers.MaxPooling2D((2, 2)))

[Link](layers.Conv2D(64, (3, 3), activation='relu'))

[Link]([Link]())

[Link]([Link](64, activation='relu'))

[Link]([Link](10, activation='softmax'))

# Compile the model

[Link](optimizer='adam',

loss='categorical_crossentropy',

metrics=['accuracy'])

# Train the model

[Link](train_images, train_labels, epochs=5, batch_size=64, validation_split=0.2)

# Evaluate the model on test data

test_loss, test_acc = [Link](test_images, test_labels)

print('Test accuracy:', test_acc)

PITM [Link]
Deep learning With Tensor Flow Lab Manual

9
6. Build a Convolution Neural Network for simple image (dogs and Cats) Classification

import tensorflow as tf

from [Link] import layers, models

# Define the CNN model

def create_model():

model = [Link]([

# Convolutional layer with 32 filters, kernel size 3x3, and ReLU activation function

layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),

# Max pooling layer with pool size 2x2

layers.MaxPooling2D((2, 2)),

# Convolutional layer with 64 filters, kernel size 3x3, and ReLU activation function

layers.Conv2D(64, (3, 3), activation='relu'),

# Max pooling layer with pool size 2x2

layers.MaxPooling2D((2, 2)),

# Convolutional layer with 128 filters, kernel size 3x3, and ReLU activation function

layers.Conv2D(128, (3, 3), activation='relu'),

# Max pooling layer with pool size 2x2

layers.MaxPooling2D((2, 2)),

# Convolutional layer with 128 filters, kernel size 3x3, and ReLU activation function

layers.Conv2D(128, (3, 3), activation='relu'),

# Max pooling layer with pool size 2x2

layers.MaxPooling2D((2, 2)),

# Flatten layer to convert 3D output to 1D

[Link](),

# Dense (fully connected) layer with 512 units and ReLU activation function

PITM [Link]
Deep learning With Tensor Flow Lab Manual

[Link](512, activation='relu'),
10
# Output layer with 1 unit (binary classification) and sigmoid activation function

[Link](1, activation='sigmoid')

])

# Compile the model

[Link](optimizer='adam',

loss='binary_crossentropy',

metrics=['accuracy'])

return model

# Create the CNN model

model = create_model()

# Display the model architecture

[Link]()

7. Use a pre-trained convolution neural network (VGG16) for image classification.

import numpy as np

from [Link] import VGG16

from [Link] import image

from [Link].vgg16 import preprocess_input, decode_predictions

# Load the pre-trained VGG16 model

model = VGG16(weights='imagenet')

# Load and preprocess the image

img_path = 'your_image.jpg'

img = image.load_img(img_path, target_size=(224, 224))

x = image.img_to_array(img)

PITM [Link]
Deep learning With Tensor Flow Lab Manual

x = np.expand_dims(x, axis=0)
11
x = preprocess_input(x)

# Use the model to make predictions

predictions = [Link](x)

# Decode and print the top-3 predicted classes

decoded_predictions = decode_predictions(predictions, top=3)[0]

print('Predictions:')

for i, (imagenet_id, label, score) in enumerate(decoded_predictions):

print(f"{i + 1}: {label} ({score:.2f})")

8. Implement one hot encoding of words or characters.

import numpy as np

def one_hot_encode_words(text):

words = [Link]()

unique_words = sorted(set(words))

word_to_index = {word: i for i, word in enumerate(unique_words)}

num_words = len(unique_words)

encoding = [Link]((len(words), num_words))

for i, word in enumerate(words):

encoding[i, word_to_index[word]] = 1

return encoding, unique_words

def one_hot_encode_characters(text):

characters = list(text)

unique_characters = sorted(set(characters))

char_to_index = {char: i for i, char in enumerate(unique_characters)}

num_chars = len(unique_characters)

PITM [Link]
Deep learning With Tensor Flow Lab Manual

encoding = [Link]((len(characters), num_chars))


12
for i, char in enumerate(characters):

encoding[i, char_to_index[char]] = 1

return encoding, unique_characters

# Example usage

text = "one hot encoding example"

word_encoding, unique_words = one_hot_encode_words(text)

print("Word Encoding:")

print(word_encoding)

print("Unique Words:")

print(unique_words)

char_encoding, unique_chars = one_hot_encode_characters(text)

print("\nCharacter Encoding:")

print(char_encoding)

print("Unique Characters:")

print(unique_chars)

9. Implement word embeddings for IMDB dataset.

import tensorflow as tf

from [Link] import imdb

from [Link] import pad_sequences

from [Link] import Sequential

from [Link] import Embedding, Flatten, Dense

# Load the IMDB dataset

vocab_size = 10000

max_len = 200

PITM [Link]
Deep learning With Tensor Flow Lab Manual

embedding_dim = 50
13
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)

# Pad sequences to ensure uniform length

x_train = pad_sequences(x_train, maxlen=max_len)

x_test = pad_sequences(x_test, maxlen=max_len)

# Build the model

model = Sequential()

[Link](Embedding(vocab_size, embedding_dim, input_length=max_len))

[Link](Flatten())

[Link](Dense(1, activation='sigmoid'))

[Link](optimizer='adam',

loss='binary_crossentropy',

metrics=['accuracy'])

# Train the model

history = [Link](x_train, y_train,

epochs=10,

batch_size=32,

validation_data=(x_test, y_test))

# Evaluate the model

loss, accuracy = [Link](x_test, y_test)

print("Test Accuracy:", accuracy)

10. Implement a Recurrent Neural Network for IMDB movie review classification problem.

import numpy as np

from [Link] import imdb

from [Link] import Sequential

PITM [Link]
Deep learning With Tensor Flow Lab Manual

from [Link] import Embedding, SimpleRNN, Dense


14
from [Link] import pad_sequences

# Set parameters

max_features = 10000 # Number of words to consider as features

maxlen = 500 # Cuts off reviews after this number of words

batch_size = 32

# Load data

print('Loading data...')

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)

print(len(x_train), 'train sequences')

print(len(x_test), 'test sequences')

# Preprocess data

print('Pad sequences (samples x time)')

x_train = pad_sequences(x_train, maxlen=maxlen)

x_test = pad_sequences(x_test, maxlen=maxlen)

print('x_train shape:', x_train.shape)

print('x_test shape:', x_test.shape)

# Define model

model = Sequential()

[Link](Embedding(max_features, 32)) # Embedding layer

[Link](SimpleRNN(32)) # RNN layer

[Link](Dense(1, activation='sigmoid')) # Output layer

# Compile model

[Link](optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])

# Train model

print('Training model...')

history = [Link](x_train, y_train,

PITM [Link]
Deep learning With Tensor Flow Lab Manual

epochs=10,
15
batch_size=batch_size,

validation_split=0.2)

# Evaluate model

print('Evaluating model...')

loss, accuracy = [Link](x_test, y_test, batch_size=batch_size)

print('Test loss:', loss)

print('Test accuracy:', accuracy)

PITM [Link]

You might also like