fork download
  1. import numpy as np
  2.  
  3. def sigmoid(z):
  4. """Sigmoid activation function"""
  5. return 1 / (1 + np.exp(-z))
  6.  
  7. def logistic_cost_function(X, y, theta):
  8. """
  9. Compute the cost function for logistic regression
  10.  
  11. Parameters:
  12. X : numpy array of shape (m, n) - feature matrix
  13. y : numpy array of shape (m,) - target labels (0 or 1)
  14. theta : numpy array of shape (n,) - parameters
  15.  
  16. Returns:
  17. cost : float
  18. """
  19. m = len(y)
  20.  
  21. # Calculate hypothesis using sigmoid
  22. h = sigmoid(X @ theta)
  23.  
  24. # Avoid log(0) errors by using np.clip or np.where
  25. h = np.clip(h, 1e-15, 1 - 1e-15) # Clip to prevent log(0)
  26.  
  27. # Cost function with logs
  28. cost = (-1/m) * np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))
  29.  
  30. return cost
Success #stdin #stdout 0.82s 41292KB
stdin
Standard input is empty
stdout
Standard output is empty