【问题标题】:'k_means' object has no attribute 'k'“k_means”对象没有属性“k”
【发布时间】:2019-10-25 05:49:25
【问题描述】:

为什么会显示 AttributeError: 'k_means' object has no attribute '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 个坐标只是用于练习)。请原谅帖子中代码的格式。

【问题讨论】:

  • 为什么不修复代码的格式?你代码中的错别字呢?

标签: python-3.x machine-learning cluster-analysis k-means machine-learning-model


【解决方案1】:

您可能调用了旧版本的代码。

因为k_meanskmeans不同。

90% 正确对于编程来说是不够的。你需要更精确地工作。编译语言可能是您更早发现错误的更好选择,而对于初学者来说,python notebook 可能是一个糟糕的选择,因为运行时环境的隐藏状态。

【讨论】:

  • 对不起。我试图找到该问题的解决方案并取出下划线。将其放回去并在类名和调用它之间保持连续性仍然不能解决问题。
  • "AttributeError: 'k_means' object has no attribute 'k'" 仍然显示为错误。
  • 在哪一行?我们看不到错误信息。并用固定版本更新问题,并修复格式,拜托! 重新初始化您的笔记本以消除此类伪影。
猜你喜欢
  • 2021-11-16
  • 2022-08-23
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多