逻辑回归python
时间: 2023-06-28 11:03:58 浏览: 103
逻辑回归 python示例
在Python中实现逻辑回归可以使用多种库,比如Scikit-learn。下面是一个简单的逻辑回归示例:
首先导入所需库:
```python
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
读取数据集:
```python
data = pd.read_csv('data.csv')
```
使用train_test_split分割数据集:
```python
x_train, x_test, y_train, y_test = train_test_split(data.iloc[:, :-1], data.iloc[:, -1], test_size=0.2, random_state=42)
```
创建逻辑回归模型:
```python
lr = LogisticRegression()
```
训练模型:
```python
lr.fit(x_train, y_train)
```
预测测试集并计算准确率:
```python
y_pred = lr.predict(x_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
以上就是一个简单的逻辑回归示例。需要注意的是,逻辑回归适用于二分类问题,如果是多分类问题则需要使用其他算法或对逻辑回归进行扩展。
阅读全文