使用python编程实现逻辑回归模型,在给定数据集上,绘制损失函数曲线图。使用混淆矩阵、错误率、精度、查全率、查准率、F1指标评估逻辑回归模型性能表现,请写出代码
时间: 2024-02-01 12:02:08 浏览: 24
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
# 生成样本数据
np.random.seed(0)
X_train = np.random.randn(100, 2) * 2 + 2
y_train = np.zeros(100)
X_test = np.random.randn(50, 2) * 2 + 2
y_test = np.zeros(50)
X_train = np.concatenate([X_train, np.random.randn(100, 2) * 2 - 2])
y_train = np.concatenate([y_train, np.ones(100)])
X_test = np.concatenate([X_test, np.random.randn(50, 2) * 2 - 2])
y_test = np.concatenate([y_test, np.ones(50)])
# 训练逻辑回归模型
clf = LogisticRegression()
clf.fit(X_train, y_train)
# 绘制损失函数曲线图
plt.plot(clf.loss_curve_)
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.show()
# 预测测试数据集
y_pred = clf.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 计算错误率和精度
error_rate = 1 - accuracy_score(y_test, y_pred)
accuracy = accuracy_score(y_test, y_pred)
# 计算查全率、查准率和F1指标
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# 打印结果
print('混淆矩阵:\n', cm)
print('错误率:', error_rate)
print('精度:', accuracy)
print('查全率:', recall)
print('查准率:', precision)
print('F1指标:', f1)