Abstract:这本书面向的是对机器学习和数据挖掘实践及竞赛感兴趣的读者,以python为基础从零开始,在不涉及数学模型和复杂编程知识的前提下,逐步学习和掌握机器学习、数据挖掘、自然语言处理工具,如scikit-learn、NLTK、Pandas、TensorFlow等。
btw:欢迎关注 ~
Github: https://github.com/ScarlettYellow
个人博客:https://scarletthuang.cn/
全书分为4章:
简介篇:机器学习概念和python编程知识
基础篇:如何使用scikit-Learn作为基础机器学习工具
进阶篇:怎样借助高级技术或模型提高机器学习系统的性能
竞赛篇:如何完成kaggle竞赛
1.简介篇
1.1 机器学习
任务:
监督学习 (supervised Learning):预测事物未知表现,包括分类问题(classification)、回归问题(regression),根据目标预测变量类型的不同可分为:
分类问题:预测类别(已知数量,类别离散),如已知一个人的身高、体重和三围等数据预测其性别
回归问题:预测连续变量,如根据房屋的面积、地理位置、建筑年代等预测销售价格(C.V)
无监督学习(Unsupervised Learning):倾向于分析事物本身特性,常用技术:降维(Dimensionality Reduction), 聚类 (Clustering)
数据降维:对事物的特性进行压缩和筛选,如对图像进行降维以保留最有区分度的像素组合
聚类:依赖于数据的相似性从而把相似的数据样本划分为一个簇(区别于分类,簇的数量和含义非已知),如电子商务中对用户信息和购买习惯进行聚类分析,一旦找到数量多且背景相似客户群,则可针对其投放广告促销
经验:
特征(feature):反映数据内在规律的信息
监督学习中的经验:特征、标记(label)
用一个特征向量描述一个数据样本
label的表现形式取决于监督学习的种类
数据标注需耗费大量资源,故数据量少
训练集(training set):带label的数据集,用来训练学习系统
无监督学习中的经验:无label故无法做预测,但适合对数据结构作分析
原始数据转化为特征向量的过程中会遭遇多种数据类型(需全部转化为具体数值运算):
类别型特征(categorical)
数值型特征(numerical)
缺失数据(missing value)
性能(performance):
评价学习模型完成任务质量的指标
分类问题:准确性(accuracy)——预测正确类别的百分比
回归问题:衡量预测值与实际值之间的偏差大小
测试集(testing set):与TS具备相同特征,没有被用于训练
how:用测试集测试预测的准确率(用具备相同特征的数据,模型在测试集上的预测结果与正确结果进行比对)
1.2 PYTHON编程库
python
numpy:高级数学运算机制,高效向量与矩阵运算
scipy:在numpy基础上更强大、应用更广泛的科学计算包,依赖numpy
Matplotlib:数据分析与可视化的绘图工具包
scikit-learn:封装了大量ML模型
pandas:数据处理和分析的工具包
1.3 PYTHON基础
常用数据类型
数字
布尔值
字符串
元组(turple):以()表征,元组数据不允许修改
列表:以[]表征,允许修改列表数据
字典(dict):以key-value构成,以{}表征
数据运算
流程控制
函数设计
2.基础篇
Abstract:机器学习模型的使用方法、性能评价和优缺点。
模型阐述角度:模型简介、数据描述 、编程实践、性能测评、特点分析。
2.1 监督学习经典模型
2.1.1 监督学习任务的基本流程
准备训练数据——抽取所需特征、形成特征向量(Feature Vectors)——把特征向量连同labels一起送入学习算法(Machine Learning Algorithm)中——训练出一个预测模型(Predictive Model)
采用同样特征抽取方法作用于测试集、得到用于测试的特征向量——使用预测模型对待测试的特征向量进行预测并得到结果(Expected Label)
2.1.2 分类学习
分类问题:
二分类(binary classification):二选一
多分类(multiclass classification):判断一个样本是否同时属于多个不同类别
2.1.2.1 线性分类器(linear classifiers)
线性分类器:假设特征与分裂结构存在线性关系的模型,通过累加计算每个维度的特征与各自权重的乘积来帮助类别决策(基于线性假设的分类器)
logistics regression模型:
x = <x1,x2,...,xn>:n维特征向量w = <w1,w2,...,wn>: 特征向量对应的权重/系数(coefficient)b:截距(intercept),为避免过原点
线性关系表示为:
我们所需处理的二分类问题中f∈(0,1),故需将函数的f∈R映射到(0,1),故有logistics函数:
综上,若将z替换为f,则logistics regression模型如下:
该模型处理一个待分类的特征向量:若z=0,则g=0.5;若z<0,则g<0.5,此FV被判别为一类,反之则为另一类。
当使用一组m个用于训练的FV 和其对应的分类目标 ,我们希望该模型能在这组训练集上取得最大似然估计(Maximum Likelihood)的概率 , 或者说至少要在训练集上表现为:
为学习到决定模型的参数(parameters),即系数w和截距b,我们普遍使用一种精确计算的解析算法和一种快速估计的随机梯度上升算法(stochasitic gradient ascend)。
1.任何模型在训练集上的表现都不一定能代表其最终在未知待测数据集上的性能,但至少要先保证模型可以被训练集优化。
2.SGA和SGD都属于梯度法迭代渐进估计参数的过程,梯度上升(SGA)用于目标最大化,梯度下降(SGD)用于目标最小化。
数据集说明:
数据集地址:Address
描述:良/恶性肿瘤预测数据
目的:分类预测,并使用精细的测评指标评价模型性能
1.数据预处理
import pandas as pd import numpy as np # create feature list column_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion','Single Epithelical Cell Size','Bare Nuclei','Bland Chromatin','Normal Nucleoli','Mitoses','Class'] # read data data = pd.read_csv('/Users/scarlett/repository/projects/breast_cancer/breast_cancer.csv',names=column_names)
# clean data data = data.replace(to_replace='?', value=np.nan) data = data.dropna(how='any') print data.shape print data.info()
output:
(683, 11) <class 'pandas.core.frame.DataFrame'> Int64Index: 683 entries, 0 to 698 Data columns (total 11 columns): Sample code number 683 non-null int64 Clump Thickness 683 non-null int64 Uniformity of Cell Size 683 non-null int64 Uniformity of Cell Shape 683 non-null int64 Marginal Adhesion 683 non-null int64 Single Epithelical Cell Size 683 non-null int64 Bare Nuclei 683 non-null object Bland Chromatin 683 non-null int64 Normal Nucleoli 683 non-null int64 Mitoses 683 non-null int64 Class 683 non-null int64 dtypes: int64(10), object(1) memory usage: 64.0+ KB None
由于原始数据没有提供对应的测试样本,故需要对带有label的样本进行分割,一般是25%作为测试集,75%作为训练集。
2.准备训练、测试数据
# prepare training set and testing set # use train_test_split in sklearn to split data from sklearn.cross_validation import train_test_split # randomly sample 25% for testing,75% for training X_train,X_test,y_train,y_test = train_test_split(data[column_names[1:10]],data[column_names[10]],test_size=0.25,random_state=33) # check number and class print y_train.value_counts() print y_test.value_counts()
2 344 4 168 Name: Class, dtype: int64 2 100 4 71 Name: Class, dtype: int64
训练样本:512条(344条良性肿瘤数据+168恶性肿瘤数据),测试样本171条(100+71)
sklearn.model_selection.train_test_split解释
from sklearn.cross_validation import train_test_split
一般形式:X_train,X_test, y_train, y_test = cross_validation.train_test_split(train_data,train_target,test_size=0.4, random_state=0)
参数解释:
train_data:所要划分的样本特征集
train_target:所要划分的样本结果
test_size:样本占比,如果是整数的话就是样本的数量
random_state:是随机数的种子
随机数种子:其实就是该组随机数的编号,在需要重复试验的时候,保证得到一组一样的随机数。比如你每次都填1,其他参数一样的情况下你得到的随机数组是一样的。但填0或不填,每次都会不一样。
随机数的产生取决于种子,随机数和种子之间的关系遵从以下两个规则:
种子不同,产生不同的随机数;种子相同,即使实例不同也产生相同的随机数。
3.使用线性分类模型进行分类预测
from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.linear_model import SGDClassifier # standarlize data,make sure DE=1,EX=0,so that the outcome wont be influenced by big feature ss = StandardScaler() X_train=ss.fit_transform(X_train) X_test=ss.transform(X_test) # init logisticregression and SGDClassifier lr = LogisticRegression() sgdc = SGDClassifier() # use fit() of LR to train paras lr.fit(X_train,y_train) # use trained lr to predict X_test lr_y_predict = lr.predict(X_test) # use fit() of SGDC to train paras, use trained lr to predict X_test sgdc.fit(X_train,y_train) sgdc_y_predict=sgdc.predict(X_test) print sgdc_y_predict print lr_y_predict
output:
[4 2 4 4 2 2 2 4 2 2 2 2 4 2 4 4 4 4 4 2 2 4 4 2 4 4 2 2 4 4 4 4 4 4 4 4 2 4 4 4 4 4 2 4 2 2 4 2 2 4 4 2 2 2 4 2 2 2 2 2 4 4 2 2 2 4 2 2 2 2 4 2 2 4 2 2 2 2 4 2 2 2 4 2 2 2 4 2 4 2 4 4 2 2 2 2 4 4 2 2 2 4 2 2 4 2 2 2 2 2 4 2 2 2 2 2 2 4 2 2 4 4 2 4 2 2 2 4 2 2 4 4 2 4 4 2 2 2 2 4 2 4 2 4 2 2 2 2 2 4 4 2 4 4 2 4 2 2 2 2 4 4 4 2 4 2 2 4 2 4 4] [2 2 4 4 2 2 2 4 2 2 2 2 4 2 4 4 4 4 4 2 2 4 4 2 4 4 2 2 4 4 4 4 4 4 4 4 2 4 4 4 4 4 2 4 2 2 4 2 2 4 4 2 2 2 4 2 2 2 2 2 4 4 2 2 2 4 2 2 2 2 4 2 2 2 2 2 2 4 4 2 2 2 4 2 2 2 4 2 4 2 4 4 2 2 2 2 4 4 2 2 2 4 2 2 4 2 2 2 2 2 4 2 2 2 2 2 2 4 2 2 4 4 2 4 2 2 2 4 2 2 4 4 2 4 4 2 2 2 2 4 2 4 2 4 2 2 2 2 2 4 4 2 4 4 2 4 2 2 2 2 4 4 4 2 4 2 2 4 2 4 4]
混淆矩阵:二分类任务中,预测结果(predicted condition)与正确标记(true condition)之间存在4种不同的组合:
真阳性(true positive):预测正确的恶性肿瘤
真阴性
假阳性(false positive):误判为恶性肿瘤
假阴性
4.性能评价
性能评价指标
评价指标1:准确率
评价指标2:召回率(Recall)和精确率(Precision),F1 指标(F1 measure)
F1指标:两指标的调和平均数,以综合考量两指标
对肿瘤识别,我们更关心召回率,即应该被正确识别的恶性肿瘤的百分比。
使用线性分类模型进行肿瘤预测任务的性能分析
from sklearn.metrics import classification_report # 使用逻辑回归模型自带的评分函数score获得模型在测试集上的准确性结果 print 'Acurracy of LR Classifier:', lr.score(X_test,y_test) # use classification_report to get the other 3 measures of LR print classification_report(y_test,lr_y_predict,target_names=['Benign','Malignant'])
output:
Acurracy of LR Classifier: 0.9883040935672515 precision recall f1-score support Benign 0.99 0.99 0.99 100 Malignant 0.99 0.99 0.99 71 avg / total 0.99 0.99 0.99 171
# 使用随机梯度下降模型自带的score评分函数模型在测试集上的准确性结果 print 'Acurracy of SDG Classifier:', sgdc.score(X_test,y_test) # use classification_report to get the other 3 measures of SGDC print classification_report(y_test,lr_y_predict,target_names=['Benign','Malignant'])
output:
Acurracy of SDG Classifier: 0.9824561403508771 precision recall f1-score support Benign 0.99 0.99 0.99 100 Malignant 0.99 0.99 0.99 71 avg / total 0.99 0.99 0.99 171
综上,发现,LR比SGDC在测试集上有更高的准确性,因为sklearn中采用解析的方式精确计算LR的参数,而使用梯度法估计SGDC的参数
特点分析:
LR model:精确解析参数,计算时间长但模型性能略高
SGDC model:随机梯度上升算法估计参数,计算时间短但模型性能略低
训练数据规模在10万量级以上的数据,考虑到时间耗用,推荐使用随机梯度算法对模型参数进行估计
2.1.2.2 支持向量机(Suport Vector Classifier)(分类)
模型介绍:
1.不是在所有数据集上SVM的表现一定都优于普通线性模型或其他模型,而是假设未知待测数据也如训练数据一样分布,则SVM可帮助找到最佳分类器;实际应用数据总是有偏差的。
2.上图,H1表现不佳(有分类错误);H2与H3都表现完美。
3.但,分类模型的选取中我们需要更加关注如何最大限度为未知分布的数据集提供足够的待预测空间。如有一个黑色样本稍偏离H2,则会很可能被误判为白色,造成误差,而H3则可为样本提供更多的容忍度,故H3优于H2.
数据描述:
应用场景:邮政系统对收信人邮编进行识别与分类,以便确定信件的投送地;邮编多数为手写
任务:手写数字图片识别与分类
数据集:利用SVM处理sklearn内部集成的手写体数字图片数据集
1.读取数据
from sklearn.datasets import load_digits # 将数据存储在digits变量中 digits=load_digits() # 检查数据规模与特征维度 print digits.data.shape
Output:
(1797, 64)
(1797,64):有1797条图像数据,每幅图片由8*8=64的像素矩阵表示
2.分割数据集
from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test=train_test_split(digits.data,digits.target,test_size=0.25,random_state=33) print y_train.shape print y_test.shape
Output:
(1347,) (450,)
3.使用SVM对手写数字图像进行识别
from sklearn.preprocessing import StandardScaler # 从SVM里导入基于线性假设的SVM分类器LinearSVC from sklearn.svm import LinearSVC # 对训练和测试的特征数据进行标准化 ss=StandardScaler() X_train=ss.fit_transform(X_train) X_test=ss.transform(X_test) # 初始化LinearSVC lsvc=LinearSVC() # 进行模型训练 lsvc.fit(X_train,y_train) # 利用训练好的模型对测试样本的数字类别进行预测,预测结果存在y_predict中 y_predict=lsvc.predict(X_test) print y_predict
Output:
[1 3 7 3 2 4 6 1 4 0 4 7 9 5 2 8 3 6 7 0 6 0 8 3 0 6 2 3 0 9 0 2 0 6 9 1 1 5 8 0 6 1 5 8 9 5 1 6 2 6 6 7 6 7 7 2 7 8 0 7 3 6 3 9 6 6 5 5 4 2 9 3 7 6 5 7 2 8 1 2 2 8 1 1 6 3 5 0 0 1 6 7 6 8 9 7 0 0 9 8 0 8 2 3 6 1 9 9 1 7 3 9 8 8 5 9 5 1 1 7 9 3 3 2 8 1 3 8 6 4 0 0 0 7 1 5 5 1 8 5 1 8 1 6 9 9 4 5 7 5 2 1 2 5 8 7 7 5 1 9 6 9 8 0 6 1 2 1 5 7 8 9 6 8 4 1 0 0 9 8 7 2 8 6 4 8 9 4 2 6 1 8 5 6 7 5 1 9 2 8 3 2 9 4 3 5 5 6 2 4 3 2 6 4 8 5 8 0 8 8 6 3 2 3 0 5 7 1 3 9 3 2 1 6 6 5 1 9 7 2 4 5 2 1 3 1 1 2 1 7 0 1 2 2 1 2 4 9 6 6 3 9 2 8 1 5 5 1 8 6 2 5 6 0 1 4 2 1 8 9 4 3 0 6 8 3 3 2 0 2 0 6 5 6 6 4 6 1 8 3 4 1 3 5 1 4 9 8 7 5 1 1 3 7 8 8 3 7 4 0 7 2 8 7 1 9 4 5 3 5 2 5 1 3 0 5 8 4 7 6 9 9 3 3 4 0 6 4 7 0 6 1 2 3 3 4 5 3 3 5 2 0 9 7 1 5 5 8 4 4 3 6 2 5 1 0 6 1 5 8 4 7 6 4 3 4 0 3 0 1 2 8 0 5 4 5 2 2 9 6 9 8 0 8 8 2 4 6 5 6 4 3 9 8 9 7 1 7 9 4 1 9 9 5 9 8 0 8 2 5 1 4 2 6 3 7 9 3 7 4 3 7 1 8 8 9 5 3 6 6]
4.性能测评
同样使用precision、recall、accuracy、F1这四个测度来评价性能
# 使用模型自带的评估函数进行准确性测评 print 'The Accuracy of Linear SVC is:',lsvc.score(X_test,y_test)
Output:
The Accuracy of Linear SVC is: 0.9533333333333334
# 使用模型自带的classification_report模块对预测结果做更精细的分析 from sklearn.metrics import classification_report print classification_report(y_test,y_predict,target_names=digits.target_names.astype(str))
Output:
precision recall f1-score support
0 0.92 1.00 0.96 35 1 0.96 0.98 0.97 54 2 0.98 1.00 0.99 44 3 0.93 0.93 0.93 46 4 0.97 1.00 0.99 35 5 0.94 0.94 0.94 48 6 0.96 0.98 0.97 51 7 0.92 1.00 0.96 35 8 0.98 0.84 0.91 58 9 0.95 0.91 0.93 44 avg / total 0.95 0.95 0.95 450
由上可知,SVM可提供较高的手写数字识别性能,平均各项指标都在95%左右。
多分类:判断一个样本是否同时属于多个不同类别;将多分类看成N个二分类任务。
如本例的分类目标有10个类别,即0—9这10个数字,因此无法直接计算三指标。故我们逐一评估每个类别的这三指标,把所有其他类别统一看做阴性(负)样本,则创造了10个二分类任务。
特点分析:
可帮助在海量甚至高维度数据中筛选对预测任务最有效的少数训练样本,节省数据内存,提高模型预测性能
但计算代价高(CPU资源与计算时间)
2.1.2.3 朴素贝叶斯(Naive Bayes)(分类)
模型介绍:基于贝叶斯理论的分类器
会单独考量每一维度特征被分类的条件概率,进而综合这些概率并对其所在的特征向量做出分类预测
基本数学假设:各个维度上的特征被分类的条件概率之间是相互独立的
若采用概率模型来表述,则定义为某一n维特征向量, 为改特征向量x所有k种可能的类别,记 为特征向量x属于类别的概率,根据贝叶斯概率公式:
我们的目标是寻找所有 中 最大的,即;并考虑到 对于同一样本都是相同的,因此可忽略不计。故:
若每一种特征可能的取值均为0或1,在无特殊假设的条件下,计算 需要对 个可能的参数进行估计:
但由于朴素贝叶斯模型的特征类别独立假设,故 ;若依然每种特征可能的取值只有2种,则只需要估计个参数,即 .
为估计每个参数的概率,采用如下公式,且改用频率比近似计算概率:
数据描述
应用场景:互联网新闻文本分类
数据集:20类新闻文本
1.读取数据
from sklearn.datasets import fetch_20newsgroups # 即时从网上下载数据 news=fetch_20newsgroups(subset='all') print len(news.data) print news.data[0]
output:
18846 From: Mamatha Devineni Ratnam <mr47+@andrew.cmu.edu> Subject: Pens fans reactions Organization: Post Office, Carnegie Mellon, Pittsburgh, PA Lines: 12 NNTP-Posting-Host: po4.andrew.cmu.edu
I am sure some bashers of Pens fans are pretty confused about the lack of any kind of posts about the recent Pens massacre of the Devils. Actually, I am bit puzzled too and a bit relieved. However, I am going to put an end to non-PIttsburghers' relief with a bit of praise for the Pens. Man, they are killing those Devils worse than I thought. Jagr just showed you why he is much better than his regular season stats. He is also a lot fo fun to watch in the playoffs. Bowman should let JAgr have a lot of fun in the next couple of games since the Pens are going to beat the pulp out of Jersey anyway. I was very disappointed not to see the Islanders lose the final regular season game. PENS RULE!!!
数据没有被设定特征,也无数字化的量度,因此需要在被训练前对数据做进一步处理。
2.分割数据
from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test=train_test_split(news.data,news.target,test_size=0.25,random_state=33)
3.使用朴素贝叶斯分类器对新闻文本数据进行类别预测
先将文本转化为特征向量
再利用朴素贝叶斯模型从训练数据中估计参数
最后利用这些概率参数对同样转化为特征向量的测试集进行类别预测
# 导入用于文本特征向量转换模块 from sklearn.feature_extraction.text import CountVectorizer vec=CountVectorizer() X_train=vec.fit_transform(X_train) X_test=vec.transform(X_test) # 导入naive bayes from sklearn.naive_bayes import MultinomialNB # 初始化NB mnb=MultinomialNB() # 利用训练数据对模型参数进行估计 mnb.fit(X_train,y_train) # 对测试样本进行类别预测,结果存储在变量y_predict中 y_predict=mnb.predict(X_test)
4.性能评估
from sklearn.metrics import classification_report print 'The Accuracy of NBC is:',mnb.score(X_test,y_test) print classification_report(y_test,y_predict,target_names=news.target_names)
output:
The Accuracy of NBC is: 0.8397707979626485 precision recall f1-score support alt.atheism 0.86 0.86 0.86 201 comp.graphics 0.59 0.86 0.70 250 comp.os.ms-windows.misc 0.89 0.10 0.17 248 comp.sys.ibm.pc.hardware 0.60 0.88 0.72 240 comp.sys.mac.hardware 0.93 0.78 0.85 242 comp.windows.x 0.82 0.84 0.83 263 misc.forsale 0.91 0.70 0.79 257 rec.autos 0.89 0.89 0.89 238 rec.motorcycles 0.98 0.92 0.95 276 rec.sport.baseball 0.98 0.91 0.95 251 rec.sport.hockey 0.93 0.99 0.96 233 sci.crypt 0.86 0.98 0.91 238 sci.electronics 0.85 0.88 0.86 249 sci.med 0.92 0.94 0.93 245 sci.space 0.89 0.96 0.92 221 soc.religion.christian 0.78 0.96 0.86 232 talk.politics.guns 0.88 0.96 0.92 251 talk.politics.mideast 0.90 0.98 0.94 231 talk.politics.misc 0.79 0.89 0.84 188 talk.religion.misc 0.93 0.44 0.60 158 avg / total 0.86 0.84 0.82 4712
由上评估结果可知,NBC对4712条新闻文本测试样本分类的准确性约为83.977%,平均精确率、召回率、F1指标分别为86%、84%、82%。
特点分析:
朴素贝叶斯模型广泛应用在互联网文本分类任务
优点:由于其较强的特征条件独立假设,使得模型预测所需估计的参数规模从幂指数量级向线性量级减少,极大节约内存消耗和计算时间
缺点:同样由于这种强假设的限制,模型训练时无法将各个特征之间的联系考量在内,使该模型在其他数据特征关联性强的分类任务上性能不佳
2.1.2.4 K近邻(k-Nearest Neighbor,KNN)(分类)
模型介绍:
最简单的ML算法之一
假设有一些携带分类标记的训练样本,分布于特征空间中;蓝色、绿色样本点各自代表其类别;对一个待分类的红色测试样本点,未知其类别,按照“近朱者赤近墨者黑”的说法,我们需要寻找与这个待分类的样本在特征空间中距离最近的K个已标记样本作为参考,来帮助做出分类决策
思路:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。
数据描述:
应用场景:使用K近邻算法对生物物种进行分类
数据集:Iris
1.读取数据集
from sklearn.datasets import load_iris iris=load_iris() print iris.data.shape print iris.DESCR
output:
(150, 4) Iris Plants Database ==================== Notes ----- Data Set Characteristics: :Number of Instances: 150 (50 in each of three classes) :Number of Attributes: 4 numeric, predictive attributes and the class :Attribute Information: - sepal length in cm - sepal width in cm - petal length in cm - petal width in cm - class: - Iris-Setosa - Iris-Versicolour - Iris-Virginica :Summary Statistics: ============== ==== ==== ======= ===== ==================== Min Max Mean SD Class Correlation ============== ==== ==== ======= ===== ==================== sepal length: 4.3 7.9 5.84 0.83 0.7826 sepal width: 2.0 4.4 3.05 0.43 -0.4194 petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) ============== ==== ==== ======= ===== ==================== :Missing Attribute Values: None :Class Distribution: 33.3% for each of 3 classes. :Creator: R.A. Fisher :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov) :Date: July, 1988 This is a copy of UCI ML iris datasets. http://archive.ics.uci.edu/ml/datasets/Iris The famous Iris database, first used by Sir R.A Fisher This is perhaps the best known database to be found in the pattern recognition literature. Fisher's paper is a classic in the field and is referenced frequently to this day. (See Duda & Hart, for example.) The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2; the latter are NOT linearly separable from each other. References ---------- - Fisher,R.A. "The use of multiple measurements in taxonomic problems" Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to Mathematical Statistics" (John Wiley, NY, 1950). - Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis. (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218. - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System Structure and Classification Rule for Recognition in Partially Exposed Environments". IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. PAMI-2, No. 1, 67-71. - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions on Information Theory, May 1972, 431-433. - See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II conceptual clustering system finds 3 classes in the data. - Many, many more ...
2.分割数据集
from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.25,random_state=33)
3.使用K近邻算法对iris数据进行类别预测
from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier ss=StandardScaler() X_train=ss.fit_transform(X_train) X_test=ss.transform(X_test) knc=KNeighborsClassifier() knc.fit(X_train,y_train) y_predict=knc.predict(X_test) print y_predict
output:
[1 1 0 1 1 2 0 0 2 2 2 0 2 1 2 1 1 0 1 2 0 0 2 0 1 2 1 1 2 1 1 1 2 2 2 2 2 1]
4.性能评估
print 'The Accuracy of KNC is:',knc.score(X_test,y_test) from sklearn.metrics import classification_report print classification_report(y_test,y_predict,target_names=iris.target_names)
output:
The Accuracy of KNC is: 0.8947368421052632 precision recall f1-score support setosa 1.00 1.00 1.00 8 versicolor 0.73 1.00 0.85 11 virginica 1.00 0.79 0.88 19 avg / total 0.92 0.89 0.90 38
特点分析:
k近邻算法是非常直观简单的模型
是无参数模型:没有参数训练过程,即未通过任何学习算法分析数据,而只是根据测试样本在训练数据中的分布做出分类
缺点:高计算复杂度和内存消耗;平方级别的算法复杂度(每处理一个测试样本就要对所有训练样本进行遍历,逐一计算相似度、排序且选取K个最近邻训练样本的标记,进而做出分类决策)
当然也有KD-Tree这样的数据结构通过“空间换时间”思想节省KNN的决策时间
2.1.2.5 决策树(Decision Tree)(分类)
模型介绍:
描述非线性关系
LR和SVM都要求被学习的数据特征和目标之间遵照线性假设,但现实场景下这种假设不存在。如用年龄预测流感死亡率,年龄与死亡率之间不存在线性关系。
决策树节点(node)——数据特征
各节点下的分支——特征值的分类
决策树的所有叶子节点——显示模型的决策结果
使用多种不同特征组合搭建多层决策树时,需考虑特征节点的选取顺序,常用的度量方式有信息熵(Information Gain)和基尼不纯性(Gini Impurity)
数据描述
借助决策树模型预测泰坦尼克号乘客生还情况
数据集:乘客信息
1.数据查验
import pandas as pd <