this function is getting too long / messy.

Please split it up into three functions: 

1. one getting the parameters/data
2. one training the method
3. one applying the method

Then you can start re-using code also in your clustering demo.