逻辑回归糖尿病python
时间: 2024-12-26 13:19:01 浏览: 5
逻辑回归是一种广泛用于分类任务的统计模型,特别是在二分类问题中预测结果的概率。针对糖尿病预测这类问题,逻辑回归可以用来识别个体是否有患糖尿病的风险,基于输入的特征变量如年龄、BMI等。
在Python中,我们可以使用sklearn库来实现逻辑回归。以下是简单的步骤:
1. 导入所需库:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
```
2. 加载数据集(假设数据在'diabetes.csv'文件中):
```python
data = pd.read_csv('diabetes.csv')
```
3. 数据预处理,包括特征选择、缺失值处理和转换(例如,如果特征是类别型,需要编码):
```python
X = data.drop('Outcome', axis=1) # 假设最后一列是目标变量
y = data['Outcome']
# 划分训练集和测试集
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
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
conf_mat = confusion_matrix(y_test, y_pred)
print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_mat)
```
阅读全文