简体   繁体   中英

What is the best way to add option to your class?

I am trying to create a class for basic prediction and I want to call different metrics for it like Euclidian, Manhattan, etc. What would be the best way to call these distance functions? Creating a distance class, where I can call the class or creating a file with functions and call it to class by just its name (I do not know how to do this)

class KNN_classifier:
    
    def __init__(self, k=3i distance_function_here = 'Manhattan'):
        self.k = k
        
    def fit(self, X_train, y_train):
        self.X_train = X_train
        self.y_train = y_train

    def predict(self, X_test):
        
        predictions = list()
        for x in X_test:
            distances = [distance_function_here(x, x_train) for x_train in self.X_train]
            k_idx = np.argsort(distances)[0:self.k]
            k_nearest_label = [self.y_train[i] for i in k_idx]
            
            label = Counter(k_nearest_label).most_common(1)[0][0]
            predictions.append(label)

        return predictions

Is there scope here for subclassing: It is one good way of providing options, where each option is potentially a very different execution.

Each of your metrics is implmented as a subclass of KNN_classifier , and each of these parent classes has to provide a metric method which the KVN_classifier then invokes at the appropriate places.

This way you can provide as many different metrics you want without eevr modifying the KVN_classifier class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM