我正在尝试在 python 中实现标准的 k-means 算法,但遇到了类型错误(TypeError: unsupported operand type(s) for /: 'Point' and 'int')。请帮助我理解我做错了什么。下面是我的代码:
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x=x
self.y=y
def __add__(self,right):
locx=self.x + right.x
locy=self.y + right.y
return Point(locx,locy)
def __sub__(self,right):
locx=self.x-right.x
locy=self.y-right.y
return Point(locx,locy)
def __mul__(self,right):
return self.x*right.x + self.y*right.y
def distance(self, other):
return sqrt((self.x-other.x)**2+(self.y-other.y)**2)
def __repr__(self):
return "Point(%d,%d)"%(self.x,self.y)
class Cluster(object):
def __init__(self, x, y):
self.center = Point(x, y)
self.points = []
def update(self):
temp=Point(0, 0)
#print(len(self.points))
count=0
for point in self.points:
count+=1
temp += point
print(len(self.points))
self.center = temp/count
self.points = []
def add_point(self, point):
self.points.append(point)
def compute_result(points):
points = [Point(*point) for point in points]
a = Cluster(1,0)
b = Cluster(-1,0)
a_old = []
for _ in range(10000): # max iterations
for point in points:
if point.distance(a.center) < point.distance(b.center):
# add the right point
a.add_point(point)
else:
# add the right point
b.add_point(point)
if a_old == a.points:
break
a_old = ...
a.update()
b.update()
return [(x, y)] * 2
在“类集群”中,我定义了一个“更新”方法,我正在尝试执行“self.center = temp/count”。那就是我从中得到错误的地方。错误如下:
<ipython-input-36-56b3a700600d> in update(self)
42 temp += point
43 print(len(self.points))
---> 44 self.center = temp/count
45 self.points = []
46
TypeError: unsupported operand type(s) for /: 'Point' and 'int'