# 创建逻辑回归模型
时间: 2024-10-13 07:16:59 浏览: 20
逻辑回归,逻辑回归算法原理,Python
5星 · 资源好评率100%
创建逻辑回归模型通常用于分类任务,它基于线性回归模型并引入了概率解释,使得预测结果表现为0到1之间的连续值,而非离散类别。以下是使用Python的scikit-learn库创建逻辑回归模型的基本步骤:
1. 导入所需库:
```python
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import pandas as pd
```
2. 加载数据集(假设数据已经预处理好):
```python
data = pd.read_csv('your_data.csv')
X = data.drop('target_column', axis=1) # 特征列
y = data['target_column'] # 目标变量
```
3. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 初始化并训练模型:
```python
model = LogisticRegression()
model.fit(X_train, y_train)
```
5. 预测新样本:
```python
predictions = model.predict(X_test)
```
6. 模型评估(如计算准确率):
```python
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, predictions)
```
阅读全文