dl lab1
dl lab1
import tensorflow as tf
housing = fetch_california_housing()
X, y = housing.data, housing.target
# 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)
model = models.Sequential([
layers.Dense(64, activation='relu'),
model.compile(optimizer='adam', loss='mean_squared_error')
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 tensorflow as tf
# Load the IMDB dataset (train and test data are pre-split in Keras)
# Load IMDB data, with pre-processing to convert words into integers (word indices)
# Pad the sequences to ensure that all reviews have the same length
model = models.Sequential([
layers.Embedding(vocab_size, 128, input_length=maxlen), # Embedding layer for word
representation
])
model.compile(optimizer='adam',
metrics=['accuracy'])
model.summary()
verbose=2)
output:-
import tensorflow as tf
model = models.Sequential([
layers.MaxPooling2D((2, 2)),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
# Output layer with 10 units (since there are 10 classes)
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.summary()
# Plot the training and validation accuracy and loss over epochs
plt.figure(figsize=(12, 5))
# Plot Accuracy
plt.subplot(1, 2, 1)
plt.ylabel('Accuracy')
plt.legend()
# Plot Loss
plt.subplot(1, 2, 2)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
predictions = model.predict(x_test[:5])
predicted_labels = predictions.argmax(axis=1)
for i in range(5):
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
import numpy as np
import pandas as pd
import yfinance as yf
print(data.head())
data = data[['Close']]
plt.figure(figsize=(10, 6))
plt.xlabel('Date')
plt.ylabel('Price in USD')
plt.legend()
plt.show()
# Data Preprocessing
scaled_data = scaler.fit_transform(data)
# Define a function to create sequences for the RNN
time_step = 60 # We will use the last 60 days to predict the next day's price
# Reshape the input data to be compatible with LSTM (samples, time_step, features)
# Split the data into training and testing sets (80% for training and 20% for testing)
model = Sequential()
# Add LSTM layer with 50 units and return sequences to connect to another LSTM layer
model.add(LSTM(units=50, return_sequences=False))
# Fully connected layer (Dense) with 1 unit (output layer)
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
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)
plt.figure(figsize=(10, 6))
plt.xlabel('Time')
plt.legend()
plt.show()
predicted_next_day = model.predict(last_60_days)
predicted_next_day_price = scaler.inverse_transform(predicted_next_day)
output:-