给我一个基于鸢尾花数据集的logisitic源码,内含梯度下降方法,和预测准确率
时间: 2023-04-08 13:02:09 浏览: 101
以下是基于鸢尾花数据集的logistic源码,包含梯度下降方法和预测准确率:
```
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将标签转换为二进制分类问题
y = np.where(y == 0, 0, 1)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 定义损失函数
def loss_function(X, y, w):
z = np.dot(X, w)
y_pred = sigmoid(z)
loss = -np.mean(y * np.log(y_pred) + (1 - y) * np.log(1 - y_pred))
return loss
# 定义梯度下降函数
def gradient_descent(X, y, w, learning_rate, num_iterations):
m = len(y)
for i in range(num_iterations):
z = np.dot(X, w)
y_pred = sigmoid(z)
gradient = np.dot(X.T, (y_pred - y)) / m
w -= learning_rate * gradient
return w
# 初始化权重
w = np.zeros(X_train.shape[1])
# 训练模型
w = gradient_descent(X_train, y_train, w, learning_rate=0.1, num_iterations=1000)
# 在测试集上进行预测
z = np.dot(X_test, w)
y_pred = sigmoid(z)
y_pred = np.where(y_pred >= 0.5, 1, 0)
# 计算预测准确率
accuracy = np.mean(y_pred == y_test)
print("预测准确率:", accuracy)
```
希望能对您有所帮助!
阅读全文