train function corrected