目录
代码:
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