task06_DW机器学习基础
作者:互联网
评估模型的性能并调参
本次学习首先讲述了使用网格搜索与随机网格搜索,开始用make_pipeline
封装了SVC,
pipe_svc = make_pipeline(StandardScalar(), SVC(random_state=1)
然后分别用sklearn中的GridSearchCV
和RandomizedSearchCV
进行调参优化。
- 当类别为两类时,可采用绘制混淆矩阵和ROC曲线
- 混淆矩阵
代码为:confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
绘制混淆矩阵图:ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)
- ROC曲线
代码:fpr, tpr, threshold = roc_curve(y_test, y_pred) # 计算真阳率和假阳率
绘制ROC曲线:plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) # 假阳率为横坐标,真阳率为纵坐标
- 混淆矩阵
小任务
- 采用了学习小组中提供的参考代码进行了学习;
其中主要步骤为将数据集划分为训练集和测试集,其中训练集进行训练时,分为了训练集和验证集, 通过验证集选择最优模型,测试集测试其性能;本次学习主要通过PCA分解提取特征。
from time import time
import logging
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC
print(__doc__)
# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
# #############################################################################
# Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape
# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]
# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]
print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)
# #############################################################################
# Split into a training set and a test set using a stratified k fold
# split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
# #############################################################################
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150
print("Extracting the top %d eigenfaces from %d faces"
% (n_components, X_train.shape[0]))
t0 = time()
pca = PCA(n_components=n_components, svd_solver='randomized',
whiten=True).fit(X_train)
print("done in %0.3fs" % (time() - t0))
标签:机器,people,print,lfw,import,test,DW,task06,sklearn 来源: https://blog.csdn.net/weixin_46121800/article/details/115313268