官网教程:logistic-regression — scikit-learn 1.5.1 documentation
一 导入包
# 导入包
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
二 数据加载
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
三 数据划分
# 将数据划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
四 模型创建
# 创建逻辑回归模型实例
logistic_regression = LogisticRegression(max_iter=10, random_state=42)
五 模型训练
# 预测测试集上的标签
y_pred = logistic_regression.predict(X_test)
六 模型评估
# 输出预测准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f}")# 输出详细的分类报告
report = classification_report(y_test, y_pred)
print("Classification Report:")
print(report)# 查看模型系数
coefficients = logistic_regression.coef_
print("Coefficients:")
print(coefficients)# 查看截距
intercept = logistic_regression.intercept_
print("Intercept:")
print(intercept)