簡體   English   中英

Python 編碼錯誤,因為它在我制作 def 后無法定義

[英]Python coding error as it canot defined after i make def

我做了自我進口,但它顯示

NameError: name 'self' is not defined
#implementation
class KMeans:
    def __init__(self, n_cluster=8, max_iter=300):
        self.n_cluster = n_cluster
        self.max_iter = max_iter
        
# Randomly select centroid start points, uniformly distributed across the domain of the dataset
min_, max_ = np.min(X_train, axis=0), np.max(X_train, axis=0)
self.centroids = [uniform(min_, max_) for _ in range(self.n_clusters)]

但顯示

NameError                                 Traceback (most recent call last)
Input In [50], in <cell line: 9>()
      7 # Randomly select centroid start points, uniformly distributed across the domain of the dataset
      8 min_, max_ = np.min(X_train, axis=0), np.max(X_train, axis=0)
----> 9 self.centroids = [uniform(min_, max_) for _ in range(self.n_clusters)]

NameError: name 'self' is not defined

您應該在 Python 中了解更多關於 OOP 的信息(以此處為例)

self是對 class 的當前實例的引用。因此它只能在實例方法內部使用。

您正在嘗試在沒有 object 本身的情況下訪問 object 的引用。

您應該將 function 定義為 class 的方法,然后初始化一些實例。 之后,您將能夠訪問它的方法。

更新了一些方法示例:


from random import uniform

import numpy as np


class KMeans:
    def __init__(self, n_cluster=8, max_iter=300):
        self.n_cluster = n_cluster
        self.max_iter = max_iter

    def get_centroids(self, x_train):
        # Randomly select centroid start points, uniformly distributed across the domain of the dataset
        min_, max_ = np.min(x_train, axis=0), np.max(x_train, axis=0)
        self.centroids = [uniform(min_, max_) for _ in range(self.n_cluster)]
        return self.centroids

some_object = KMeans()
some_object.get_centroids([1, 2, 3])
print(some_object.centroids)

你想做這樣的事情嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM