Home > Mobile >  Python coding error as it canot defined after i make def
Python coding error as it canot defined after i make def

Time:11-18

i did imported self but it show

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)]

but show

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

CodePudding user response:

You should learn more about OOP in Python (here for example)

self is a reference to the current instance of the class. So it can be used only inside of instance method.

You are trying to reach reference of an object without object itself.

You should define your function as a method of your class and then initialize some instance. After that you will be able to access its methods.

UPD some example of method:


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)

Are you trying to do something like this?

  • Related