Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import numpy as np # Sample data points data _ points = { ' P 1 ' : [ 5 . 1 , 3 .
import numpy as np
# Sample data points
datapoints
P:
P:
P:
P:
P:
P:
# Calculate Euclidean distance between two points
def euclideandistancepoint point:
return npsqrtnpsumnparraypoint nparraypoint
# Create initial distance matrix
labels listdatapoints.keys
numpoints lenlabels
distancematrix npzerosnumpoints, numpoints
for i in rangenumpoints:
for j in rangei numpoints:
distancematrixi j euclideandistancedatapointslabelsi datapointslabelsj
distancematrixj i distancematrixi j # Distance matrix is symmetric
# Display initial distance matrix
printInitial Distance Matrix:"
printdistancematrix
# Single linkage clustering and updating distance matrix
clusters label: label for label in labels
while lenclusters:
# Find the minimum distance in the current matrix
mindistance npmindistancematrixnpnonzerodistancematrix
# Find indices of the minimum distance
indices npwheredistancematrix mindistance
idx idx indices indices
# Merge the clusters by updating the distance matrix
newcluster labelsidx labelsidx
clustersnewcluster clusters.poplabelsidx clusters.poplabelsidx
# Update the distance matrix for merged clusters
for i in rangenumpoints:
if labelsi in clustersnewcluster:
for j in rangenumpoints:
if labelsj not in clustersnewcluster:
mindist mindistancematrixi j distancematrixidx j distancematrixidx j
distancematrixi j mindist
distancematrixj i mindist
# Display updated distance matrix
printf
Clusters Formed: listclusterskeys
printUpdated Distance Matrix:"
printdistancematrix
# Print the final cluster
printf
Final Cluster: listclusterskeys
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started