机器学习之sklearn基础教程!

点击此处查看最新的网赚项目教程

本次分享是基于scikit-learn工具包的基本分类方法,包括常见的Logisitic Regression、支持向量机、决策树、随机森林以及K近邻方法KNN。本文在基于读者已经基本了解这些基本算法的原理以及推导的基础上,使用sklearn工具包进行算法实践,如果大家没有掌握基本算法原理,文中也会给出一些优秀的链接方便大家学习。如果大家对基本分类算法的基本原理有需求,可以在评论区写下自己的需求,我们会根据大家的意见推出相应的分享。

机器学习算法主要步骤有:

本次分享主要把目光聚集在"选择分类器并优化算法",我们将用学术界和工业界常用的机器学习库sklearn,对算法进行实践。

本文内容:

1. 数据准备

我们使用鸢尾花数据集,进行分析考核可视化

# 引入数据from sklearn import datasetsimport numpy as np
iris = datasets.load_iris()X = iris.data[:,[2,3]]y = iris.targetprint("Class labels:",np.unique(y)) #打印分类类别的种类

Class labels: [0 1 2]

切分训练数据和测试数据

# 切分训练数据和测试数据from sklearn.model_selection import train_test_split## 30%测试数据,70%训练数据,stratify=y表示训练数据和测试数据具有相同的类别比例X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1,stratify=y)

数据标准化

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()## 估算训练数据中的mu和sigmasc.fit(X_train)## 使用训练数据中的mu和sigma对数据进行标准化X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)

定制可视化函数:画出决策边界图(只有在2个特征才能画出来)

## 画出决策边界图(只有在2个特征才能画出来)import matplotlib.pyplot as plt%matplotlib inlinefrom matplotlib.colors import ListedColormap
def plot_decision_region(X,y,classifier,resolution=0.02): markers = ('s','x','o','^','v') colors = ('red','blue','lightgreen','gray','cyan') cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface x1_min,x1_max = X[:,0].min()-1,X[:,0].max()+1 x2_min,x2_max = X[:,1].min()-1,X[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,resolution), np.arange(x2_min,x2_max,resolution)) Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1,xx2,Z,alpha=0.3,cmap=cmap) plt.xlim(xx1.min(),xx1.max()) plt.ylim(xx2.min(),xx2.max())
# plot class samples for idx,cl in enumerate(np.unique(y)): plt.scatter(x=X[y==cl,0], y = X[y==cl,1], alpha=0.8, c=colors[idx], marker = markers[idx], label=cl, edgecolors='black')

2. 基于逻辑回归的分类概率建模2.1 原理介绍

可参考阅读:

2.2 参考文档详细解释

class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)

2.2.1可选参数

2.2.2 返回标签

from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=100.0,random_state=1)lr.fit(X_train_std,y_train)print("Class:",lr.classes_)print("Coef:",lr.coef_)print("intercept",lr.intercept_)print("n_iter",lr.n_iter_)

统计常用软件工具_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计工具应用

plot_decision_region(X_train_std,y_train,classifier=lr,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计常用软件工具_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计工具应用

预测:

# 预测## 预测前三样本在各个类别的概率print("前三样本在各个类别的预测概率为:n",lr.predict_proba(X_test_std[:3,:]))print("n============================")## 获得前三个样本的分类标签print("n前三样本在各个类别的预测类别为:n",lr.predict(X_test_std[:3,:]))print("n============================")

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计工具应用_统计常用软件工具

我们可以看到逻辑回归的决策边界是一个线性边界,这也就是为什么逻辑回归作为线性分类模型的原因了。大家不要小瞧线性模型,线性模型在现实生产中还发挥的重要作用,在金融、经济中尤为明显,因为线性模型的模型复杂度较小,它的可解释性很好,能够给决策者决策提供更加强大的依据,而不是像类似于深度学习那些复杂的网络模型一样是个黑箱子。

3. 基于支持向量机的分类模型

3.1 原理介绍

可参考阅读:

3.2 参考文档详细解释

class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)

3.2.1 可选参数

3.2.2可选标签

线性支持向量机:

## 线性支持向量机from sklearn.svm import SVCsvm = SVC(kernel='linear',C=1.0,random_state=1)svm.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计工具应用_统计常用软件工具

使用核函数对非线性分类问题建模(gamma=0.20)

## 使用核函数对非线性分类问题建模(gamma=0.20)svm = SVC(kernel='rbf',random_state=1,gamma=0.20,C=1.0)    ##较小的gamma有较松的决策边界svm.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具_统计工具应用

使用核函数对非线性分类问题建模(gamma=100)

## 使用核函数对非线性分类问题建模(gamma=100)svm = SVC(kernel='rbf',random_state=1,gamma=100.0,C=1.0,verbose=1)   svm.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计工具应用_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具

从不同的gamma取值的图像来看:对于高斯核函数,增大gamma值,将增大训练样本的影响范围,导致决策边界紧缩和波动;较小的gamma值得到的决策边界相对宽松。虽然较大的gamma值在训练样本中有很小的训练误差,但是很可能泛化能力较差,容易出现过拟合。

4. 构建决策树分类器

4.1 原理介绍

可参考阅读:

4.2 参考文档详细解释

class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, presort='deprecated', ccp_alpha=0.0)

4.2.1 可选参数

4.2.2可选标签

决策树分类器:

## 决策树分类器from sklearn.tree import DecisionTreeClassifiertree = DecisionTreeClassifier(criterion='gini',max_depth=4,random_state=1)tree.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=tree,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计常用软件工具_统计工具应用_统计学工具软件,0,0,0,0.0,0,0,0,,-

决策树可视化:

可视化决策树需要安装基本的软件和python库:

从免费下载程序

pip3 install pydotplus

pip3 install graphviz

pip3 install pyparsing

## 决策树可视化from pydotplus import graph_from_dot_datafrom sklearn.tree import export_graphvizdot_data = export_graphviz(tree,filled=True,class_names=['Setosa','Versicolor','Virginica'],                          feature_names=['petal_length','petal_width'],out_file=None)graph = graph_from_dot_data(dot_data)graph.write_png('/home/leo/文档/大四下学期/zhihu/sklearn的基本分类模型详解/tree.png')

统计工具应用_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具

从树的边界来看,决策树在鸢尾花分类问题上表现不错,但是sklearn不提供手工决策树修剪功能。

5. 通过随机森林组合多棵决策树

5.1 原理介绍

可参考阅读:

5.2 参考文档详细解释

class sklearn.ensemble.RandomForestClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None)

5.2.1 可选参数

5.2.2可选标签

使用随机森林分类器:

## 使用随机森林分类器from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(criterion='gini',n_estimators=25,random_state=1,n_jobs=2,verbose=1)forest.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=forest,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具_统计工具应用

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具_统计工具应用

6.K近邻(KNN)6.1 原理介绍

可参考阅读:

6.2 参考文档详细解释

class sklearn.neighbors.KNeighborsClassifier(n_neighbors=5, _, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, *_kwargs)

6.2.1 可选参数

6.2.2可选标签

使用KNN分类器:

## 使用KNN分类器from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=2,p=2,metric="minkowski")knn.fit(X_train_std,y_train)plot_decision_region(X_train_std,y_train,classifier=knn,resolution=0.02)plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.show()

统计工具应用_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具

值得注意的是:KNN容易过拟合,因为在高维空间上,随着维数越来越大,特征空间越来越稀疏,大家可以想象在一个球体里面,大部分的信息集中在球面,那KNN需要找最近的点就会十分困难,那么也就无法合适进行估计。

重磅!

Python遇见机器学习交流群已成立!


额外赠送福利资源!
邱锡鹏深度学习与神经网络,pytorch官方中文教程,利用Python进行数据分析,机器学习学习笔记,pandas官方文档中文版,effective java(中文版)等20项福利资源

统计工具应用_统计常用软件工具_统计学工具软件,0,0,0,0.0,0,0,0,,-

获取方式:进入群后点开群公告即可领取下载链接

统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具_统计工具应用

注意:请大家添加时修改备注为

[学校/公司 + 姓名 + 方向]

例如 —— 哈工大+张三+对话系统。

号主,微商等广告请自觉绕道。谢谢!

推荐阅读

•  开源教程 「nlp-tutorial」!用百行代码搞定各类NLP模型

•  机器学习、数据科学、人工智能、深度学习和统计学之间的区别!

•  做好数据可视化的技巧和原则!

•  深度学习环境配置指南!(Windows、Mac、Ubuntu全讲解)

统计工具应用_统计学工具软件,0,0,0,0.0,0,0,0,,-_统计常用软件工具

———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: qs62318888

主题授权提示:请在后台主题设置-主题授权-激活主题的正版授权,授权购买:RiTheme官网

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注