目标:建立分类器(求解出三个参数 )
设定阈值,根据阈值判断录取结果
要完成的模块
-
sigmoid
: 映射到概率的函数 -
model
: 返回预测结果值 -
cost
: 根据参数计算损失 -
gradient
: 计算每个参数的梯度方向 -
descent
: 进行参数更新 -
accuracy
: 计算精度
sigmoid
函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
sigmoid(0)
model函数
def model(X, theta):
return sigmoid(np.dot(X, theta.T))
损失函数
将对数似然函数去负号
求平均损失
def cost(x, y, theta):
left = np.multiply(-y, np.log(model(x, theta)))
right = np.multiply(1 - y, np.log(1 - model(x, theta)))
return np.sum(left - right) / (len(x))
计算梯度
def gradient(x, y, theta):
grad = np.zeros(theta.shape)
error = (model(x, theta) - y).ravel()
for j in range(len(theta.ravel())):
term = np.multiply(error, x[:, j])
grad[0, j] = np.sum(term) / len(x)
return grad