Skip to content
Advertisement

python divide by zero encountered in log – logistic regression

I’m trying to implement a multiclass logistic regression classifier that distinguishes between k different classes.

This is my code.

JavaScript

I can verify that cost and gradient are returning values that are in the right dimension (cost returns a scalar, and gradient returns a 1 by n row vector), but i get the error

JavaScript

why is this happening and how can i avoid this?

Advertisement

Answer

You can clean up the formula by appropriately using broadcasting, the operator * for dot products of vectors, and the operator @ for matrix multiplication — and breaking it up as suggested in the comments.

Here is your cost function:

JavaScript

You can clean up your gradient function along the same lines.

By the way, are you sure you want np.linalg.norm(theta[1:]). If you’re trying to do L2-regularization, the term should be np.linalg.norm(theta[1:]) ** 2.

Advertisement