为什么显示 AttributeError 错误:'k_means' 对象没有属性 'k'?我相信 self.k = k 行(第 15 行)初始化了属性 k。
这是我关注的一个在线示例,我在 Python 3 中使用 Google colaboratory。
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import numpy as np
x = np.array([[1,2],[3,4],[1,3]])
plt.scatter(x[:,0],x[:,1],s=150)
plt.show()
color = 10*["g.","r.","c.","b.","k."]
class kmeans():
def __init__(self, k = 2, tol = .001, max_iteration = 200):
self.k = k
self.tol = tol
self.iter = max_iteration
def fit(self,data):
self.centroids = {}
for i in range(self.k):
self.centroids[i] = data[i]
for i in range(self.max_iteration):
self.classifications = {}
for i in range(self.k):
self.classifications[i] = []
for featureset in data:
distances = [np.linalg.norm(featureset-self.centriods[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
self.classifications[classification].append(featureset)
previous_centroids = dict(self.centroids)
for classifications in self.classificaitons:
self.centroids[classifications] = np.average(self.classificaitons[classifications], axis=0)
optimixed = True
for c in self.centroids:
origional_centroid = previous_centroids[c]
current_centroid = self.centroids[c]
if np.sum((current_centroid - origional_centroid)/origional_centroid*100.0) > self.tol:
optimized = False
if optimized:
break
拟合结束
def predict(self,data):
distances = [np.linalg.norm(featureset-self.centriods[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
return classification
clf = k_means() clf.fit(x)
当我调用 kmeans 时,我希望输出结果显示第 6 行中的一些坐标簇,但我无法克服这个错误。(一旦这个问题得到解决,我计划扩大数据集,这 3 个坐标只是用于练习)。请原谅帖子中代码的格式。