complete implementation of cost func and gradient for classification problem