Fixed training script to be more robust.