Improved Training Function