I define a method called dist, to calculate the distance between two points which I does it correctly when directly using the method.
However, when I get a function to call it to calculate the distance between two points, I get
UnboundLocalError: local variable 'minkowski_distance' referenced before assignment
edit
sorry, I just realised, this function does work. However I have another method calling it that doesn't. I put the last method at the bottom
This is the method:
class MinkowskiDistance(Distance):
def __init__(self, dist_funct_name_str = 'Minkowski distance', p=2):
self.p = p
def dist(self, obj_a, obj_b):
distance_to_power_p=0
p=self.p
for i in range(len(obj_a)):
distance_to_power_p += abs((obj_a[i]-obj_b[i]))**(p)
minkowski_distance = (distance_to_power_p)**(1/p)
return minkowski_distance
and this is the function:
(it basically splits the tuples x and y into their number and string components and calculates the distance between the numeric part of x and y and then the distance between the string parts, then adds them.
def total_dist(x, y, p=2, q=2):
jacard = QGramDistance(q=q)
minkowski = MinkowskiDistance(p=p)
x_num = []
x_str = []
y_num = []
y_str = []
#I am spliting each vector into its numerical parts and its string parts so that the distances
#of each part can be found, then summed together.
for i in range(len(x)):
if type(x[i]) == float or type(x[i]) == int:
x_num.append(x[i])
y_num.append(y[i])
else:
x_str.append(x[i])
y_str.append(y[i])
num_dist = minkowski.dist(x_num,y_num)
str_dist = I find using some more steps
#I am simply adding the two types of distance to get the total distance:
return num_dist + str_dist
class NearestNeighbourClustering(Clustering):
def __init__(self, data_file,
clust_algo_name_str='', strip_header = "no", remove = -1):
self.data_file= data_file
self.header_strip = strip_header
self.remove_column = remove
def run_clustering(self, max_dist, p=2, q=2):
K = {}
#dictionary of clusters
data_points = self.read_data_file()
K[0]=[data_points[0]]
k=0
#I added the first point in the data to the 0th cluster
#k = number of clusters minus 1
n = len(data_points)
for i in range(1,n):
data_point_in_a_cluster = "no"
for c in range(k+1):
distances_from_i = [total_dist(data_points[i],K[c][j], p=p, q=q) for j in range(len(K[c]))]
d = min(distances_from_i)
if d <= max_dist:
K[c].append(data_points[i])
data_point_in_a_cluster = "yes"
if data_point_in_a_cluster == "no":
k += 1
K[k]=[data_points[i]]
return K