以吴恩达老师的课程为例
损失函数为
带入逻辑回归的损失函数:
有
即
Python代码的实现
import numpy as np
def cost(theta, X, y):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
first = np.multiply(-y, np.log(sigmoid(X*theta.T)))
second = np.multiply((1 - y), np.log(1 - sigmoid(X*theta.T)))
return np.sum(first - second) / (len(X))
之后,就可以使用梯度下降法来求是的损失函数最小的theta参数了。