【DSW Gallery】SkLearn CookBook

本文涉及的产品
交互式建模 PAI-DSW,5000CU*H 3个月
简介: 本文以KNN模型为例子,介绍了如何使用sklearn中的方法进行模型的训练,超参数的自动化调优以及如何对数据进行降维等等。

直接使用

请打开SkLearn CookBook,并点击右上角 “ 在DSW中打开” 。

image.png

sklearn CookBook

本文主要介绍sklearn的一些基本技巧,主要包括以下几方面:

1. sklearn在机器学习中的一些主要应用:
   1. 监督学习/非监督血虚
   2. 如何使用sklearn进行自动化的超参数调优
   3. 如何使用sklearn创建pipeline,让我们的机器学习代码更加简洁高效

1.1 使用sklearn进行监督学习的建模

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.read_csv('diabetes.csv')
df.head()
Pregnancies Glucose BloodPressure SkinThickness Insulin BMI DiabetesPedigreeFunction Age Outcome
0 6 148 72 35 0 33.6 0.627 50 1
1 1 85 66 29 0 26.6 0.351 31 0
2 8 183 64 0 0 23.3 0.672 32 1
3 1 89 66 23 94 28.1 0.167 21 0
4 0 137 40 35 168 43.1 2.288 33 1
X = df.drop('Outcome',axis=1).values
y = df['Outcome'].values
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.4,random_state=42, stratify=y)
from sklearn.neighbors import KNeighborsClassifier
neighbors = np.arange(1,9)
train_accuracy =np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for i,k in enumerate(neighbors):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    train_accuracy[i] = knn.score(X_train, y_train)

基于不同的k,打印k的值和模型精度的关系曲线,我们发现k=7的时候,精度最高

plt.title('k-NN Varying number of neighbors')
plt.plot(neighbors, test_accuracy, label='Testing Accuracy')
plt.plot(neighbors, train_accuracy, label='Training accuracy')
plt.legend()
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
plt.show()   

15-1.png

手动计算一下k=7的时候,分类模型的精度

knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train,y_train)
knn.score(X_test,y_test)
0.7305194805194806

计算一下此时的混淆矩阵

  1. 使用sklearn提供的方法
from sklearn.metrics import confusion_matrix
y_pred = knn.predict(X_test)
confusion_matrix(y_test,y_pred)
array([[165,  36],
       [ 47,  60]])

15-2.png

  1. 使用pandas的crosstab方法
pd.crosstab(y_test, y_pred, rownames=['True'], colnames=['Predicted'], margins=True)
Predicted 0 1 All
TRUE
0 165 36 201
1 47 60 107
All 212 96 308


  1. sklearn中还提供了一种很好的api classification_report

classification_report可以帮助用户自动计算出分类问题中常用的几个metrics的值,包括precision/recall, f1 score

from sklearn.metrics import classification_report
print(classification_report(y_test,y_pred))
     precision    recall  f1-score   support
           0       0.78      0.82      0.80       201
           1       0.62      0.56      0.59       107
    accuracy                           0.73       308
   macro avg       0.70      0.69      0.70       308
weighted avg       0.73      0.73      0.73       308
  1. ROC

ROC、AUC可以排除由于训练样本中的类别不均衡导致的我们最后对模型进行评估的时候的影响

from sklearn.metrics import roc_curve
y_pred_proba = knn.predict_proba(X_test)[:,1]
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
plt.plot([0,1],[0,1],'k--')
plt.plot(fpr,tpr, label='Knn')
plt.xlabel('fpr')
plt.ylabel('tpr')
plt.title('Knn(n_neighbors=7) ROC curve')
plt.show()

15-3.png

from sklearn.metrics import roc_auc_score
roc_auc_score(y_test,y_pred_proba)
0.7345050448691124

1.2 使用sklearn进行超参数调优

  • GridSearch
  • 本例子中,只有一个参数n_neighbors,也就是我们预定义的要分多少类。
  • 实际使用中,如果参数较多,组合较多,这种方式可能会很慢
from sklearn.model_selection import GridSearchCV
param_grid = {'n_neighbors':np.arange(1,50)}
knn = KNeighborsClassifier()
knn_cv= GridSearchCV(knn,param_grid,cv=5)
knn_cv.fit(X,y)
GridSearchCV(cv=5, estimator=KNeighborsClassifier(),
             param_grid={'n_neighbors': array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
       35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])})
knn_cv.best_score_
0.7578558696205755
knn_cv.best_params_
{'n_neighbors': 14}

从上面的例子中可以看出,k=14的时候,当前的KNN算法可以在当前的数据集取得最好的分类效果

1.3 使用pipeline

  • 可以使用sklearn提供的pipeline功能将一些顺序执行的模块串起来,这样代码可以更加简洁
  • 本例中,将会使用pipeline实现下面的事情
  1. 数据标准化(scaler)
  2. 数据降维(PCA)
  3. 训练逻辑回归模型
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn import datasets
pca = PCA()
scaler = StandardScaler()
logistic = LogisticRegression(max_iter=10000, tol=0.1)
pipe = Pipeline(steps=[("scaler", scaler), ("pca", pca), ("logistic", logistic)])
X_digits, y_digits = datasets.load_digits(return_X_y=True)
param_grid = {
    "pca__n_components": [5, 15, 20,25,30,50,55, 60],
    "logistic__C": np.logspace(-4, 4, 8),
}
search = GridSearchCV(pipe, param_grid, n_jobs=2)
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)
pca.fit(X_digits)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(12, 12))
ax0.plot(
    np.arange(1, pca.n_components_ + 1), pca.explained_variance_ratio_, "+", linewidth=2
)
ax0.set_ylabel("PCA explained variance ratio")
ax1.plot(
    np.arange(1, pca.n_components_ + 1), search.cv_results_["mean_test_score"], "*", linewidth=2
)
ax1.set_ylabel("Classification Accuracy")
ax0.axvline(
    search.best_estimator_.named_steps["pca"].n_components,
    linestyle=":",
    label="n_components chosen",
)
ax1.axvline(
    search.best_estimator_.named_steps["pca"].n_components,
    linestyle=":",
    label="n_components chosen",
)
Best parameter (CV score=0.925):
{'logistic__C': 0.2682695795279725, 'pca__n_components': 55}
<matplotlib.lines.Line2D at 0x7fdfe5e612b0>

16-1.png

从上面的图中可以知道,在n_components=55也就是降维到55维度的时候,分类的效果最好

其他

1. sklearn还提供了一系列用于文本处理的工具包和transformer。基于这些工具可以方便的对文本数据进行encoding,分类
2. sklearn提供了一系列基本的统计学算法模型的API,可以很方便的直接去引用。比如XGBoost,naive_bayes,SVM等等
相关实践学习
使用PAI-EAS一键部署ChatGLM及LangChain应用
本场景中主要介绍如何使用模型在线服务(PAI-EAS)部署ChatGLM的AI-Web应用以及启动WebUI进行模型推理,并通过LangChain集成自己的业务数据。
机器学习概览及常见算法
机器学习(Machine Learning, ML)是人工智能的核心,专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能,它是使计算机具有智能的根本途径,其应用遍及人工智能的各个领域。 本课程将带你入门机器学习,掌握机器学习的概念和常用的算法。
相关文章
|
机器学习/深度学习 数据可视化 数据挖掘
PyTorch Geometric (PyG) 入门教程
PyTorch Geometric是PyTorch1的几何图形学深度学习扩展库。本文旨在通过介绍PyTorch Geometric(PyG)中常用的方法等内容,为新手提供一个PyG的入门教程。
PyTorch Geometric (PyG) 入门教程
|
12月前
|
机器学习/深度学习 数据采集 分布式计算
Lesson 6.1 Scikit-Learn 快速入门
Lesson 6.1 Scikit-Learn 快速入门
|
机器学习/深度学习 人工智能 自然语言处理
【DSW Gallery】基于EasyNLP的中文信息抽取
EasyNLP提供多种模型的训练及预测功能,旨在帮助自然语言开发者方便快捷地构建模型并应用于生产。本文以中文信息抽取为例,为您介绍如何在PAI-DSW中基于EasyNLP快速使用K-Global Pointer算法进行中文信息抽取模型的训练、评估、推理。
【DSW Gallery】基于EasyNLP的中文信息抽取
|
算法 PyTorch 算法框架/工具
【DSW Gallery】基于EasyCV的视频分类示例
EasyCV是基于Pytorch,以自监督学习和Transformer技术为核心的 all-in-one 视觉算法建模工具,并包含图像分类,度量学习,目标检测,姿态识别等视觉任务的SOTA算法。本文以视频分类为例,为您介绍如何在PAI-DSW中使用EasyCV。
【DSW Gallery】基于EasyCV的视频分类示例
|
人工智能 并行计算 算法
【DSW Gallery】基于MOCOV2的自监督学习示例
EasyCV是基于Pytorch,以自监督学习和Transformer技术为核心的 all-in-one 视觉算法建模工具,并包含图像分类,度量学习,目标检测,姿态识别等视觉任务的SOTA算法。本文以自监督学习-MOCO为例,为您介绍如何在PAI-DSW中使用EasyCV。
【DSW Gallery】基于MOCOV2的自监督学习示例
|
机器学习/深度学习 人工智能 编解码
【DSW Gallery】基于EasyNLP-Diffusion模型的中文文图生成
EasyNLP提供多种模型的训练及预测功能,旨在帮助自然语言开发者方便快捷地构建模型并应用于生产。本文简要介绍文图生成的技术,以及如何在PAI-DSW中基于EasyNLP使用diffusion model进行finetune和预测评估。
【DSW Gallery】基于EasyNLP-Diffusion模型的中文文图生成
|
Shell 开发者 Python
【DSW Gallery】Jupyter简介
JupyterNotebook是一个用于编写Jupyter Notebook的Python环境。本文介绍Jupyter Notebook的常用使用技巧,包括shell命令,测试运行时间等使用方法。
【DSW Gallery】Jupyter简介
|
自然语言处理 Shell 开发者
【DSW Gallery】基于EasyNLP的中文新闻标题生成
EasyNLP提供多种模型的训练及预测功能,旨在帮助自然语言开发者方便快捷地构建模型并应用于生产。本文以中文新闻标题生成为例,为您介绍如何在PAI-DSW中使用EasyNLP。
【DSW Gallery】基于EasyNLP的中文新闻标题生成
|
机器学习/深度学习 运维 算法
【DSW Gallery】使用Tensorflow来构建AutoEncoder
本文基于TensorFlow 1.x版本,实现了一个自编码器。自编码器是一个应用比较广泛的神经网络。他可以用来做非监督的异常检测,也可以用在特征工程之中,衡量feature之间的高阶非线性关系等等。
【DSW Gallery】使用Tensorflow来构建AutoEncoder
|
机器学习/深度学习 人工智能 分布式计算
【DSW Gallery】DSW Gallery
DSW Gallery提供了AI研发场景下丰富的案例和解决方案,内容涵盖如: Jupyter, 数据分析,机器学习,深度学习,PAI产品说明, SDK使用说明,以及行业解决方案),支持一键在DSW中启动和运行,帮助您快速了解云原生下AI研发流程,熟练使用PAI的各种工具,提升开发效率和质量。
【DSW Gallery】DSW Gallery

热门文章

最新文章