逻辑回归python代码实现
时间: 2023-10-13 10:25:27 浏览: 58
好的,逻辑回归在 Python 中可以使用 sklearn 库来实现。以下是一个简单的逻辑回归示例代码:
```python
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X = iris['data']
y = iris['target']
# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 定义逻辑回归模型
clf = LogisticRegression(random_state=0)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = clf.score(X_test, y_test)
# 输出准确率
print("Accuracy:", accuracy)
```
以上代码可以实现对鸢尾花数据集的分类任务,将数据集分为训练集和测试集,使用逻辑回归模型进行训练,并输出测试集准确率。
相关问题
逻辑回归python代码实现 迪哥
逻辑回归是一种机器学习算法,常用于二分类问题。下面是一个逻辑回归的Python代码实现的例子:
```python
import numpy as np
import pandas as pd
# Sigmoid函数,用于将预测结果转化为概率值
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 损失函数,用于评估模型的准确性
def cost(theta, X, y):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
second = np.multiply((1-y), np.log(1 - sigmoid(X * theta.T)))
return np.sum(first - second) / len(X)
# 梯度下降算法,用于最小化损失函数,得到最优参数
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.ravel().shape[1])
cost = np.zeros(iters)
for i in range(iters):
error = sigmoid(X * theta.T) - y
for j in range(parameters):
term = np.multiply(error, X[:,j])
temp[0,j] = theta[0,j] - (alpha / len(X)) * np.sum(term)
theta = temp
cost[i] = cost(theta, X, y)
return theta, cost
# 读取数据
data = pd.read_csv('data.csv')
# 添加一列全为1的特征列
data.insert(0, 'Ones', 1)
# 将数据转化为矩阵
cols = data.shape[1]
X = data.iloc[:,0:cols-1]
y = data.iloc[:,cols-1:cols]
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.zeros([1,3])
# 设置学习率和迭代次数
alpha = 0.01
iters = 1000
# 执行梯度下降算法,得到最优参数
theta, cost = gradientDescent(X, y, theta, alpha, iters)
# 输出最优参数和损失函数值
print("最优参数:", theta)
print("损失函数值:", cost[-1])
```
贝叶斯参数优化逻辑回归Python代码实现
贝叶斯参数优化逻辑回归是一种使用贝叶斯优化算法来寻找逻辑回归模型最佳参数的方法。下面是一个简单的Python代码实现:
```python
import numpy as np
from sklearn.linear_model import LogisticRegression
from skopt import BayesSearchCV
# 准备数据
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 0, 1, 1])
# 定义逻辑回归模型
model = LogisticRegression()
# 定义参数搜索空间
param_space = {
'C': (0.1, 10.0, 'log-uniform'),
'penalty': ['l1', 'l2'],
'fit_intercept': [True, False],
'solver': ['liblinear', 'saga']
}
# 使用贝叶斯参数优化进行参数搜索
opt_model = BayesSearchCV(model, param_space, n_iter=50, cv=3)
opt_model.fit(X, y)
# 输出最佳参数和得分
print("Best parameters found: ", opt_model.best_params_)
print("Best score found: ", opt_model.best_score_)
```
这段代码使用了`sklearn`库中的`LogisticRegression`类作为逻辑回归模型,并使用`skopt`库中的`BayesSearchCV`类进行贝叶斯参数优化。首先,我们准备了输入特征矩阵`X`和目标变量数组`y`。然后,定义了逻辑回归模型`model`和参数搜索空间`param_space`。最后,使用`BayesSearchCV`进行参数搜索,并输出最佳参数和得分。