请在jupyter中,完成并补全以下任务代码:作业:考虑Breast_Cancer-乳腺癌数据集 总类别数为2 特征数为30 样本数为569(正样本212条,负样本357条) 特征均为数值连续型、无缺失值 (1)使用GridSearchCV搜索单个DecisionTreeClassifier中max_samples,max_features,max_depth的最优值。 (2)使用GridSearchCV搜索BaggingClassifier中n_estimators的最佳值。 (3)考虑BaggingClassifier中的弱分类器使用SVC(可以考虑是否使用核函数),类似步骤(1),(2), 自己调参(比如高斯核函数的gamma参数,C参数),寻找最优分类结果。 from sklearn.datasets import load_breast_cancer from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap ds_breast_cancer = load_breast_cancer() X=ds_breast_cancer.data y=ds_breast_cancer.target # draw sactter f1 = plt.figure() cm_bright = ListedColormap(['r', 'b', 'g']) ax = plt.subplot(1, 1, 1) ax.set_title('breast_cancer') ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cm_bright, edgecolors='k') plt.show()
时间: 2024-02-16 08:04:31 浏览: 26
(1) 使用GridSearchCV搜索单个DecisionTreeClassifier中max_samples,max_features,max_depth的最优值。
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
# 数据预处理
sc = StandardScaler()
X_std = sc.fit_transform(X)
# 定义模型
tree = DecisionTreeClassifier()
# 定义参数空间
param_grid = {'max_samples': [0.4, 0.6, 0.8, 1.0],
'max_features': [0.4, 0.6, 0.8, 1.0],
'max_depth': [3, 5, 7, 9, None]}
# 定义网格搜索对象
clf = GridSearchCV(tree, param_grid=param_grid, cv=5)
# 训练模型
clf.fit(X_std, y)
# 输出最优参数
print("Best parameters:", clf.best_params_)
```
(2) 使用GridSearchCV搜索BaggingClassifier中n_estimators的最佳值。
```python
from sklearn.ensemble import BaggingClassifier
# 定义模型
tree = DecisionTreeClassifier()
bagging = BaggingClassifier(tree)
# 定义参数空间
param_grid = {'n_estimators': [10, 50, 100, 200, 500]}
# 定义网格搜索对象
clf = GridSearchCV(bagging, param_grid=param_grid, cv=5)
# 训练模型
clf.fit(X_std, y)
# 输出最优参数
print("Best parameters:", clf.best_params_)
```
(3) 考虑BaggingClassifier中的弱分类器使用SVC(可以考虑是否使用核函数),类似步骤(1),(2),自己调参(比如高斯核函数的gamma参数,C参数),寻找最优分类结果。
```python
from sklearn.svm import SVC
from sklearn.ensemble import BaggingClassifier
# 定义模型
svc = SVC()
bagging = BaggingClassifier(svc)
# 定义参数空间
param_grid = {'base_estimator__C': [0.1, 1, 10],
'base_estimator__gamma': [0.1, 1, 10],
'n_estimators': [10, 50, 100, 200, 500]}
# 定义网格搜索对象
clf = GridSearchCV(bagging, param_grid=param_grid, cv=5)
# 训练模型
clf.fit(X_std, y)
# 输出最优参数
print("Best parameters:", clf.best_params_)
```