0

I'm a python beginner and I'm implementing a version of k-means.

I'm defining the k-means class and one of the class attributes is __class, where __class[i] = j means that the i-th data point is assigned to the j-th cluster. This means that if we have n datapoints and k clusters, then 0 <= __class[i] < k for each i in range(n).

Now, what I want to do (to be error safe) is to raise an exception if we do something like __class[i] = impossibleK where impossibleK < 0 V impossibleK >= k and i in range(n). In few words, I want that exception is thrown whenever we assign an impossible cluster to an element of __class.

How can I automatize this check in Python?

This the class and the constructor:

import numpy as np


class CLUMPY:
    def __init__(self, k, file):
        # input file
        self.__file = file
        print("k=",k)
        print("Reading {}...".format(file))
        # data points
        self.__points = np.loadtxt(file)
        # number of data points
        self.__n = self.__points.shape[0]
        # data points dimensionality (or length according to numpy terminology)
        self.__d = self.__points.shape[1]
        print("Read {}: {} points in {} dimensions.".format(file, self.__n, self.__d))
        # __class[i] = j : the i-th data point is assigned to the j-th cluster
        self.__class = np.zeros(self.__n, dtype=np.int8)


if __name__ == "__main__":
    clumpy = CLUMPY(2, "datasets/202d")
justHelloWorld
  • 6,478
  • 8
  • 58
  • 138
  • https://stackoverflow.com/q/11902458/1951298 – Curcuma_ Sep 16 '17 at 20:57
  • @Curcuma_ I'm not sure that I understand your linked question, but the problem here seems different: I don't want to handle exceptions, I want to raise exception when a condition is not satisfied during the assignment operation. Please, correct me if I'm still missing something, otherwise read my question again. – justHelloWorld Sep 17 '17 at 10:45
  • Then just raise when it's the case – Curcuma_ Sep 17 '17 at 16:40

1 Answers1

0

You can use error handling in python...

try:
    __class[i] = j  # impossibleK
except IndexError:
    print("Index error occurred")
Jai
  • 3,211
  • 2
  • 17
  • 26