逻辑回归算法python完整代码
时间: 2024-10-18 07:02:31 浏览: 24
逻辑回归是一种广泛用于分类任务的线性模型,它基于Sigmoid函数将线性预测转换为概率。以下是使用Python库`sklearn`实现逻辑回归的简单示例:
```python
# 导入所需的库
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import pandas as pd
import numpy as np
# 假设你已经有了一个名为'data.csv'的数据集,其中包含特征列X和目标列y
data = pd.read_csv('data.csv')
# 数据预处理(如果需要)
# ... (例如:填充缺失值、编码类别变量等)
# 将数据分为特征(X)和标签(y)
X = data.drop('target_column', axis=1) # 替换 'target_column' 为你的真实目标列名
y = data['target_column']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并初始化逻辑回归模型
model = LogisticRegression()
# 训练模型
model.fit(X_train, y_train)
# 预测新数据
predictions = model.predict(X_test)
# 打印预测结果的前几项
print(predictions[:5])
# 结果评估(如精度、召回率等)
from sklearn.metrics import accuracy_score, classification_report
accuracy = accuracy_score(y_test, predictions)
report = classification_report(y_test, predictions)
print(f"Accuracy: {accuracy}")
print("Classification Report:")
print(report)
阅读全文