Logistic回归——用于二分类。使用python在乳腺癌数据集上应用Logistic回归进行预测并分析。
时间: 2023-12-29 12:05:52 浏览: 166
Logistic回归在乳腺癌诊断中的应用.zip
好的,下面是关于在乳腺癌数据集上应用Logistic回归进行预测和分析的Python代码:
首先,我们需要导入所需的库和数据集:
```python
import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
cancer = load_breast_cancer()
df = pd.DataFrame(np.c_[cancer['data'], cancer['target']], columns = np.append(cancer['feature_names'], ['target']))
```
然后,我们需要将数据集分成训练集和测试集:
```python
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
```
接下来,我们可以使用Logistic回归模型进行训练和预测:
```python
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
```
最后,我们可以使用准确率和混淆矩阵来评估模型的性能:
```python
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
```
完整的代码如下所示:
```python
import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
cancer = load_breast_cancer()
df = pd.DataFrame(np.c_[cancer['data'], cancer['target']], columns = np.append(cancer['feature_names'], ['target']))
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
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)
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
```
阅读全文