逻辑回归实验完整python代码
时间: 2023-11-03 07:52:56 浏览: 77
基于Python的逻辑回归实验【100011738】
以下是逻辑回归实验的完整 Python 代码:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
# Load the data
data = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
# Convert categorical variable to numerical
data.species = pd.Categorical(data.species)
data['species'] = data.species.cat.codes
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(data.iloc[:, :-1], data.iloc[:, -1], test_size=0.2)
# Create a logistic regression model
model = LogisticRegression()
# Train the model using the training data
model.fit(X_train, y_train)
# Make predictions on the testing data
predictions = model.predict(X_test)
# Print the accuracy score
print('Accuracy:', model.score(X_test, y_test))
# Print the confusion matrix
print('Confusion Matrix:')
print(confusion_matrix(y_test, predictions))
```
在这个示例中,我们使用逻辑回归模型对鸢尾花数据集进行分类。我们首先加载数据集,然后将分类变量转换为数字变量。接下来,我们将数据集拆分为训练集和测试集,然后创建一个逻辑回归模型并使用训练数据进行训练。最后,我们使用测试数据进行预测并计算模型的准确性和混淆矩阵。
阅读全文