Deep Learning Lab
Deep Learning Lab
Python is a widely used high-level programming language. To write and execute code in
python, we first need to install Python on our system.
Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to use or
need. There are different versions of Python 2 and Python 3 available.
On the web browser, in the official site of python (www.python.org), move to the Download
for Windows section.
All the available versions of Python will be listed. Select the version required by you and
click on Download. Let suppose, we chose the Python 3.9.1 version.
On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating
system and download the instlaller. Let suppose, we select the Windows installer(64 bits).
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
New.
To ensure if Python is succesfully installed on your system. Follow the given steps −
Open the command prompt.
Type ‘python’ and press enter.
The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.
Pip is a powerful package management system for Python software packages. Thus, make
sure that you have it installed.
The msys2 documentation gives an overview of the supported environments in msys2 and a
comparison of MSVCRT and UCRT. The main difference between upstream msys2 and
rtools4 is that our toolchains and libraries are configured for static linking, whereas upstream
msys2 prefers dynamic linking. The references at the bottom of this document contain more
information.
Rtools 4.0 has been maintained by Jeroen Ooms. Older editions were put together by
Prof. Brian Ripley and Duncan Murdoch.
Installing Rtools
Note that Rtools is only needed build R packages with C/C++/Fortran code from source. By
default, R for Windows installs the precompiled “binary packages” from CRAN, for which
you do not need Rtools.
Note for RStudio users: you need at least RStudio version 1.2.5042 to work with rtools4.
Putting Rtools on the PATH
After installation is complete, you need to perform one more step to be able to compile R
packages: we put the location of the Rtools make utilities (bash, make, etc) on the PATH. The
easiest way to do so is by creating a text file .Renviron in your Documents folder which
contains the following line:
PATH="${RTOOLS40_HOME}\usr\bin;${PATH}"
You can do this with a text editor, or from R like so (note that in R code you need to escape
backslashes):
Restart R, and verify that make can be found, which should show the path to your Rtools
installation.
Sys.which("make")
## "C:\\rtools40\\usr\\bin\\make.exe"
If this succeeds, you’re good to go! See the links below to learn more about rtools4 and the
Windows build infrastructure.
Certainly, here are some simple points about the study and usage of R, commonly referred to
as R language or R tool:
Statistical and Data Analysis: R is a programming language and environment for
statistical computing and data analysis.
Open Source: R is open source and freely available, which means you can download
and use it without cost.
Rich Ecosystem: R has a rich ecosystem of packages and libraries for various data
analysis and visualization tasks.
Data Visualization: R is known for its powerful data visualization capabilities, with
packages like ggplot2 for creating highly customizable graphs and charts.
Data Manipulation: R provides tools for data manipulation and transformation,
making it suitable for cleaning and preparing data.
Statistics and Machine Learning: R is widely used for statistical analysis and machine
learning tasks, with packages like stats and caret.
Statistical Modeling: R supports various statistical modeling techniques, including
linear and nonlinear modeling, time-series analysis, and more.
R Markdown: R Markdown allows you to create dynamic documents that combine R
code, visualizations, and narrative text.
Community Support:R has an active and supportive user community, with forums and
resources for learning and problem-solving.
Cross-Platform Compatibility: R runs on multiple platforms, including Windows,
macOS, and Linux.
EX NO :2 Implement a classifier for the sales data.
AIM:
To implement a classifier for the sales data. Read the training data from a .CSV file.
PROCEDURE:
Step 1:download packages from the RTools website and follow the installation instructions.
RTools is typically used for building and installing R packages that include compiled
code.
Step 2:Set Up Your Working Directory to Create a folder where you will store your R scripts
Step 4:Run Your Script using a Rtool console and use the source() function to run your script
Step 5:Review Output and Check the output in the R console or RStudio console.
PROGRAM:
# Attach objects in the database; can be accessed by simply giving their names
attach(icecream)
# All packages that are used on this study have been installed; eg install.packages("dplyr") for
dplyr package to investigate data
# Load packages dplyr and ggplot2 for investigating and visualising the data respectively
library(dplyr)
library(ggplot2)
# Just glimpse of how the data looks like and check the classes of the variables
glimpse(icecream)
class(icecream$icecream_sales)
class(icecream$price)
class(icecream$income)
class(icecream$temperature)
class(icecream$season)
class(icecream$country)
#Analysis for the sales; Density plot of sales, box plot of sales per country, box plot of sales
per season
ggplot(icecream, aes(x=icecream_sales)) + geom_density() + xlab("Ice cream Sales") +
ylab("Density") + ggtitle("Density plot of Ice cream Sales")
ggplot(data = icecream, aes(x = country, y = icecream_sales)) + geom_boxplot() +
xlab("Country") + ylab("Ice cream sales") + ggtitle("Box plot of ice cream sales")
ggplot(data = icecream, aes(x = season, y = icecream_sales)) + geom_boxplot() +
xlab("Season") + ylab("Ice cream sales") + ggtitle("Box plot of ice cream sales")
#Analysis for the Income; Density plot of Income, box plot of Income per country, box plot
of Income per season
ggplot(icecream, aes(x=income)) + geom_density() + xlab("Income") + ylab("Density") +
ggtitle("Density plot of Income")
ggplot(data = icecream, aes(x = country, y = income)) + geom_boxplot() + xlab("Season") +
ylab("Income") + ggtitle("Box plot of Income per Season")
ggplot(data = icecream, aes(x = season, y = income)) + geom_boxplot() + xlab("Season") +
ylab("Income") + ggtitle("Box plot of Income per Season")
#Analysis for the Price; Density plot of Price, box plot of Price per country
ggplot(icecream, aes(x=price)) + geom_density() + xlab("Price") + ylab("Density") +
ggtitle("Density plot of Price")
ggplot(data = icecream, aes(x = country, y = price)) + geom_boxplot() + xlab("Country") +
ylab("Price") + ggtitle("Box plot of Price")
ggplot(data = na.omit(icecream),
aes(x = country, y= icecream_sales, colour=country)) +
geom_boxplot() + xlab("Country") +
ylab("Ice ceam sales") +
ggtitle("Box plot of ice cream sales") +
stat_summary(fun.y=mean, colour="darkred", geom="point", shape=1, size=3)
#Collection of a simple random sample of size 100 from the icecream dataset, which is
assigned to samp1
sales <- icecream$icecream_sales
samp1 <- sample(sales, 100)
mean(samp1) # mean of the sample distribution for sales
glimpse(samp1)
hist(samp1)
# For use of inference(), I have installed "statsr" package with the following command;
install.packages("statsr")
library(statsr)
inference(y= icecream_sales, x = country, data = icecream,
statistic = c("mean"),
type = c("ht"),
null = 0,
alternative = c("twosided"), method = c("theoretical"), conf_level = 0.95,
order = c("A","B"))
#Computation of the correlation coefficient between pairs of our numerical variables, this
returns the correlation matrix
icecream %>%
select(icecream_sales, income, price, temperature) %>%
cor() %>%
knitr::kable(
digits = 3,
caption = "Correlations between icecream_sales, income, price and temperature", booktabs
= TRUE
)
#Visualize the association between the outcome variable with each of the explanatory
variables
library(ggplot2)
icecream <- read.csv("http://bit.ly/2OMHgFi")
p1 <- ggplot(icecream, aes(x = income, y = icecream_sales)) +
geom_point() +
labs(x = "Income (in £)", y = "Ice cream sales (in £)", title = "Relationship between ice
cream sales and income") +
geom_smooth(method = "lm", se = FALSE)
p2 <- ggplot(icecream, aes(x = price, y = icecream_sales)) +
geom_point() +
labs(x = "Price (in £)", y = "Ice cream sales (in £)", title = "Relationship between ice cream
sales and price") +
geom_smooth(method = "lm", se = FALSE)
p3 <- ggplot(icecream, aes(x = temperature, y = icecream_sales)) +
geom_point() +
labs(x = "Temperature (in Celsius °C)", y = "Ice cream sales (in £)", title = "Relationship
between ice cream sales and temperature") +
geom_smooth(method = "lm", se = FALSE)
library(gridExtra)
grid.arrange(p1, p2, p3)
# Scatter plot; relationship between temperature and ice cream sales by country, adding x, y
axis labels, title and a different regression line for each country
ggplot(data = icecream, aes(x = temperature, y = icecream_sales, colour = country)) +
geom_point() +
xlab("Temperature (in °C)") + ylab("Sales of ice cream (in £)") +
ggtitle("Ice cream Sales vs Temperature by Country") +
geom_smooth(method = "lm", se = FALSE)
# Scatter plot; relationship between income and ice cream sales by country, adding x, y axis
labels, title and a different regression line for each country
ggplot(data = icecream, aes(x = income, y = icecream_sales, colour = country)) +
geom_point() +
xlab("Income (in £)") + ylab("Sales of ice cream (£)") +
ggtitle("Ice cream Sales vs Income by Country") +
geom_smooth(method = "lm", se = FALSE)
# Scatter plot; relationship between price and ice cream sales by country, adding x, y axis
labels, title and a different regression line for each country
ggplot(data = icecream, aes(x = price, y = icecream_sales, colour = country)) + geom_point()
+
xlab("Price (in £)") + ylab("Sales of ice cream (in £)") +
ggtitle("Ice cream Sales vs Price by Country") +
geom_smooth(method = "lm", se = FALSE)
#Independent residuals
plot(Sales_model$residuals)
# Prediction
pred <- data.frame(income = 30000, price = 3, temperature = 23, country = "A", season =
"Spring")
predict(Sales_model, pred, interval = "prediction", level = 0.95)
OUTPUT:
RESULT:
Thus, the program to implement a classifier for the sales data are successfully
executed and the output was verified.
EX NO :3 Develop a predictive model for predicting house prices.
AIM:
PROCEDURE:
Step 1:download packages from the RTools website and follow the installation instructions.
RTools is typically used for building and installing R packages that include compiled
code.
Step 2:Set Up Your Working Directory to Create a folder where you will store your R scripts
Step 4:Run Your Script using a Rtool console and use the source() function to run your script
Step 5:Review Output and Check the output in the R console or RStudio console.
PROGRAM:
RESULT:
Thus, the program to develop a predictive model for predicting house prices are
successfully executed and the output was verified.
EX NO :4 Implement the FIND-S algorithm. Verify that it successfully
produces the trace in for the Enjoy sport example.
AIM:
Implement and demonstrate the FIND-S algorithm for finding the most specific
hypothesis based on a given set of training data samples. Read the training data from
a .CSV file.
PROCEDURE:
Step 1: Install Jupyter Notebook you can do so by running one of the following commands in
your command prompt or terminal:
Step 3: Access Jupyter Notebook through Your web browser will open, displaying the
Jupyter Notebook dashboard.
Step 4: To navigate Your .ipynb File In the Jupyter Notebook dashboard, click on the folder
containing your .ipynb file.
Step 5: Open Your .ipynb File Click on the .ipynb file you want to run. It will open in a new
tab.
Step 6: Running Cells in Jupyter Notebooks consist of cells. Click on a code cell to select it.
Press Shift + Enter on your keyboard or click the "Run" button in the toolbar
Step 7: Close Jupyter Notebook When you're done, you can close the Jupyter Notebook tab
in your web browser.
Step 8: Shut Down the Jupyter Notebook Server to Go back the command prompt or
terminal where you started Jupyter Notebook and press Ctrl + C to shut down the Jupyter
Notebook server.
PROGRAM:
FindS.ipynb
import csv
hypo=[]
data=[]
with open('SP.csv') as csv_file:
fd = csv.reader(csv_file)
print("\nThe given training examples are:")
for line in fd:
print(line)
if line[-1]== "Yes":
data.append(line)
print("\nThe positive examples are: playing sports");
for x in data:
print(x);
row= len(data);
col=len(data[0]);
for j in range(col):
hypo.append(data[0][j]);
for i in range(row):
for j in range(col):
if hypo[j]!=data[i][j]:
hypo[j]='?'
print("\nThe maximally specific Find-s hypothesis for the given training examples
is");
print(hypo)
OUTPUT:
The given training examples are:
['Sky', 'Airtemp', 'Humidity', 'Wind', 'Water', 'Forecast', 'WaterSport']
['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same', 'Yes']
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same', 'Yes']
['Cloudy', 'Cold', 'High', 'Strong', 'Warm', 'Change', 'No']
['Sunny', 'Warm', 'High', 'Strong', 'Cool', 'Change', 'Yes']
The maximally specific Find-s hypothesis for the given training examples is
['Sunny', 'Warm', '?', 'Strong', '?', '?', 'Yes']
RESULT:
Thus, the program to implement and demonstrate the FIND-S algorithm for finding
the most specific hypothesis are successfully executed and the output was verified.
AIM:
To implement a decision tree algorithm for sales prediction/ classification in retail sector.
PROCEDURE:
Step 1:download packages from the RTools website and follow the installation instructions.
RTools is typically used for building and installing R packages that include compiled
code.
Step 2:Set Up Your Working Directory to Create a folder where you will store your R scripts
Step 4:Run Your Script using a Rtool console and use the source() function to run your script
Step 5:Review Output and Check the output in the R console or RStudio console.
PROGRAM:
install.packages("rpart.plot")
library(rpart)
library(rpart.plot)
# Assume 'mpg' as the target variable (sales prediction) and 'cyl', 'hp', and 'wt' as features
# You should replace these variables with your actual dataset columns
target_variable <- "mpg"
feature_variables <- c("cyl", "hp", "wt")
# Make predictions (you can replace the newdata with your test data)
predictions <- predict(tree_model, newdata = mtcars, type = "class")
OUTPUT
RESULT:
Thus, the program to implement a decision tree algorithm for sales prediction/
classification in retail sector are successfully executed and the output was verified.
EX NO :6 Implement back propagation algorithm for stock prices
prediction
AIM:
PROCEDURE:
Step 1:download packages from the RTools website and follow the installation instructions.
RTools is typically used for building and installing R packages that include compiled
code.
Step 2:Set Up Your Working Directory to Create a folder where you will store your R scripts
Step 4:Run Your Script using a Rtool console and use the source() function to run your script
Step 5:Review Output and Check the output in the R console or RStudio console.
PROGRAM:
# Generate predictions
predictions <- predict(model, data)
RESULT:
Thus, the program to implement back propagation algorithm for stock prices
prediction are successfully executed and the output was verified.
AIM:
PROCEDURE:
Step 1: Install Jupyter Notebook you can do so by running one of the following commands in
your command prompt or terminal:
Step 3: Access Jupyter Notebook through Your web browser will open, displaying the
Jupyter Notebook dashboard.
Step 4: To navigate Your .ipynb File In the Jupyter Notebook dashboard, click on the folder
containing your .ipynb file.
Step 5: Open Your .ipynb File Click on the .ipynb file you want to run. It will open in a new
tab.
Step 6: Running Cells in Jupyter Notebooks consist of cells. Click on a code cell to select it.
Press Shift + Enter on your keyboard or click the "Run" button in the toolbar
Step 7: Close Jupyter Notebook When you're done, you can close the Jupyter Notebook tab
in your web browser.
Step 8: Shut Down the Jupyter Notebook Server to Go back the command prompt or
terminal where you started Jupyter Notebook and press Ctrl + C to shut down the Jupyter
Notebook server.
PROGRAM:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.datasets import load_breast_cancer
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
n_clusters = 2
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
df['PCA1'] = X_pca[:, 0]
df['PCA2'] = X_pca[:, 1]
RESULT:
Thus, the program to implement clustering algorithm for insurance fraud are
successfully executed and the output was verified.
EX.NO:8 Implement clustering algorithm for identifying cancerous data
AIM:
To implement clustering algorithm for identifying cancerous data Read the training data
PROCEDURE:
Step 1: Install Jupyter Notebook you can do so by running one of the following commands in
your command prompt or terminal:
Step 3: Access Jupyter Notebook through Your web browser will open, displaying the
Jupyter Notebook dashboard.
Step 4: To navigate Your .ipynb File In the Jupyter Notebook dashboard, click on the folder
containing your .ipynb file.
Step 5: Open Your .ipynb File Click on the .ipynb file you want to run. It will open in a new
tab.
Step 6: Running Cells in Jupyter Notebooks consist of cells. Click on a code cell to select it.
Press Shift + Enter on your keyboard or click the "Run" button in the toolbar
Step 7: Close Jupyter Notebook When you're done, you can close the Jupyter Notebook tab
in your web browser.
Step 8: Shut Down the Jupyter Notebook Server to Go back the command prompt or
terminal where you started Jupyter Notebook and press Ctrl + C to shut down the Jupyter
Notebook server.
PROGRAM:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.datasets import load_breast_cancer
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
n_clusters = 2
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
df['PCA1'] = X_pca[:, 0]
df['PCA2'] = X_pca[:, 1]
plt.scatter(df[df['Cluster'] == 0]['PCA1'], df[df['Cluster'] == 0]['PCA2'], label='Cluster 0')
plt.scatter(df[df['Cluster'] == 1]['PCA1'], df[df['Cluster'] == 1]['PCA2'], label='Cluster 1')
plt.legend()
plt.xlabel('PCA1')
plt.ylabel('PCA2')
plt.title('K-Means Clustering')
plt.show()
OUTPUT:
RESULT:
Thus, the program to implement clustering algorithm for identifying cancerous are
successfully executed and the output was verified.
EX.NO: 9 Apply reinforcement learning and develop a game of your own
AIM:
To apply reinforcement learning and develop a game of your own
PROCEDURE:
Step 1: Install Jupyter Notebook you can do so by running one of the following commands in
your command prompt or terminal:
Step 3: Access Jupyter Notebook through Your web browser will open, displaying the
Jupyter Notebook dashboard.
Step 4: To navigate Your .ipynb File In the Jupyter Notebook dashboard, click on the folder
containing your .ipynb file.
Step 5: Open Your .ipynb File Click on the .ipynb file you want to run. It will open in a new
tab.
Step 6: Running Cells in Jupyter Notebooks consist of cells. Click on a code cell to select it.
Press Shift + Enter on your keyboard or click the "Run" button in the toolbar
Step 7: Close Jupyter Notebook When you're done, you can close the Jupyter Notebook tab
in your web browser.
Step 8: Shut Down the Jupyter Notebook Server to Go back the command prompt or
terminal where you started Jupyter Notebook and press Ctrl + C to shut down the Jupyter
Notebook server.
PROGRAM:
import pygame
import random
import numpy as np
# Constants
WIDTH, HEIGHT = 600, 400
FPS = 30
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
def get_possible_actions(self):
row, col = self.state
actions = ['up', 'down', 'left', 'right']
if row == 0:
actions.remove('up')
if row == self.rows - 1:
actions.remove('down')
if col == 0:
actions.remove('left')
if col == self.cols - 1:
actions.remove('right')
return actions
reward = 0
if self.state == (2, 2): # Goal state
reward = 1
elif self.state in [(1, 2), (2, 1)]: # Penalty states
reward = -1
done = False
if reward != 0:
done = True
def reset(self):
self.state = (0, 0)
return self.state
# Pygame setup
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Reinforcement Learning Game")
clock = pygame.time.Clock()
# Initialize the environment and agent
environment = GridWorld(rows=3, cols=3, start=(0, 0))
agent = QLearningAgent(actions=['up', 'down', 'left', 'right'])
# Training parameters
num_episodes = 1000
alpha = 0.1
gamma = 0.9
epsilon = 0.1
state = next_state
pygame.display.flip()
clock.tick(FPS)
# Quit Pygame
pygame.quit()
OUTPUT:
RESULT:
Thus, the program to apply reinforcement learning and develop a game of your own
are successfully executed and the output was verified.
EX.NO: 10 Develop a traffic signal control system using reinforcement
learning technique
AIM:
PROCEDURE:
Step 1:download packages from the RTools website and follow the installation instructions.
RTools is typically used for building and installing R packages that include compiled
code.
Step 2:Set Up Your Working Directory to Create a folder where you will store your R scripts
Step 4:Run Your Script using a Rtool console and use the source() function to run your script
Step 5:Review Output and Check the output in the R console or RStudio console.
PROGRAM:
library(ggplot2)
# Define a simple traffic simulation environment
# In a real-world scenario, you would need a more complex environment.
simulate_traffic <- function(num_time_steps) {
traffic_data <- data.frame(
time_step = 1:num_time_steps,
road_1_traffic = sample(0:30, num_time_steps, replace = TRUE),
road_2_traffic = sample(0:40, num_time_steps, replace = TRUE)
)
return(traffic_data)
}
for (i in 1:nrow(traffic_data)) {
if (traffic_data$road_1_traffic[i] < 20 && traffic_data$road_2_traffic[i] < 30) {
traffic_data$signal_state[i] <- "Green"
}
}
return(traffic_data)
}
RESULT:
Thus, the program to develop a traffic signal control system using reinforcement
learning technique are successfully executed and the output was verified.