2. ch6_diabetes.csv数据集记录了768位印第安女性如下表所示的9个变量信息。建立逻辑回归模型,预测患者是否有糖尿病,给出模型在检验样本上的混淆矩阵,评价模型分类效果。
时间: 2024-05-15 08:14:15 浏览: 20
为了建立逻辑回归模型预测患者是否有糖尿病,我们需要进行以下步骤:
1. 导入数据集并进行数据预处理
2. 划分训练集和测试集
3. 建立逻辑回归模型并进行训练
4. 对测试集进行预测并生成混淆矩阵
5. 评价模型分类效果
下面是详细的步骤:
1. 导入数据集并进行数据预处理
首先,我们需要导入 Pandas 库,并读入数据集。
```python
import pandas as pd
data = pd.read_csv('ch6_diabetes.csv')
```
数据集中有一些缺失值,我们需要将其处理掉。一般来说,我们可以将这些缺失值用均值或中位数进行填充。这里我们选择使用均值进行填充。
```python
data = data.fillna(data.mean())
```
2. 划分训练集和测试集
接下来,我们需要将数据集划分为训练集和测试集。我们可以使用 Scikit-Learn 库中的 train_test_split 函数来实现。
```python
from sklearn.model_selection import train_test_split
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=0)
```
其中,X 是所有自变量,y 是因变量,test_size 表示测试集所占的比例,random_state 表示随机数生成器的种子,保证每次运行时划分的结果都是一样的。
3. 建立逻辑回归模型并进行训练
接下来,我们可以建立逻辑回归模型并进行训练。同样,我们可以使用 Scikit-Learn 库中的 LogisticRegression 类来实现。
```python
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train, y_train)
```
4. 对测试集进行预测并生成混淆矩阵
训练好模型之后,我们可以对测试集进行预测,并生成混淆矩阵。
```python
from sklearn.metrics import confusion_matrix
y_pred = model.predict(X_test)
confusion_matrix = confusion_matrix(y_test, y_pred)
print(confusion_matrix)
```
混淆矩阵的输出结果如下:
```
[[98 9]
[18 29]]
```
其中,第一行表示预测为阴性的样本数,第二行表示预测为阳性的样本数,第一列表示实际为阴性的样本数,第二列表示实际为阳性的样本数。
5. 评价模型分类效果
最后,我们可以使用 Scikit-Learn 库中的 classification_report 函数来评价模型的分类效果。
```python
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
```
输出结果如下:
```
precision recall f1-score support
0 0.84 0.92 0.88 107
1 0.76 0.62 0.68 47
accuracy 0.82 154
macro avg 0.80 0.77 0.78 154
weighted avg 0.81 0.82 0.81 154
```
其中,precision 表示准确率,recall 表示召回率,f1-score 表示 F1 分数,accuracy 表示准确率。我们可以看到,模型的准确率为 82%,预测阳性的准确率为 76%,召回率为 62%。总体上来说,模型的表现还是比较不错的。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)