[英]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.