The smart contract environment is not adequate to implement any machine learning algorithm which could need a non definite number of iterations. This aspect conflicts with the maximum computational power which can be included in a single Ethereum block, where you cannot split the convergency algorithm to use more blocks than one without heavy overheads.
On the other side, the unavailability of any double or float math, more an int/uint math not protected against overflows by default, the absence of the memory pointers and so on, make it to implement gradient landing algorithms a true nightmare.
In general, any smart contract under Ethereum is more adequate to implement finite state machines with some very light computations on it, nothing more.
Trying to implement heavy computational works on it results in a costly run of the same, where it can be implemented.
Probably, the clustering part of the application should be moved on some offline resource based on a state completely defined and stored on the blockchain.