为啥只有一个图,不是应该四个图吗
时间: 2024-01-26 11:02:08 浏览: 23
非常抱歉,我的回答确实有误。应该对四个数据集分别进行建模和可视化,并且在绘制可视化图像时,需要将四个图像分别绘制出来,而不是只绘制一个图像。以下是修改后的代码,希望能够解决你的问题:
```python
from sklearn.datasets import make_blobs, make_classification, make_moons, make_circles
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import numpy as np
# 生成数据集
X1, y1 = make_blobs(n_samples=100, centers=2, random_state=42)
X2, y2 = make_classification(n_samples=100, n_features=2, n_redundant=0, n_informative=2, random_state=42)
X3, y3 = make_moons(n_samples=100, noise=0.1, random_state=42)
X4, y4 = make_circles(n_samples=100, noise=0.1, factor=0.5, random_state=42)
# 定义超参数空间
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'poly', 'rbf', 'sigmoid'], 'gamma': ['scale', 'auto']}
# 定义模型
model = SVC()
# 定义超参数搜索器
grid_search1 = GridSearchCV(model, param_grid, cv=3)
grid_search2 = GridSearchCV(model, param_grid, cv=3)
grid_search3 = GridSearchCV(model, param_grid, cv=3)
grid_search4 = GridSearchCV(model, param_grid, cv=3)
# 训练模型
grid_search1.fit(X1, y1)
grid_search2.fit(X2, y2)
grid_search3.fit(X3, y3)
grid_search4.fit(X4, y4)
# 输出最优超参数和准确率
print('Data 1 - Best hyperparameters:', grid_search1.best_params_)
print('Data 1 - Accuracy:', grid_search1.best_score_)
print('Data 2 - Best hyperparameters:', grid_search2.best_params_)
print('Data 2 - Accuracy:', grid_search2.best_score_)
print('Data 3 - Best hyperparameters:', grid_search3.best_params_)
print('Data 3 - Accuracy:', grid_search3.best_score_)
print('Data 4 - Best hyperparameters:', grid_search4.best_params_)
print('Data 4 - Accuracy:', grid_search4.best_score_)
# 定义绘图函数
def plot_classification(model, X, y):
# 绘制散点图
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='coolwarm', alpha=0.8)
# 绘制决策边界
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()
xx = np.linspace(xlim[0], xlim[1], 100)
yy = np.linspace(ylim[0], ylim[1], 100)
XX, YY = np.meshgrid(xx, yy)
Z = model.predict(np.c_[XX.ravel(), YY.ravel()]).reshape(XX.shape)
plt.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])
# 绘制数据集和决策边界
plt.subplot(2, 2, 1)
plot_classification(grid_search1.best_estimator_, X1, y1)
plt.title('Data 1')
plt.subplot(2, 2, 2)
plot_classification(grid_search2.best_estimator_, X2, y2)
plt.title('Data 2')
plt.subplot(2, 2, 3)
plot_classification(grid_search3.best_estimator_, X3, y3)
plt.title('Data 3')
plt.subplot(2, 2, 4)
plot_classification(grid_search4.best_estimator_, X4, y4)
plt.title('Data 4')
# 显示图像
plt.show()
```
这样,就可以正确地对四个数据集进行建模和可视化。非常感谢你的指出,我会更加谨慎认真地回答问题。