机器学习代码(一)——KNN

 下面是sklearn 关于knn的代码

 

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

n_neighbors = 15

iris = datasets.load_iris()

x = iris.data[:, :2]
y = iris.target

h = 0.01

cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

for i in ['uniform', 'distance']:
    clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, weights=i) #n_neighbors 相当于KNN 的K
    #参数 weights 表示是否对距离进行加权, unifor 是和距离无关, distance 与距离成反比

    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, h),
                         np.arange(y_min, y_max, h))

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])#xx.ravel() 将xx 散开  xx.reshape(1,N) 
    #np.c_[a, b]  输出[ab]
    #np.r_[a, b]  输出[a;b]


    Z = Z.reshape(xx.shape)

    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cmap_bold,
                edgecolor='k', s=20)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, i))

plt.show()

输出结果

        

 

 

下面是不用python 库实现Knn

 

import numpy as np
import matplotlib.pyplot as plt
import math
from sklearn import datasets

k = 5
iris = datasets.load_iris()

x = iris.data[:, :2]
y = iris.target

def Myknn(inputdata, k, datasets, label):

    numsampel = datasets.shape[0]
    diff = np.tile(inputdata, (numsampel, 1)) - datasets

    SquaredDiff = np.power(diff, 2)

    squaredDist = np.sum(SquaredDiff, axis=1)#axis=1按列
    distance = np.sqrt(squaredDist)

    sortdistance = np.argsort(distance)

    callasscount = {}

    for i in range(k):
        vol = label[sortdistance[i]]
        callasscount[vol] = callasscount.get(vol, 0) + 1
    maxnum = 0
    maxitem = ''
    for key, value in callasscount.items():
        if value > maxnum:
            maxnum = value
            maxitem = key
    return maxitem

test = [5, 1]

outputlabel = Myknn(test, k, x, y)
print('数据{} 的标签是'.format(test), outputlabel)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值