Final ML
Final ML
01
AIM:- Heuristics and search strategy for Travelling sales person problem.
SOFTWARE REQUIRED:- Python Compiler, Computers.
THEORY:-
Heuristics Search:- Heuristic search is class of method which is used in
order to search a solution space for an optimal solution for a problem. The
heuristic here uses some method to search the solution space while assessing
where in the space the solution is most likely to be and focusing the search
on that area.
Travelling Salesman Problem (TSP) : Given a set of cities and distances
between every pair of cities, the problem is to find the shortest possible route
that visits every city exactly once and returns to the starting point.
EXAMPLE :- consider the graph shown in the figure on the. A TSP tour in the
graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80.
1
ALGORITHM :-
1. Consider city 1 as the starting and ending point. Since the route is cyclic, we
can consider any point as a starting point.
2. Generate all (n-1)! permutations of cities.
3. Calculate the cost of every permutation and keep track of the minimum cost
permutation.
4. Return the permutation with minimum cost.
PROGRAM CODE:-
2
# compute current path weight
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
OUTPUT :- 80
Time complexity: O(n!) where n is the number of vertices in the graph. This
is because the algorithm uses the next_permutation function which generates
all the possible permutations of the vertex set.
Auxiliary Space: O(n) as we are using a vector to store all the vertices.
3
EXPERIMENT NO. 02
THEORY:-
N-Queens Problem: The N Queen Is The Problem Of Placing N Chess
Queens On An N*N Chessboard So That No Two Queens Attack Each Other
Hill-climbing: Hill climbing is a simple optimization algorithm used in
Artificial Intelligence (AI) to find the best possible solution for a given
problem. It belongs to the family of local search algorithms and is often used
in optimization problems where the goal is to find the best solution from a set
of possible solutions.
4
PROGRAM:-
for i in range(N):
def printBoard(board):
for i in range(N):
print(*board[i]
5
for i in range(N):
for j in range(N):
board[i][j] = value;
for i in range(N):
row = state[i]
col = i - 1;
while (col >= 0 and board[row][col] != 1) :
col -= 1
row = state[i]
col = i + 1;
while (col < N and board[row][col] != 1):
col += 1;
row = state[i] - 1
6
col = i - 1;
while (col >= 0 and row >= 0 and board[row][col] != 1) :
col-= 1;
row-= 1;
row = state[i] + 1
col = i + 1;
while (col < N and row < N and board[row][col] != 1) :
col+= 1;
row+= 1;
row = state[i] + 1
col = i - 1;
while (col >= 0 and row < N and board[row][col] != 1) :
col -= 1;
row += 1;
7
if (col < N and row >= 0 and board[row][col] == 1) :
attacking += 1;
for i in range(N):
state1[i] = state2[i];
copyState(opState, state);
generateBoard(opBoard, opState);
8
NeighbourState = [0 for _ in range(N)]
copyState(NeighbourState, state);
generateBoard(NeighbourBoard, NeighbourState);
for i in range(N):
for j in range(N):
if (j != state[i]) :
NeighbourState[i] = j;
NeighbourBoard[NeighbourState[i]][i] = 1;
NeighbourBoard[state[i]][i] = 0;
NeighbourBoard[NeighbourState[i]][i] = 0;
NeighbourState[i] = state[i];
NeighbourBoard[state[i]][i] = 1;
copyState(state, opState);
fill(board, 0);
generateBoard(board, state);
9
neighbourBoard = [[0 for _ in range(N)] for _ in range(N)]
neighbourState = [0 for _ in range(N)]
copyState(neighbourState, state);
generateBoard(neighbourBoard, neighbourState);
while True:
copyState(state, neighbourState);
generateBoard(board, state);
getNeighbour(neighbourBoard, neighbourState);
if (compareStates(state, neighbourState)) :
printBoard(board);
break;
10
board = [[0 for _ in range(N)] for _ in range(N)]
configureRandomly(board, state);
hillClimbing(board, state);
OUTPUT:-
11
EXPERIMENT NO . 03
THEORY:
Tic-tac-toe game: is a fun game played by two players. Before starting the
game, a 3x3 square grid is formed using two vertical and two horizontal lines.
The player who succeeds in placing three of their marks in a horizontal,
vertical, or diagonal row is the winner. In this study, we develop a computer
program where a player can challenge artificial intelligent heuristic approach
(opponent) to win the game. We want to prove that artificial intelligent
heuristic approach enables in giving a great performance for development of
tic-tac-toe game.
12
PROGRAM :
def sum(a, b, c ):
return a + b + c
def printBoard(xState, zState):
zero = 'X' if xState[0] else ('O' if zState[0] else 0)
one = 'X' if xState[1] else ('O' if zState[1] else 1)
two = 'X' if xState[2] else ('O' if zState[2] else 2)
three = 'X' if xState[3] else ('O' if zState[3] else 3)
four = 'X' if xState[4] else ('O' if zState[4] else 4)
five = 'X' if xState[5] else ('O' if zState[5] else 5)
six = 'X' if xState[6] else ('O' if zState[6] else 6)
seven = 'X' if xState[7] else ('O' if zState[7] else 7)
eight = 'X' if xState[8] else ('O' if zState[8] else 8)
print(f"{zero} | {one} | {two} ")
print(f"--|---|---")
print(f"{three} | {four} | {five} ")
print(f"--|---|---")
print(f"{six} | {seven} | {eight} ")
def checkWin(xState, zState):
wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4,
6]]
for win in wins:
if(sum(xState[win[0]], xState[win[1]], xState[win[2]]) == 3):
print("X Won the match")
return 1
if(sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3):
print("O Won the match")
return 0
return -1
if __name__ == "__main__":
13
xState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
zState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
turn = 1 # 1 for X and 0 for O
print("Welcome to Tic Tac Toe")
while(True):
printBoard(xState, zState)
if(turn == 1):
print("X's Chance")
value = int(input("Please enter a value: "))
xState[value] = 1
else:
print("O's Chance")
value = int(input("Please enter a value: "))
zState[value] = 1
cwin = checkWin(xState, zState)
if(cwin != -1):
print("Match over")
break turn = 1 – turn
OUTPUT:-
14
EXPERIMENT NO. 04
AIM: Describe the Sudoku game and represent the actions using Backtracking.
THEORY:
The objective is to place the digits within the grid so that each column, row,
and sub-grid contains all of the digits from 11 to 99. Each puzzle is
published with some of the boxes already filled in, and those constraints help
define the problem's difficulty level.
15
PROGRAM:
# A Backtracking program
# in Python to solve Sudoku problem
16
# in the specified column matches
# the given number.
def used_in_col(arr, col, num):
for i in range(9):
if(arr[i][col] == num):
return True
return False
17
# If there is no unassigned
# location, we are done
if(not find_empty_location(arr, l)):
return True
# consider digits 1 to 9
for num in range(1, 10):
# if looks promising
if(check_location_is_safe(arr,
row, col, num)):
# return, if success,
# ya !
if(solve_sudoku(arr)):
return True
# failure, unmake & try again
arr[row][col] = 0
18
[0, 0, 5, 2, 0, 6, 3, 0, 0]]
OUTPUT:
19
EXPERIMENT NO. 05
AIM: Sorting algorithms employing forward chaining.
THEORY:
The Forward-chaining algorithm starts from known facts, triggers all rules
whose premises are satisfied, and add their conclusion to the known facts.
This process repeats until the problem is solved
20
PROGRAM:
global facts
global is_changed
is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]
def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
if A1[0] == "plant" and ["eating",A1[1]] in facts:
assert_fact(["human",A1[1]])
print(facts)
OUTPUT:
21
EXPERIMENT NO. 06
1.SCIKIT LEARN
22
We can easily install Python by visiting the following link:
https://www.python.org/downloads/
Download the SciPy installer using the following link and then run it:
http://sourceforge.net/projects/scipy/files/scipy/0.16.1/
2.PYTORCH
PyTorch is a Torch based, Python machine learning library. The torch is a Lua
based computing framework, scripting language, and machine learning library.
Installation and Configuration :
STEP-1: Download and install Anaconda here. Select Anaconda 64-bit installer
for Windows Python 3.8.
23
STEP-2: Open Anaconda manager via Start - Anaconda3 - Anaconda PowerShell
Prompt and test your versions:
You can check your Python version by running the following command: python –-
version
You can check your Anaconda version by running the following command: conda
–-version
STEP-3: .Now, you can install PyTorch package from binaries via Conda.
3.TENSORFLOW
TensorFlow provides a JavaScript library that helps in machine learning. APIs will
help you to build and train the models.
if you want to use TensorFlow with GPU support, TensorFlow recommends using
Miniconda (installer for conda package manager) to kick things off.
curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -o
Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
24
conda deactivate
conda activate tf
You can skip this section if you only run TensorFlow on the CPU.
First install the NVIDIA GPU driver if you have not. You can use the following
command to verify it is installed.
nvidia-smi
Configure the system paths. You can do it with the following command every time
you start a new terminal after activating your conda environment.
For your convenience it is recommended that you automate it with the following
commands. The system paths will be automatically configured when you activate
this conda environment.
mkdir -p $CONDA_PREFIX/etc/conda/activate.d
echo 'CUDNN_PATH=$(dirname $(python -c "import
nvidia.cudnn;print(nvidia.cudnn.__file__)"))' >>
$CONDA_PREFIX/etc/conda/activate.d/env_vars.sh
echo 'export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/:$CUDN
N_PATH/lib' >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh
25
TensorFlow requires a recent version of pip, so upgrade your pip installation to be
sure you're running the latest version.
Note: Do not install TensorFlow with conda. It may not have the latest stable
version. pip is recommended since TensorFlow is only officially released to PyPI.
pip install tensorflow==2.12.*
4.WEKA
These machine learning algorithms help in data mining.
Step 1: Visit this website of weka using any web browser. Click on Free
Download
Step 3: Now check for the executable file in downloads in your system and run it.
26
Step 4: It will prompt confirmation to make changes to your system. Click on
Yes.
Step 8: The next screen will be of installing location so choose the drive which
will have sufficient memory space for installation. It needed a memory space of
301 MB.
Step 9: Next screen will be of choosing the Start menu folder so don’t do
anything just click on Install Button.
Step 10: After this installation process will start and will hardly take a minute to
complete the installation.
Step 11: Click on the Next button after the installation process is complete.
Step 13: Weka is successfully installed on the system and an icon is created on
the desktop.
5.KNIME
KNIME is a tool for data analytics, reporting and integration platform. Using the
data pipelining concept, it combines different components for machine learning
and data mining.
27
Installation and configuration
6.COLAB
Google Colab is a cloud service which supports Python. It will help you in building
the machine learning applications using the libraries of PyTorch, Keras,
TensorFlow, and OpenCV
After you have installed Anaconda go to your terminal and let us create an
environment called colab, but you can put the name that you like.
in my case I copy
http://localhost:9090/?token=107b5b6de7b8fe5ada010e2ed066c9f6dafc1e5674392
63c
https://colab.research.google.com/
29
Step 5: Connect to your local runtime
In Colab, click the “Connect” button and select “Connect to local runtime”.
Uninstall
7.APACHE MAHAOUT
Enter y and your Mahout will start installing. Once done, you can test it by
typing the command – mahout, and this will show you the same screen as
shown in preceding figure.
30
Setting up Mahout for Windows users
Windows users can use cygwin to setup their environment. There is one more
easy-to-use way.
Enter y and your Mahout will start installing. Once done, you can test it by typing
the command – mahout, and this will show you the same screen as shown in
preceding figure.
31
Installation and Configuration
Must create a new C# project in Visual Studio, then right-click your project, select
"Manage NuGet packages", then look for "Accord.NET" in the NuGet packages
browser. Install any libraries that you think you would need in the application you
are trying to create (i.e. Accord. MachineLearning).
9.KERAS
Keras is an open-source software library that provides a Python interface for
artificial neural networks. Keras acts as an interface for the TensorFlow library
10.RAPID MINER
Rapid Miner provides a platform for machine learning, deep learning, data
preparation, text mining, and predictive analytics. It can be used for research,
education and application development.
Change to the bin directory (within the installation directory) to locate the start
script (or batch file) for the installation.
1. For Windows, use the file rapidminer-server-installer.bat
2. For Linux, Unix, or Mac OS, use the file rapidminer-server-installer
3. As Admin, run the appropriate installer script. The RapidMiner Server
Installer window opens. This is not the RapidMiner service; it is a tool to
help you preconfigure the service.
4. In the RapidMiner Server Installer window, read the Before You
Start text and click Next when you are ready.
4. In the next window, select your installation type. You can install either locally or
you can create a configuration file used for a headless installation. If you select a
headless installation, browse to a file location for storing the resulting XML file.
Click Next.
1. Scroll to the bottom of the EULA screen, check the box to accept, and
click Next.
2. Enter or browse to the location where RapidMiner Server should be
installed. Please ensure that the folder path does not
contain + or % characters. Click Next. The RapidMiner Server
Installer License window opens.
3. From your account portal Licenses page, copy the license key to your
clipboard. (See this additional information if you need help copying your
key.)
4. Paste the key into the License window. The license registration information
updates based on the details of the entered license. Click Next.
5. Paste the key into the License window. The license registration information
updates based on the details of the entered license. Click Next.
33
EXPERIMENT NO. 07
THEORY:
In this algorithm, the data points are assigned to a cluster in such a manner
that the sum of the squared distance between the data points and centroid
would be minimum. It is to be understood that less variation within the clusters
will lead to more similar data points within same cluster.
34
PROGRAM:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
# The following code will generate the 2D, containing four blobs
# Next, make an object of KMeans along with providing number of clusters, train
the model and do the prediction as follows −
kmeans = KMeans(n_clusters=4)
kmeans.fit(X)
y_kmeans = kmeans.predict(X)
Now, with the help of following code we can plot and visualize the cluster’s
centers picked by k-means Python estimator −
35
OUTPUT:
36
EXPERIMENT NO. 08
THEROY:
37
PROGRAM :- Agglomerative Clustering
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
hierarchical_cluster = AgglomerativeClustering(n_clusters=2,
affinity='euclidean', linkage='ward')
labels = hierarchical_cluster.fit_predict(data)
plt.scatter(x, y, c=labels)
plt.show()
OUTPUT:
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
38
# randomly chosen dataset
X = np.array([[1, 2], [1, 4], [1, 0],
[4, 2], [4, 4], [4, 0]])
# Plot dendrogram
dendrogram(Z)
OUTPUT:
39
import skfuzzy as fuzz
colors = ['b', 'orange', 'g', 'r', 'c', 'm', 'y', 'k', 'Brown', 'ForestGreen']
OUTPUT:
40
EXPERIMENT NO. 09
AIM: Use an appropriate data set for building Write a program to demonstrate the
working of the decision tree based ID3 algorithm
THOERY:
A decision tree is a structure that contains
• Nodes (Rectangular / Circular shape)
• Edges(arrows)
It is built from a dataset
Each node is either used to
• Make a decision
• Or represent an outcome
41
PROGRAM:
# Import the necessary libraries
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from graphviz import Source
# Load the dataset
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
# DecisionTreeClassifier
tree_clf = DecisionTreeClassifier(criterion='entropy',
max_depth=2)
tree_clf.fit(X, y)
# Plot the decision tree graph
export_graphviz(
tree_clf,
out_file="iris_tree.dot",
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
with open("iris_tree.dot") as f:
dot_graph = f.read()
Source(dot_graph)
42
OUTPUT:
43
EXPERIMENT NO. 10
THEORY:
Artificial Neural Networks:
Artificial Neural Networks contain artificial neurons which are called units.
These units are arranged in a series of layers that together constitute the whole
Artificial Neural Network in a system.
Back propagation:
Backpropagation is the essence of neural network training. It is the method of
fine-tuning the weights of a neural network based on the error rate obtained
in the previous epoch (i.e., iteration). Proper tuning of the weights allows you
to reduce error rates and make the model reliable by increasing its
generalization.
44
PROGRAM:
import random
from math import exp
from random import seed
45
def ac vate(weights, inputs):
ac va on = weights[-1]
for i in range(len(weights)-1):
ac va on += weights[i] * inputs[i]
return ac va on
46
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
if i != len(network)-1:
for j in range(len(layer)):
error = 0.0
for neuron in network[i + 1]:
error += (neuron['weights'][j] * neuron['delta'])
errors.append(error)
else:
for j in range(len(layer)):
neuron = layer[j]
errors.append(expected[j] - neuron['output'])
for j in range(len(layer)):
neuron = layer[j]
neuron['delta'] = errors[j] * transfer_deriva ve(neuron['output'])
47
for neuron in network[i]:
for j in range(len(inputs)):
neuron['weights'][j] += l_rate * neuron['delta'] * inputs[j]
neuron['weights'][-1] += l_rate * neuron['delta']
48
dataset = [[2.7810836,2.550537003,0],
[1.465489372,2.362125076,0],
[3.396561688,4.400293529,0],
[1.38807019,1.850220317,0],
[3.06407232,3.005305973,0],
[7.627531214,2.759262235,1],
[5.332441248,2.088626775,1],
[6.922596716,1.77106367,1],
[8.675418651,-0.242068655,1],
[7.673756466,3.508563011,1]]
49
for sub in layer:
print("\n Layer[%d] Node[%d]:\n" %(i,j),sub)
j=j+1
i=i+1
OUTPUT:
50