Untitled

 avatar
user_3298650655
python
3 years ago
809 B
5
Indexable
def euclid(a, b):
  return np.sqrt(np.sum((a - b) ** 2))

class metric_algorithm:
  def __init__(self, h):
    self.h = h

  def fit(self, X, y):
    self.X = X
    self.y = y
    self.uniq_y = np.unique(y)

  def predict(self, X):
    y_pred = []

    for i in X:
      lab = []
      w = []

      for z in range(len(self.X)):
        d = euclid(i, self.X[z])

        if d < self.h:  
          lab.append(self.y[z])
          w.append(1 - abs(d / self.h))

      ind = 0

      for a in self.uniq_y:  
        max_s = 0

        for k in range(len(self.uniq_y)):
          s = 0

          for i in range(len(lab)):
            if lab[i] == self.uniq_y[k]:
              s += w[i]

          if s > max_s:
            max_s = s
            ind = k

      y_pred.append(self.uniq_y[ind])

    return y_pred
Editor is loading...