【问题标题】:AttributeError: 'KMeans' object has no attribute 'k'AttributeError: \'KMeans\' 对象没有属性 \'k\'
【发布时间】:2022-08-23 14:50:50
【问题描述】:

我知道有一个完全相同的问题[here]。但这对我不起作用,另一个人发现它不正确,如答案的评论中所述。虽然,OP(也回答了他的问题)没有回复评论以解释更多。因此,我再次要求此寻求帮助。

我尝试了什么:

  1. k 更改为n_clustern_clusters(如类似问题的cmets 部分所述)既不能解决问题也不能改变错误!!
  2. \"storing the result of the elbow_method function into a variable\"不起作用(请参阅我的代码)

    我正在尝试使用KElbowVisualizer 的轮廓系数在KMeans 聚类中找到最佳聚类数。假设这是火车数据:

    import numpy as np
    
    data = np.array([[146162.56679954],
           [137227.54181954],
           [126450.29169228],
           [119435.56512675],
           [114988.18682806],
           [111546.74599395],
           [111521.9739634 ],
           [110335.78734103],
           [105098.20650161],
           [ 99178.48409528],
           [ 93982.20860075],
           [ 91453.21097512],
           [ 94160.32926255],
           [102299.29173218],
           [114540.38664748],
           [122133.18759654],
           [121756.94400854],
           [118709.47518003],
           [119216.20443483],
           [122172.5736574 ],
           [122433.8120907 ],
           [120599.22092939],
           [118789.73304299],
           [119107.28063106],
           [123920.58809778],
           [128772.96569855],
           [131502.10371984],
           [129525.67885428],
           [123411.68604418],
           [120263.05106831],
           [114844.47942828],
           [108214.07115472],
           [101822.69619871],
           [ 94871.33385049],
           [ 91251.9375137 ],
           [ 90058.80745747],
           [ 93606.20700239],
           [101044.76675943],
           [109125.2713446 ],
           [112272.386321  ],
           [104429.87179175],
           [ 90827.50408907],
           [ 80805.43033707],
           [ 76165.48417937],
           [ 75002.04576279],
           [ 75428.52404817],
           [ 77444.72355588],
           [ 80389.43621805],
           [ 83401.15424418],
           [ 87638.20462011]])
    

    以下代码与寻找最佳聚类数有关:

    from sklearn.cluster import KMeans
    from yellowbrick.cluster import KElbowVisualizer
    
    # Here, I store the results in a variable named `visualizer` (Since the OP of the similar question said in his answer)
    visualizer = KElbowVisualizer(KMeans(), k=11, metric=\'silhouette\', timings= True)
    visualizer.fit(data)
    

    我收到此错误:

    AttributeError                            Traceback (most recent call last)
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\IPython\\core\\formatters.py:343, in BaseFormatter.__call__(self, obj)
        341     method = get_real_method(obj, self.print_method)
        342     if method is not None:
    --> 343         return method()
        344     return None
        345 else:
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\base.py:625, in BaseEstimator._repr_html_inner(self)
        620 def _repr_html_inner(self):
        621     \"\"\"This function is returned by the @property `_repr_html_` to make
        622     `hasattr(estimator, \"_repr_html_\") return `True` or `False` depending
        623     on `get_config()[\"display\"]`.
        624     \"\"\"
    --> 625     return estimator_html_repr(self)
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\utils\\_estimator_html_repr.py:385, in estimator_html_repr(estimator)
        383 style_template = Template(_STYLE)
        384 style_with_id = style_template.substitute(id=container_id)
    --> 385 estimator_str = str(estimator)
        387 # The fallback message is shown by default and loading the CSS sets
        388 # div.sk-text-repr-fallback to display: none to hide the fallback message.
        389 #
       (...)
        394 # The reverse logic applies to HTML repr div.sk-container.
        395 # div.sk-container is hidden by default and the loading the CSS displays it.
        396 fallback_msg = (
        397     \"In a Jupyter environment, please rerun this cell to show the HTML\"
        398     \" representation or trust the notebook. <br />On GitHub, the\"
        399     \" HTML representation is unable to render, please try loading this page\"
        400     \" with nbviewer.org.\"
        401 )
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\base.py:279, in BaseEstimator.__repr__(self, N_CHAR_MAX)
        271 # use ellipsis for sequences with a lot of elements
        272 pp = _EstimatorPrettyPrinter(
        273     compact=True,
        274     indent=1,
        275     indent_at_name=True,
        276     n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW,
        277 )
    --> 279 repr_ = pp.pformat(self)
        281 # Use bruteforce ellipsis when there are a lot of non-blank characters
        282 n_nonblank = len(\"\".join(repr_.split()))
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\pprint.py:157, in PrettyPrinter.pformat(self, object)
        155 def pformat(self, object):
        156     sio = _StringIO()
    --> 157     self._format(object, sio, 0, 0, {}, 0)
        158     return sio.getvalue()
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\pprint.py:174, in PrettyPrinter._format(self, object, stream, indent, allowance, context, level)
        172     self._readable = False
        173     return
    --> 174 rep = self._repr(object, context, level)
        175 max_width = self._width - indent - allowance
        176 if len(rep) > max_width:
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\pprint.py:454, in PrettyPrinter._repr(self, object, context, level)
        453 def _repr(self, object, context, level):
    --> 454     repr, readable, recursive = self.format(object, context.copy(),
        455                                             self._depth, level)
        456     if not readable:
        457         self._readable = False
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\utils\\_pprint.py:189, in _EstimatorPrettyPrinter.format(self, object, context, maxlevels, level)
        188 def format(self, object, context, maxlevels, level):
    --> 189     return _safe_repr(
        190         object, context, maxlevels, level, changed_only=self._changed_only
        191     )
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\utils\\_pprint.py:440, in _safe_repr(object, context, maxlevels, level, changed_only)
        438 recursive = False
        439 if changed_only:
    --> 440     params = _changed_params(object)
        441 else:
        442     params = object.get_params(deep=False)
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\utils\\_pprint.py:93, in _changed_params(estimator)
         89 def _changed_params(estimator):
         90     \"\"\"Return dict (param_name: value) of parameters that were given to
         91     estimator with non-default values.\"\"\"
    ---> 93     params = estimator.get_params(deep=False)
         94     init_func = getattr(estimator.__init__, \"deprecated_original\", estimator.__init__)
         95     init_params = inspect.signature(init_func).parameters
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\yellowbrick\\base.py:342, in ModelVisualizer.get_params(self, deep)
        334 def get_params(self, deep=True):
        335     \"\"\"
        336     After v0.24 - scikit-learn is able to determine that ``self.estimator`` is
        337     nested and fetches its params using ``estimator__param``. This functionality is
       (...)
        340     the estimator params.
        341     \"\"\"
    --> 342     params = super(ModelVisualizer, self).get_params(deep=deep)
        343     for param in list(params.keys()):
        344         if param.startswith(\"estimator__\"):
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\sklearn\\base.py:211, in BaseEstimator.get_params(self, deep)
        209 out = dict()
        210 for key in self._get_param_names():
    --> 211     value = getattr(self, key)
        212     if deep and hasattr(value, \"get_params\"):
        213         deep_items = value.get_params().items()
    
    File ~\\Anaconda3\\envs\\Python3.10\\lib\\site-packages\\yellowbrick\\utils\\wrapper.py:42, in Wrapper.__getattr__(self, attr)
         40 def __getattr__(self, attr):
         41     # proxy to the wrapped object
    ---> 42     return getattr(self._wrapped, attr)
    
    AttributeError: \'KMeans\' object has no attribute \'k\'
    

    加上一个数字(继续错误!):
    有趣的是它呈现了一个我根本没有要求的情节!另外,我设置了timings= True,但情节上没有任何时间信息!所以也许这意味着算法根本没有运行(但我不知道它是如何渲染结果的!)。所以我想知道,问题出在哪里?

    附加信息:
    yellowbrick 版本 = 1.4
    scikitlearn 版本 = 1.1.1

    我也在 VSCode 和 Jupyter Notebook (anaconda) 中尝试过这些。结果是一样的。

    标签: python scikit-learn yellowbrick


    【解决方案1】:

    我尝试了一些东西,但我需要帮助理解为什么我应该为此定义一个class。代码:

    class find_n_cluster:
        def __init__(self, train_data, metric) -> None:
            self.data = train_data
            self.metric = metric
            self.visualizer = KElbowVisualizer(KMeans(), k=11, metric=self.metric, timings= True)
    
        def fit(self):
            self.visualizer.fit(self.data)
    
    model = find_n_cluster(data, 'silhouette')
    model.fit()
    

    结果(由于情节而出乎意料):

    再说一次,我什至没有要求任何情节! 另外,我不知道如何为这个工作定义一个class 来解决这个错误!!


    更新
    我通过在self.visualizer.fit(self.data) 之后添加plt.close() 解决了与显示情节相关的问题:

    class find_n_cluster:
        def __init__(self, train_data, metric) -> None:
            self.data = train_data
            self.metric = metric
            self.visualizer = KElbowVisualizer(KMeans(), k=11, metric=self.metric, timings= True)
    
        def fit(self):
            self.visualizer.fit(self.data)
            plt.close()
    
    model = find_n_cluster(data, 'silhouette')
    model.fit()
    

    这不会返回并按预期显示任何内容。但是,我仍然不知道如何定义 class 解决了这个错误。


    2022 年 8 月 23 日更新

    基于thisyellowbrick更新为v1.5,解决了AttributeError: 'KMeans' object has no attribute 'k'的问题。但是在 Jupyter Notebook 中自动显示绘图的问题是still persistent

    【讨论】:

      【解决方案2】:

      我相信模型需要在变量中分配,我不确定它是否可以在函数中调用。在仔细查看并重新启动我的内核并将所有库重新安装到其最新版本之后(截至本文)。以下代码有效,可以在我的控制台中复制:

      从 sklearn.cluster 导入 KMeans 从 Yellowbrick.cluster 导入 KElbowVisualizer

      model = KMeans()
      visualizer = KElbowVisualizer(model, k=11,metric='silhouette', timings= True)
      visualizer.fit(data)
      visualizer.show()
      

      输出:

      Out[24]: <AxesSubplot:title={'center':'Silhouette Score Elbow for KMeans Clustering'}, xlabel='k', ylabel='silhouette score'>
      

      【讨论】:

      • 你好,谢谢你的好态度。我试了一下,得到了相同的结果(错误):(。是的,它可以在official doc 中所述的KElbowVisualizer 函数中调用。
      • 感谢您的评论,我设法复制了您的问题。致力于解决方案。
      • 非常感谢?我希望我们能找到解决方法。
      • 我做了,我不确定,让我编辑我的,因为我也让它工作。
      • 所以你的意思是更新软件包导致干净运行没有任何错误?但是我定义的类呢?它也可以毫无问题地运行。我的意思是,我们没有找到问题的根源。此外,如果您评论 visualizer.show() 并重新运行它,它会呈现一个情节。我们现在有两个问题:找到错误的根源和渲染图!
      猜你喜欢
      • 2021-11-16
      • 2021-05-08
      • 2021-06-15
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2021-04-19
      相关资源
      最近更新 更多