logistic regression损失函数python代码
时间: 2023-09-03 10:11:55 浏览: 23
下面是一个简单的 logistic regression 损失函数 Python 代码示例:
```python
import numpy as np
def sigmoid(z):
"""sigmoid函数"""
return 1 / (1 + np.exp(-z))
def loss(h, y):
"""损失函数"""
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
def logistic_regression(X, y, num_iterations, learning_rate):
"""logistic regression模型训练"""
# 初始化模型参数
theta = np.zeros(X.shape[1])
# 迭代训练
for i in range(num_iterations):
# 计算模型预测值
z = np.dot(X, theta)
h = sigmoid(z)
# 计算损失函数
l = loss(h, y)
# 计算梯度
gradient = np.dot(X.T, (h - y)) / y.size
# 更新模型参数
theta -= learning_rate * gradient
return theta
```
其中,`sigmoid` 函数是 logistic regression 模型中常用的激活函数;`loss` 函数是 logistic regression 模型中常用的损失函数,它计算模型预测值与实际值之间的差异;`logistic_regression` 函数是 logistic regression 模型的训练函数,它通过迭代训练来更新模型参数,使得损失函数最小化。