4.2KNN算法实例2--python机器学习

测试数据的格式仍然和前面使用的身高体重数据一致。不过数据增加了一些:


1.5 40 thin  

1.5 50 fat  

1.5 60 fat  

1.6 40 thin  

1.6 50 thin  

1.6 60 fat  

1.6 70 fat  

1.7 50 thin  

1.7 60 thin  

1.7 70 fat  

1.7 80 fat  

1.8 60 thin  

1.8 70 thin  

1.8 80 fat  

1.8 90 fat  

1.9 80 thin  

1.9 90 fat  


# -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 15:21:20 2016


@author: aijun
"""

Python代码

scikit-learn提供了优秀的KNN算法支持。使用Python代码如下:


import numpy as np
from sklearn import neighbors
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt


#设置当前工作目录
import os
path = "D:\\python数据分析数据\\knn"
os.chdir(path)


#读取数据
data  = []
labels = []
with open("./knn.txt") as ifile:
    for line in ifile:
        tokens = line.strip().split(' ')
        #将自变量添加到data中
        data.append([float(tk) for tk in tokens[:-1]])
        #将因变量添加到labels中        
        labels.append(tokens[-1])
#将列表data转化为数组
x = np.array(data)
#将列表labels转化为数组
labels = np.array(labels)
#按数组长度的将因变量转化为0值的数组
y = np.zeros(labels.shape)


#因变量为因子类型:需要将因变量转化为0、1值(注意:此时因子类型只有两种)
y[labels=='fat'] = 1


#创建训练数据和测试数据
x_train, x_test,  y_train, y_test = train_test_split(x, y,  test_size=0.2)


#创建网格以方便绘制
h = 0.01
x_min, x_max = x[:, 0].min() - 0.1, x[:, 0].max() + 0.1
y_min, y_max = x[:, 1].min() - 1,  x[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), 
                     np.arange(y_min, y_max, h))


#训练KNN分类器
clf = neighbors.KNeighborsClassifier(algorithm="kd_tree")
clf.fit(x_train,  y_train)


#测试结果的打印
answer = clf.predict(x)


#预测结果正确的比率
print(np.mean(answer==y))


#准确率与召回率
precision,  recall, thresholds = precision_recall_curve(y_train,  clf.predict(x_train))
#返回测试数据的概率估计
answer = clf.predict_proba(x)[:, 1]
#print(classification_report(y, answer, target_names=['thin', 'fat']))


#将整个测试空间的分类结果用不同颜色区分开
answer = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
z = answer.reshape(xx.shape)
plt.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.8)


#绘制训练样本
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired)
plt.xlabel(u'身高')
plt.ylabel(u'体重')
plt.show()


结果分析

其输出结果如下:

[ 0.  0.  1.  0. 0.  1.  1.  0.  0.  1.  1.  0. 0.  1.  1.  0.  1.]

[ 0.  1.  1.  0. 0.  1.  1.  0.  0.  1.  1.  0. 0.  1.  1.  0.  1.]

准确率=0.94, score=0.94

            precision    recall  f1-score   support

       thin     0.89      1.00      0.94        8

        fat      1.00      0.89      0.94        9

avg / total      0.95      0.94      0.94       17

 


KNN分类器在众多分类算法中属于最简单的之一,需要注意的地方不多。有这几点要说明:

1、KNeighborsClassifier可以设置3种算法:‘brute’,‘kd_tree’,‘ball_tree’。如果不知道用哪个好,设置‘auto’让KNeighborsClassifier自己根据输入去决定。

2、注意统计准确率时,分类器的score返回的是计算正确的比例,而不是R2R2一般应用于回归问题。

3、本例先根据样本中身高体重的最大最小值,生成了一个密集网格(步长h=0.01),然后将网格中的每一个点都当成测试样本去测试,最后使用contourf函数,使用不同的颜色标注出了胖、廋两类。

容易看到,本例的分类边界,属于相对复杂,但却又与距离呈现明显规则的锯齿形。

这种边界线性函数是难以处理的。而KNN算法处理此类边界问题具有天生的优势。我们在后续的系列中会看到,这个数据集达到准确率=0.94算是很优秀的结果了。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值