能否给我提供一份适用于逻辑回归的案例和相关代码
时间: 2023-07-12 21:54:06 浏览: 91
当然可以,以下是一个适用于逻辑回归的案例和相关代码:
案例:假设你是一家银行的贷款官员,你需要根据客户的信用评级、收入、负债和其他因素来预测客户是否会还贷。你可以使用逻辑回归算法来进行预测。
代码:
首先,我们需要导入所需的库和数据集:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/german.csv"
data = pd.read_csv(url, delimiter=';')
```
接下来,我们需要对数据集进行预处理,包括特征选择、缺失值处理、特征编码等:
```python
# 特征选择
features = ['status', 'duration', 'credit_history', 'purpose', 'amount', 'savings', 'employment', 'installment_rate', 'personal_status', 'other_debtors', 'residence_since', 'property', 'age', 'other_installment_plans', 'housing', 'existing_credits', 'job', 'num_dependents', 'telephone', 'foreign_worker', 'credit_risk']
data = data[features]
# 缺失值处理
data = data.replace('?', np.nan)
data = data.dropna()
# 特征编码
data = pd.get_dummies(data, columns=['status', 'credit_history', 'purpose', 'savings', 'employment', 'personal_status', 'other_debtors', 'property', 'other_installment_plans', 'housing', 'job', 'telephone', 'foreign_worker'])
# 定义特征和目标
X = data.drop('credit_risk', axis=1)
y = data['credit_risk']
```
然后,我们将数据集拆分为训练集和测试集,并使用逻辑回归算法进行训练和测试:
```python
# 拆分数据集
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)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
```
最后,我们可以输出模型的准确率,以评估模型的性能。
阅读全文