0% found this document useful (0 votes)
2 views

dl lab1

The document outlines various deep learning applications using TensorFlow and Keras, including linear regression for Boston housing price prediction, binary classification of movie reviews using the IMDB dataset, CNN for classifying fashion clothing with the MNIST Fashion dataset, and RNN for predicting Google stock prices. Each section includes code snippets for data preprocessing, model building, training, and evaluation. The document serves as a comprehensive guide for implementing different neural network architectures for specific tasks.

Uploaded by

charlton.latham
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)
2 views

dl lab1

The document outlines various deep learning applications using TensorFlow and Keras, including linear regression for Boston housing price prediction, binary classification of movie reviews using the IMDB dataset, CNN for classifying fashion clothing with the MNIST Fashion dataset, and RNN for predicting Google stock prices. Each section includes code snippets for data preprocessing, model building, training, and evaluation. The document serves as a comprehensive guide for implementing different neural network architectures for specific tasks.

Uploaded by

charlton.latham
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/ 15

2.

Linear regression by using Deep Neural network: Implement Boston


housing price prediction problem by Linear regression using Deep Neural
network. Use Boston House price prediction dataset.

# Import necessary libraries

import tensorflow as tf

from tensorflow.keras import layers, models

from sklearn.datasets import fetch_california_housing

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import StandardScaler

# Fetch the California housing dataset

housing = fetch_california_housing()

X, y = housing.data, housing.target

# Split the data into training and test sets

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

# Scale the data (this is a common preprocessing step for neural networks)

scaler = StandardScaler()

X_train = scaler.fit_transform(X_train)

X_test = scaler.transform(X_test)

# Build a simple neural network model using TensorFlow/Keras

model = models.Sequential([

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

layers.Dense(64, activation='relu'),

layers.Dense(1) # Output layer for regression (no activation function)


])

# Compile the model

model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model

model.fit(X_train, y_train, epochs=20, batch_size=32, validation_split=0.2)

# Evaluate the model

test_loss = model.evaluate(X_test, y_test)

print(f'Test Loss: {test_loss}')

output:-
3. Classification using Deep neural network: Binary classification using Deep
Neural Networks Example: Classify movie reviews into positive" reviews and
"negative" reviews, just based on the text content of the reviews. Use IMDB
dataset

# Import necessary libraries

import tensorflow as tf

from tensorflow.keras import layers, models

from tensorflow.keras.datasets import imdb

from tensorflow.keras.preprocessing.sequence import pad_sequences

from sklearn.model_selection import train_test_split

# Load the IMDB dataset (train and test data are pre-split in Keras)

vocab_size = 10000 # Number of words to consider as features

maxlen = 200 # Maximum length of review (padding to ensure uniform length)

# Load IMDB data, with pre-processing to convert words into integers (word indices)

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

# Pad the sequences to ensure that all reviews have the same length

x_train = pad_sequences(x_train, maxlen=maxlen)

x_test = pad_sequences(x_test, maxlen=maxlen)

# Split the training data into training and validation datasets

x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)

# Build the model (Deep Neural Network)

model = models.Sequential([
layers.Embedding(vocab_size, 128, input_length=maxlen), # Embedding layer for word
representation

layers.GlobalAveragePooling1D(), # Global average pooling to reduce dimensionality

layers.Dense(64, activation='relu'), # Hidden layer with ReLU activation

layers.Dense(1, activation='sigmoid') # Output layer with sigmoid activation for binary


classification

])

# Compile the model

model.compile(optimizer='adam',

loss='binary_crossentropy', # Binary cross-entropy for binary classification

metrics=['accuracy'])

# Summarize the model architecture

model.summary()

# Train the model

history = model.fit(x_train, y_train,

epochs=5, # Number of epochs

batch_size=64, # Batch size

validation_data=(x_val, y_val), # Validation data

verbose=2)

# Evaluate the model on the test data

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)

print(f"Test Accuracy: {test_acc:.4f}")

# Predict on some test data

predictions = model.predict(x_test[:5]) # Test prediction on 5 examples


print("Predictions (probabilities):", predictions)

print("Predictions (binary):", (predictions > 0.5).astype("int32"))

output:-

4. Convolutional neural network (CNN): Use MNIST Fashion Dataset and


create a classifier to classify fashion clothing into categories.

# Import necessary libraries

import tensorflow as tf

from tensorflow.keras import layers, models

from tensorflow.keras.datasets import fashion_mnist

import matplotlib.pyplot as plt

# Load the Fashion MNIST dataset

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


# Normalize the images to be between 0 and 1 (divide by 255)

x_train, x_test = x_train / 255.0, x_test / 255.0

# Reshape the data to add a channel dimension for CNN (28x28x1)

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

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

# Create a Convolutional Neural Network (CNN) model

model = models.Sequential([

# First Convolutional Layer

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

layers.MaxPooling2D((2, 2)),

# Second Convolutional Layer

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

layers.MaxPooling2D((2, 2)),

# Third Convolutional Layer

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

# Flatten the 3D tensor to 1D before feeding into fully connected layers

layers.Flatten(),

# Fully connected layer with 64 units

layers.Dense(64, activation='relu'),
# Output layer with 10 units (since there are 10 classes)

layers.Dense(10, activation='softmax')

])

# Compile the model

model.compile(optimizer='adam',

loss='sparse_categorical_crossentropy',

metrics=['accuracy'])

# Summarize the model architecture

model.summary()

# Train the model

history = model.fit(x_train, y_train, epochs=5, batch_size=64, validation_split=0.2)

# Evaluate the model on the test set

test_loss, test_acc = model.evaluate(x_test, y_test)

print(f"Test Accuracy: {test_acc:.4f}")

# Plot the training and validation accuracy and loss over epochs

plt.figure(figsize=(12, 5))

# Plot Accuracy

plt.subplot(1, 2, 1)

plt.plot(history.history['accuracy'], label='Training Accuracy')

plt.plot(history.history['val_accuracy'], label='Validation Accuracy')

plt.title('Accuracy over Epochs')


plt.xlabel('Epochs')

plt.ylabel('Accuracy')

plt.legend()

# Plot Loss

plt.subplot(1, 2, 2)

plt.plot(history.history['loss'], label='Training Loss')

plt.plot(history.history['val_loss'], label='Validation Loss')

plt.title('Loss over Epochs')

plt.xlabel('Epochs')

plt.ylabel('Loss')

plt.legend()

plt.show()

# Predict on the test set

predictions = model.predict(x_test[:5])

print("Predictions (probabilities):", predictions)

# Convert predictions to class labels

predicted_labels = predictions.argmax(axis=1)

print("Predicted class labels:", predicted_labels)

# Show some sample images and their predicted labels

fig, axes = plt.subplots(1, 5, figsize=(12, 3))

for i in range(5):

axes[i].imshow(x_test[i].reshape(28, 28), cmap='gray')


axes[i].set_title(f"Pred: {predicted_labels[i]}")

axes[i].axis('off')

plt.show()

output:-
5. Recurrent neural network (RNN) Use the Google stock prices dataset and
design a time series analysis and prediction system using RNN

In terminal install

pip install yfinance

code (python shell):-


# Import necessary libraries

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import yfinance as yf

from sklearn.preprocessing import MinMaxScaler

from tensorflow.keras.models import Sequential


from tensorflow.keras.layers import Dense, LSTM

from sklearn.metrics import mean_squared_error

# Download the Google stock price data using yfinance

data = yf.download('GOOG', start='2010-01-01', end='2022-01-01')

# Display the first few rows of the data

print(data.head())

# We will use only the 'Close' prices for prediction

data = data[['Close']]

# Plot the closing prices over time

plt.figure(figsize=(10, 6))

plt.plot(data['Close'], label='Google Stock Price')

plt.title('Google Stock Price (2010-2022)')

plt.xlabel('Date')

plt.ylabel('Price in USD')

plt.legend()

plt.show()

# Data Preprocessing

# Normalize the data between 0 and 1

scaler = MinMaxScaler(feature_range=(0, 1))

scaled_data = scaler.fit_transform(data)
# Define a function to create sequences for the RNN

def create_sequences(data, time_step=60):

x_data, y_data = [], []

for i in range(time_step, len(data)):

x_data.append(data[i-time_step:i, 0]) # Features: last `time_step` days

y_data.append(data[i, 0]) # Target: price at time `i`

return np.array(x_data), np.array(y_data)

# Create sequences for training the model

time_step = 60 # We will use the last 60 days to predict the next day's price

x_data, y_data = create_sequences(scaled_data, time_step)

# Reshape the input data to be compatible with LSTM (samples, time_step, features)

x_data = x_data.reshape(x_data.shape[0], x_data.shape[1], 1)

# Split the data into training and testing sets (80% for training and 20% for testing)

train_size = int(len(x_data) * 0.8)

x_train, x_test = x_data[:train_size], x_data[train_size:]

y_train, y_test = y_data[:train_size], y_data[train_size:]

# Build the RNN model (LSTM network)

model = Sequential()

# Add LSTM layer with 50 units and return sequences to connect to another LSTM layer

model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))

model.add(LSTM(units=50, return_sequences=False))
# Fully connected layer (Dense) with 1 unit (output layer)

model.add(Dense(units=1))

# Compile the model

model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model

history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))

# Evaluate the model on the test data

test_loss = model.evaluate(x_test, y_test)

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

# Make predictions on the test data

predicted_stock_price = model.predict(x_test)

# Inverse transform the predictions and actual values back to the original scale

predicted_stock_price = scaler.inverse_transform(predicted_stock_price)

y_test_actual = scaler.inverse_transform(y_test.reshape(-1, 1))

# Calculate RMSE (Root Mean Squared Error)

rmse = np.sqrt(mean_squared_error(y_test_actual, predicted_stock_price))

print(f"Root Mean Squared Error (RMSE): {rmse}")

# Plot the actual vs predicted stock prices

plt.figure(figsize=(10, 6))

plt.plot(y_test_actual, color='blue', label='Actual Google Stock Price')


plt.plot(predicted_stock_price, color='red', label='Predicted Google Stock Price')

plt.title('Google Stock Price Prediction (Actual vs Predicted)')

plt.xlabel('Time')

plt.ylabel('Stock Price (USD)')

plt.legend()

plt.show()

# Predict the stock price for the next day

last_60_days = scaled_data[-time_step:].reshape(1, time_step, 1)

predicted_next_day = model.predict(last_60_days)

predicted_next_day_price = scaler.inverse_transform(predicted_next_day)

print(f"Predicted stock price for the next day: {predicted_next_day_price[0][0]:.2f} USD")

output:-

You might also like