ML: new cost function and gradient solution