几个常用库初探及KNN

一、Numpy  基础科学计算库

功能包括:高维数组计算、线性代数计算、傅里叶变换以及生产伪随机数等

多维数组(n-dimensional array)是其核心功能之一

import numpy
i=numpy.array([[520,13,14],[25,9,178]])
print("i:\n{}".format(i))
输出
i:
[[520  13  14]
 [ 25   9 178]]

二、Scipy  强大的科学计算工具集

功能例如:计算统计学分布、信号处理、计算线性代数方程等

scikit-learn需要实用Scipy来队算法进行执行,其中用的最多的是sparse函数(用来生成稀疏矩阵)

import numpy as np
from scipy import sparse
matrix=np.eye(6) #生成一个六行六列的对角矩阵
sparse_matrix=sparse.csr_matrix(matrix)
#转换成csr格式的稀疏矩阵
print("对角矩阵:\n{}".format(matrix))

print("\nsparse存储的对角矩阵:\n{}".format(sparse_matrix))
输出
对角矩阵:
[[1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]]

sparse存储的对角矩阵:
  (0, 0)        1.0
  (1, 1)        1.0
  (2, 2)        1.0
  (3, 3)        1.0
  (4, 4)        1.0
  (5, 5)        1.0

三、pandas  数据分析的利器

1.可以生成类似Excel表格式的数据表,且可以对数据表进行修改操作
2.还可以从不同种类的数据库中提取数据,如SQL数据库、Excel表格、csv文件
3.支持在不同的列中实用不同数据类型的数据

import pandas
#创建一个同学个人信息的小数据集
data={"name":["小芋","小菡","小瑜","小涵"],
      "City":["北京","上海","广州","深圳"],
      "Age":["18","20","22","24"],
      "Height":["162","161","165","166"]}
data_frame=pandas.DataFrame(data)
print(data_frame)

print(data_frame[data_frame.City!="北京"])#把在北京的同学去掉,筛选出不在北京的同学
输出
  name City Age Height
0   小芋   北京  18    162
1   小菡   上海  20    161
2   小瑜   广州  22    165
3   小涵   深圳  24    166

  name City Age Height
1   小菡   上海  20    161
2   小瑜   广州  22    165
3   小涵   深圳  24    166

四、matplotlib   画出优美的图形

import numpy as np
import matplotlib.pyplot as plt
#生成一个从-20到20,元素数为10的等差数列
x=np.linspace(-20,20,10)
#再令y=x^3+2x^2+6x+5
y=x**3+x*x**2+6*x+5
plt.plot(x,y,marker="o")
plt.show()

在这里插入图片描述

五、scikit-learn  非常流行的Python机器学习库

scikit-learn是一个建立在Scipy基础上的用于机器学习的python模块
包含众多机器学习算法,主要有六大类的基本功能:分类、回归、聚类、数据降维、模型选择和数据预处理


一、K最邻近算法 KNN(K-Nearest Neighbors)

K最邻近算法在分类任务中的应用
1.手动生成一些数据集(Training Set)

在scikit-learn中内置了若干个玩具数据集(Toy Datasets)以及一些API让我们可以自己手动生成一些数据集:

#导入数据集生成器
from sklearn.datasets import make_blobs
#导入KNN分类器
from sklearn.neighbors import KNeighborsClassifier
#导入画图工具
import matplotlib.pyplot as plt
#导入数据集拆分工具
from sklearn.model_selection import train_test_split
#生成样本数为200,分类为2的数据集,采用scikit-learn的make_blobs函数生成
data=make_blobs(n_samples=200,centers=2,random_state=8)
X,y=data #生成的结果赋值给X,y
#将生成的数据集进行可视化
plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.spring,edgecolor='k')
plt.show()

在这里插入图片描述
我们根据以上数据用算法进行模型的训练,然后在对新的未知的数据进行分类或回归

2.训练分类模型
import numpy as np
clf=KNeighborsClassifier()
clf.fit(X,y)#利用KNN算法建立了一个下图粉灰分隔的分类器模型

#以下代码用于画图
x_min,x_max=X[:,0].min()-1,X[:,0].max()+1
y_min,y_max=X[:,1].min()-1,X[:,1].max()+1
xx,yy=np.meshgrid(np.arange(x_min,x_max,.02),np.arange(y_min,y_max,.02))
Z=clf.predict(np.c_[xx.ravel(),yy.ravel()])
Z=Z.reshape(xx.shape)
plt.pcolormesh(xx,yy,Z,cmap=plt.cm.Pastel1)
plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.spring,edgecolor='k')
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:KNN")
plt.show()

在这里插入图片描述
至此,分类模型就建立了,粉色区域为0,灰色区域为1,如果有新的数据要输入,模型就会自动将新数据分到对应的分类中
例如有三个数据点,他们的特征值分别为(6.75,4.82),(8,10),(10,3)

#在show前加入以下代码段,观察对于新数据的分类效果
plt.scatter(6.75,4.82,marker='*',c='green',s=200)
print("该数据点的分类是:",clf.predict([[6.75,4.82]]))#验证
plt.scatter(8,10,marker='*',c='red',s=200)
print("该数据点的分类是:",clf.predict([[8,10]]))
plt.scatter(10,3,marker='*',c='yellow',s=200)
print("该数据点的分类是:",clf.predict([[10,3]]))
该数据点的分类是: [1]
该数据点的分类是: [0]
该数据点的分类是: [1]

在这里插入图片描述

K最邻近算法处理多元分类任务

上述代码仅需部分修改

#生成样本数为500,分类为5的数据集,采用scikit-learn的make_blobs函数生成
data=make_blobs(n_samples=500,centers=5,random_state=8)

在这里插入图片描述我们可以看到,中间区域部分相互重合的部分数据分类有误,但大部分分类是准确的

print("模型正确率:{:.2f}".format(clf.score(X,y)))
#模型正确率:0.96

完整代码:

#导入数据集生成器
from sklearn.datasets import make_blobs
#导入KNN分类器
from sklearn.neighbors import KNeighborsClassifier
#导入画图工具
import matplotlib.pyplot as plt
#导入数据集拆分工具
from sklearn.model_selection import train_test_split
#生成样本数为500,分类为5的数据集,采用scikit-learn的make_blobs函数生成
data=make_blobs(n_samples=500,centers=5,random_state=8)
X,y=data #生成的结果赋值给X,y

 
clf=KNeighborsClassifier()
clf.fit(X,y)

#以下代码用于画图
x_min,x_max=X[:,0].min()-1,X[:,0].max()+1
y_min,y_max=X[:,1].min()-1,X[:,1].max()+1
xx,yy=np.meshgrid(np.arange(x_min,x_max,.02),np.arange(y_min,y_max,.02))
Z=clf.predict(np.c_[xx.ravel(),yy.ravel()])
Z=Z.reshape(xx.shape)
plt.pcolormesh(xx,yy,Z,cmap=plt.cm.Pastel1)
plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.spring,edgecolor='k')
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:KNN")

#输出模型的正确率
print("模型正确率:{:.2f}".format(clf.score(X,y)))
plt.show()
K最邻近算法在回归分析中的应用

scikit-learn的数据集生成器中有一个非常好的用于回归分析的数据集生成器:make_regression函数

from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
#导入make_regression数据集生成器
from sklearn.datasets import make_regression
#生成特征数量为1,噪音为50的数据集
X,y=make_regression(n_features=1,n_informative=1,noise=50,random_state=8)
#用散点图将数据点进行可视化
#plt.scatter(X,y,c='orange',edgecolor='k')
#横轴代表的是样本特征的数值(-3~3),纵轴代表的是样本的测定值(-250~250)

#导入用于回归分析的KNN模型
from sklearn.neighbors import KNeighborsRegressor
reg=KNeighborsRegressor()

#用KNN模型拟合数据
reg.fit(X,y)

#把预测结果用图像进行可视化
z=np.linspace(-3,3,200).reshape(-1,1)
plt.scatter(X,y,c='orange',edgecolor='k')
plt.plot(z,reg.predict(z),c='k',linewidth=3)
#给图像加标题
plt.title("KNN Regressor")

print("模型评分:{:.2f}".format(reg.score(X,y))) #模型评分:0.77
plt.show()

在这里插入图片描述
但是这个拟合的效果并不是很好,大量数据点没有被覆盖到,模型得分也只有0.77,为了寻求更号的拟合效果,我们尝试调整K邻近数,默认的情况下,n-neighbors=5,我们现在减少看看:

#导入用于回归分析的KNN模型
from sklearn.neighbors import KNeighborsRegressor
reg=KNeighborsRegressor(n_neighbors=3) #模型评分:0.79
# n_neighbors=2 模型评分:0.86 曲线如下图,拟合了更多数据
# n_neighbors=1 模型评分:1.00

n_neighbors=2:
在这里插入图片描述
n_neighbors=1:
在这里插入图片描述
这个时候就要思考另一个问题了,会不会过拟合?

酒的分类问题的应用
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
#从sklearn的datasets模块载入数据集
wine_dataset=load_wine() #载入的数据集时一种Bunch对象,包括key和values
print("红酒数据集中的键:\n{}".format(wine_dataset.keys()))
print("-----------------------------------------------------\n")
#打印数据的情况 例如样本数、变量数
print("数据概况:{}\n\n".format(wine_dataset['data'].shape))
print("-----------------------------------------------------\n")
#打印酒的数据集中的简短描述
print(wine_dataset['DESCR'])
print("-----------------------------------------------------\n")
#将数据集拆分成训练数据集和测试数据集
X_train,X_test,y_train,y_test=train_test_split(wine_dataset['data'],wine_dataset['target'],random_state=0)
#train_test_split函数会生成一个伪随机数,并根据这个伪随机数对数据集进行划分
#而当我们在一个项目中需要让多次生成的伪随机数相同,就需要固定random_state的值,相同的random_state会一直产生同样的伪随机数
#但当这个值设为0或保持缺省的时候则每次生成的伪随机数均不同

#查看拆分后的数据集
#打印测试数据集中的特征向量的形态
print("X_train shape:{}".format(X_train.shape))
print("X_test shape:{}".format(X_test.shape))
#打印测试数据集中目标的形态
print("y_train shape:{}".format(y_train.shape))
print("y_test shape:{}".format(y_test.shape))
print("-----------------------------------------------------\n")
#K最邻近算法根据训练数据集进行建模,在训练数据集中寻找和新输入的数据最近的数据点然后把这个数据点的标签分配给新的数据点,以此对新的样本进行分类
#导入KNN分类模型
from sklearn.neighbors import KNeighborsClassifier
#指定模型的m_neighbors参数值为1
knn=KNeighborsClassifier(n_neighbors=1)
#使用knn对象中的拟合方法进行建模,建模的依据就是训练数据集中的样本数据X_train和其对应的标签y_train
knn.fit(X_train,y_train)
#打印模型的全部参数设定
print(knn)
print("-----------------------------------------------------\n")
#打印测试数据集效果(得分)
print("测试数据集得分:{:.2f}".format(knn.score(X_test,y_test)))
print("-----------------------------------------------------\n")
#用建好的模型对新酒作出分类预测
import numpy as np
#输入新的数据点,有13个特征变量值 噗 注意两个[[]]
X_new=np.array([[13.2,2.77,2.51,18.5,96.6,1.04,2.55,0.57,1.47,6.2,1.05,3.33,820]])
#使用predict进行预测
prediction=knn.predict(X_new)
print("预测的红酒分类为:{}".format(wine_dataset['target_names'][prediction]))
print("\n")
红酒数据集中的键:
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names'])
-----------------------------------------------------

数据概况:(178, 13)


-----------------------------------------------------

.. _wine_dataset:

Wine recognition dataset
------------------------

**Data Set Characteristics:**

    :Number of Instances: 178 (50 in each of three classes)
    :Number of Attributes: 13 numeric, predictive attributes and the class
    :Attribute Information:
                - Alcohol
                - Malic acid
                - Ash
                - Alcalinity of ash
                - Magnesium
                - Total phenols
                - Flavanoids
                - Nonflavanoid phenols
                - Proanthocyanins
                - Color intensity
                - Hue
                - OD280/OD315 of diluted wines
                - Proline

    - class:
            - class_0
            - class_1
            - class_2

    :Summary Statistics:

    ============================= ==== ===== ======= =====
                                   Min   Max   Mean     SD
    ============================= ==== ===== ======= =====
    Alcohol:                      11.0  14.8    13.0   0.8
    Malic Acid:                   0.74  5.80    2.34  1.12
    Ash:                          1.36  3.23    2.36  0.27
    Alcalinity of Ash:            10.6  30.0    19.5   3.3
    Magnesium:                    70.0 162.0    99.7  14.3
    Total Phenols:                0.98  3.88    2.29  0.63
    Flavanoids:                   0.34  5.08    2.03  1.00
    Nonflavanoid Phenols:         0.13  0.66    0.36  0.12
    Proanthocyanins:              0.41  3.58    1.59  0.57
    Colour Intensity:              1.3  13.0     5.1   2.3
    Hue:                          0.48  1.71    0.96  0.23
    OD280/OD315 of diluted wines: 1.27  4.00    2.61  0.71
    Proline:                       278  1680     746   315
    ============================= ==== ===== ======= =====

    :Missing Attribute Values: None
    :Class Distribution: class_0 (59), class_1 (71), class_2 (48)
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

This is a copy of UCI ML Wine recognition datasets.
https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data

The data is the results of a chemical analysis of wines grown in the same
region in Italy by three different cultivators. There are thirteen different
measurements taken for different constituents found in the three types of
wine.

Original Owners:

Forina, M. et al, PARVUS -
An Extendible Package for Data Exploration, Classification and Correlation.
Institute of Pharmaceutical and Food Analysis and Technologies,
Via Brigata Salerno, 16147 Genoa, Italy.

Citation:

Lichman, M. (2013). UCI Machine Learning Repository
[https://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
School of Information and Computer Science.

.. topic:: References

  (1) S. Aeberhard, D. Coomans and O. de Vel,
  Comparison of Classifiers in High Dimensional Settings,
  Tech. Rep. no. 92-02, (1992), Dept. of Computer Science and Dept. of
  Mathematics and Statistics, James Cook University of North Queensland.
  (Also submitted to Technometrics).

  The data was used with many others for comparing various
  classifiers. The classes are separable, though only RDA
  has achieved 100% correct classification.
  (RDA : 100%, QDA 99.4%, LDA 98.9%, 1NN 96.1% (z-transformed data))
  (All results using the leave-one-out technique)

  (2) S. Aeberhard, D. Coomans and O. de Vel,
  "THE CLASSIFICATION PERFORMANCE OF RDA"
  Tech. Rep. no. 92-01, (1992), Dept. of Computer Science and Dept. of
  Mathematics and Statistics, James Cook University of North Queensland.
  (Also submitted to Journal of Chemometrics).

-----------------------------------------------------

X_train shape:(133, 13)
X_test shape:(45, 13)
y_train shape:(133,)
y_test shape:(45,)
-----------------------------------------------------

KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
                     metric_params=None, n_jobs=None, n_neighbors=1, p=2,
                     weights='uniform')
-----------------------------------------------------

测试数据集得分:0.76
-----------------------------------------------------

预测的红酒分类为:['class_2']
KNN模型总结

K最邻近算法经典且容易理解,但在实际使用中会有很多问题,例如需要对数据集认真的进行预处理、对规模超大的数据集拟合的时间较长、对高维数据的拟合欠佳、无法处理稀疏数据集等,所以并不常用。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值