下载或者导入鸢尾花数据集,任选两个类别并使用logistics回归正则化实现分类模型,比较不同正则化结果并绘制出该模型的分类结果,并保存模型。

本文介绍了使用Python的Scikit-learn库对鸢尾花数据集进行预处理、划分训练集和测试集,通过GridSearchCV寻找最优LogisticRegression模型参数,最终实现高精度分类并可视化结果,最后保存模型。
摘要由CSDN通过智能技术生成

目录

代码:

运行结果:


代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
import joblib

# 加载鸢尾花数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 选择两个类别(这里选择类别0和1)
X = X[y != 2]
y = y[y != 2]

# 数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 特征缩放
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 定义逻辑回归模型
model = LogisticRegression()

# 定义正则化参数的候选值
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100]}

# 使用GridSearchCV寻找最佳正则化参数
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X_train_scaled, y_train)

# 获取最佳模型
best_model = grid_search.best_estimator_

# 使用最佳模型进行预测
y_pred = best_model.predict(X_test_scaled)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

# 绘制分类结果
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, s=100, label='Actual')
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred,  s=100, label='Predicted') 
plt.title('Logistic Regression Classification Results')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()

# 保存模型
model_filename = 'logistic_regression_model.joblib'
joblib.dump(best_model, model_filename)
print(f"Model saved as {model_filename}")

运行结果:

Accuracy: 1.00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值