给我一个基于鸢尾花数据集的logisitic源码,内含梯度下降方法
时间: 2023-04-08 17:02:07 浏览: 78
以下是基于鸢尾花数据集的logistic源码,内含梯度下降方法:
```
import numpy as np
from sklearn.datasets import load_iris
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 添加偏置项
X = np.insert(X, 0, 1, axis=1)
# 初始化参数
theta = np.zeros(X.shape[1])
# 定义sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 定义损失函数
def cost_function(X, y, theta):
m = len(y)
h = sigmoid(X.dot(theta))
J = (-1/m) * (y.T.dot(np.log(h)) + (1-y).T.dot(np.log(1-h)))
return J
# 定义梯度下降函数
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
h = sigmoid(X.dot(theta))
theta = theta - (alpha/m) * X.T.dot(h-y)
J_history[i] = cost_function(X, y, theta)
return theta, J_history
# 设置学习率和迭代次数
alpha = 0.01
num_iters = 1000
# 运行梯度下降算法
theta, J_history = gradient_descent(X, y, theta, alpha, num_iters)
# 打印最终参数和损失函数值
print('最终参数:', theta)
print('损失函数值:', J_history[-1])
```