0% found this document useful (0 votes)
4 views6 pages

Lab Report 4

The lab report focuses on supervised learning techniques, specifically classification and regression, with the goal of training models to predict outcomes from historical data. It includes source code for various implementations, such as plotting animations and working with the MNIST dataset. The conclusion emphasizes the importance of data pre-processing and suggests exploring advanced deep learning models for improved accuracy in future experiments.

Uploaded by

sampritihaldar77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Lab Report 4

The lab report focuses on supervised learning techniques, specifically classification and regression, with the goal of training models to predict outcomes from historical data. It includes source code for various implementations, such as plotting animations and working with the MNIST dataset. The conclusion emphasizes the importance of data pre-processing and suggests exploring advanced deep learning models for improved accuracy in future experiments.

Uploaded by

sampritihaldar77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Lab Report-3

Title: Supervised Learning and Classification, Regression


Objective: The primary objective is to train a model that can accurately
predict the output for new unseen data based on the patterns learned from
historical data in classification. The objective can accurately determine a
category of a new data points belongs to.

Theory:
Supervised Learning: It is a machine learning technique that uses
labeled data to train models to predict outcomes.
Classification: Classification is a subset of supervised learning in the
process of predicting which category a new data points belongs to.
Source Code 1: from io import IncrementalNewlineDecoder
import numpy as np

import os

import sklearn

import sys

try:

%tensorflow_version 1.x

!apt update && apt install -y libpq-dev libsdl2-dev swig xorg-dev xvfb

!pip install -q -U pyvirtualdisplay gym[atari,box2d]

IS_COLAB = True

except Exception:

IS_COLAB = False

def reset_graph(seed=42):

tf.reset_default_graph()

tf.set_random_seed(seed)

np.random.seed(seed)

import matplotlib as mpl

import matplotlib.pyplot as plt

mpl.rc('axes', labelsize=14)

mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)

import matplotlib.animation as animation

mpl.rc('animation', html='jshtml')

PROJECT_ROOT_DIR = "."

CHAPTER_ID = "rl"

IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)

os.makedirs(IMAGES_PATH, exist_ok=True)

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):

path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)

print("Saving figure", fig_id)

if tight_layout:

plt.tight_layout()

plt.savefig(path, format=fig_extension, dpi=resolution)

def create_my_plot():

x = np.linspace(0, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.title("Sine Wave")

plt.xlabel("x")

plt.ylabel("sin(x)")

plt.show()

create_my_plot()

save_fig("my_plot")

Source Code 2: import gym # Import the gym library


def plot_animation(frames, repeat=False, interval=40):

def update_scene(num, frames, patch):

patch.set_data(frames[num])

return patch,

fig = plt.figure()

patch = plt.imshow(frames[0])

plt.axis('off')

anim = mpl.animation.FuncAnimation(

fig, update_scene, fargs=(frames, patch),

frames=len(frames), repeat=repeat, interval=interval)


plt.close()

return anim

# Animation Frame collection

frames = []

n_max_steps = 1000

n_change_steps = 10

# Create an instance of the environment 'CartPole-v1'

env = gym.make('CartPole-v1') # This line is added to create the environment

# Now 'env' is defined and can be used

env.seed(42) obs = env.reset()

for step in range(n_max_steps):

img = env.render(mode="rgb_array")

frames.append(img)

if step % n_change_steps == 0:

action = env.action_space.sample() # play randomly

obs, reward, done, info = env.step(action)

if done:

break

plot_animation(frames)

def plot_animation(frames, repeat=False, interval=40):

def update_scene(num, frames, patch):

patch.set_data(frames[num])

return patch,

fig = plt.figure()

patch = plt.imshow(frames[0])

plt.axis('off')

anim = mpl.animation.FuncAnimation(

fig, update_scene, fargs=(frames, patch),

frames=len(frames), repeat=repeat, interval=interval)

plt.close()

return anim

# Animation Frame collection

frames = []

n_max_steps = 1000 n_change_steps = 10


# Assuming 'env' is defined and set up

env.seed(42)

obs = env.reset()

for step in range(n_max_steps):

img = env.render(mode="rgb_array")

frames.append(img)

if step % n_change_steps == 0:

action = env.action_space.sample() # play randomly

obs, reward, done, info = env.step(action)

if done:

break

plot_animation(frames)

Source Code 3: import numpy as np


import matplotlib as mpl

import matplotlib.pyplot as plt

import matplotlib.animation as animation

# Set up matplotlib parameters

mpl.rc('axes', labelsize=14)

mpl.rc('xtick', labelsize=12)

mpl.rc('ytick', labelsize=12)

# Function to create and plot an animation from frames

def update_scene(num, frames, patch):

patch.set_data(frames[num])

return patch,

def plot_animation(frames, repeat=False, interval=40):

fig = plt.figure()

patch = plt.imshow(frames[0])

plt.axis('off')

anim = animation.FuncAnimation(

fig, update_scene, fargs=(frames, patch),

frames=len(frames), repeat=repeat, interval=interval)

plt.close()

return anim

# Generate frames for a moving sine wave


frames = []

x = np.linspace(0, 2 * np.pi, 100)

for i in range(100):

y = np.sin(x + i * 0.1) # Shift the sine wave over time

frame = np.zeros((20, 100)) # Create a frame with a black background

# Iterate through each point in the sine wave and update the frame

for j in range(len(x)):

frame[int(10 + 5 * y[j]), j] = 1 # Draw the sine wave in white

frames.append(frame)

# Create and display the animation

anim = plot_animation(frames)

anim

# Save the animation (optional)

# anim.save('sine_wave.gif', writer='imagemagick', fps=30)

# anim.save('sine_wave.mp4', writer='ffmpeg', fps=30) (Classification 1)

Source Code 4: from sklearn.datasets import fetch_openml


import numpy as np

import os

import matplotlib as mpl

import matplotlib.pyplot as plt

# Load the MNIST dataset

X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)

X = X / 255.0 # Scale the data to the range [0, 1]

def plot_digit(data):

image = data.reshape(28, 28)

plt.imshow(image, cmap=mpl.cm.binary, interpolation="nearest")

plt.axis("off")

# EXTRA

def plot_digits(instances, images_per_row=10, **options):

size = 28

images_per_row = min(len(instances), images_per_row)

images = [instance.reshape(size, size) for instance in instances]

n_rows = (len(instances)
● 1) // images_per_row + 1
row_images = []
n_empty = n_rows * images_per_row len(instances)
images.append(np.zeros((size, size * n_empty)))
for row in range(n_rows):
rimages = images[row * images_per_row: (row + 1) * images_per_row]
row_images.append(np.concatenate(rimages, axis=1))
image = np.concatenate(row_images, axis=0)
plt.imshow(image, cmap=mpl.cm.binary, **options)
plt.axis("off")
plt.figure(figsize=(9, 9))

# Where to save the figures

PROJECT_ROOT_DIR = "."

CHAPTER_ID = "classification"

IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)

os.makedirs(IMAGES_PATH, exist_ok=True)

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):

path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)

print("Saving figure", fig_id)

if tight_layout: plt.tight_layout() plt.savefig(path, format=fig_extension, dpi=resolution)

example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]

plot_digits(example_images, images_per_row=10) save_fig("more_digits_plot")

plt.show() number 2

Conclusion: This lab provided hands-on experience in implementing


unsupervised learning and Decision tree models. The experiment demonstrated
the importance of data pre-processing, model section, and performance
evaluation. Future improvements can include trying advanced deep learning
models for better accuracy.

You might also like