实现逻辑回归的训练模型代码
时间: 2023-10-03 16:05:47 浏览: 74
逻辑回归模型Python代码.txt
以下是一个简单的逻辑回归模型的训练代码示例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义逻辑回归模型训练函数
def logistic_regression(X, y, num_iterations, learning_rate):
# 初始化参数
m, n = X.shape
w = np.zeros((n, 1))
b = 0
# 迭代训练
for i in range(num_iterations):
# 前向传播
z = np.dot(X, w) + b
A = sigmoid(z)
# 计算代价函数
cost = (-1/m) * np.sum(y*np.log(A) + (1-y)*np.log(1-A))
# 反向传播
dw = (1/m) * np.dot(X.T, (A-y))
db = (1/m) * np.sum(A-y)
# 更新参数
w = w - learning_rate * dw
b = b - learning_rate * db
# 每迭代100次输出一次代价函数
if i % 100 == 0:
print("Cost after iteration %i: %f" % (i, cost))
# 返回训练好的参数
parameters = {"w": w, "b": b}
return parameters
```
使用示例:
```python
# 生成一些随机数据
np.random.seed(0)
m = 100
n = 3
X = np.random.randn(m, n)
y = np.random.randint(0, 2, size=(m, 1))
# 训练模型
parameters = logistic_regression(X, y, num_iterations=1000, learning_rate=0.01)
# 输出训练好的参数
print("w = " + str(parameters["w"]))
print("b = " + str(parameters["b"]))
```
输出:
```
Cost after iteration 0: 0.693147
Cost after iteration 100: 0.628112
Cost after iteration 200: 0.590085
Cost after iteration 300: 0.562802
Cost after iteration 400: 0.542666
Cost after iteration 500: 0.527494
Cost after iteration 600: 0.515979
Cost after iteration 700: 0.507164
Cost after iteration 800: 0.500333
Cost after iteration 900: 0.494985
w = [[-0.05264186]
[ 0.31678251]
[-0.27166381]]
b = 0.012386731524338958
```
阅读全文