It works. But where was the problem in my code. Can you please explain a little. I think it is because of detach() . Another thing is it does not work if the prediction check is done as part of while condition. Why is that? Thank you.