机器学习K近邻模块训练学习和模块确定

1.机器学习常用包

import cv2
import numpy as np
import matplotlib.pyplot as plt

2.matplotlib 安装

 pip install matplotlib 

下面是安装的成功提示信息

Installing collected packages: six, cycler, kiwisolver, pyparsing, python-dateutil, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.2.0 matplotlib-3.2.1 pyparsing-2.4.7 python-dateutil-2.8.1 six-1.14.0

3.K近邻模块

KNN(K-Nearest Neighbor) 是一种数据分类有监督的算法

特点分类 ,有监督

KNN 是根据事先拟定的距离度量公式,计算未知类别点与K个相邻数据点的距离;

算法流程如下:

  • 假设数据集中有一定数据量的点,已经标注类别。
  • 对待判定的点,根据拟定的距离,计算与其最近的K个点。
  • 根据K个“邻居”中类别,来判断该点的类别。

4.代码分析

4.1代码1和运行效果

如下图训练集合有3个地方组成 分别提供给20个的 三组空间,在0-35,36-65,66-100 三组随机小数

# 用于训练的数据
# train1数据位于(0,35) 训练数据0-35的数据
train1 = np.random.randint(0, 35, (50, 2)).astype(np.float32)
# train2数据位于(65,100)

train2 = np.random.randint(65, 100, (50, 2)).astype(np.float32)
#训练集叠加
trainData = np.vstack((train2, train1))
# test为用于测试的随机数,该数在0到100之间
test = np.random.randint(0, 100, (1, 2)).astype(np.float32)
  • train1数据位于(0,35) 训练数据0-35的数据,期间在x,y的值在0-35 
  • train2数据位于(65,100) 训练数据65-100的数据,期间在x,y的值在65-100 
  • 训练集合叠加
  • 将第一组划分到类型0的标签,将第二组划分为类型1的标签。
  • 然后,生成一个(0,100)内的随机数,用来作为被测试数据

随机X点红色,距离黄色的(类型0会近一点)

4.2 代码2和运行效果

knn的算法分析

def kNNClassify(inX, dataSet, labels, k):
    

    dataSetSize = dataSet.shape[0]
    diffMax = tile(inX,(dataSetSize,1)) - dataSet
    sqDiffMax = diffMax ** 2  #平方
    sqDistances = sqDiffMax.sum(axis=1)
    distances = sqDistances**0.5
    # argsort 返回由大到小的索引值
    sortedDistIndicies = distances.argsort()
    classCount= {}

    for i in range(k):
        # 找到最大索引值对应数据的label
        voteIlabel = labels[sortedDistIndicies[i]]
         # returns a value for the given key
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    # 按照键值的大小排列
    sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)
    return sortedClassCount[0][0]

4.2.1 数据处理

       网上有个例子为约会的例子,分析数据 将 dotntlike ==0,smallDoses==1,largeDoses==2

最终会转化为 数组类型 ,以此类推,数值为了方便处理,

42770   11.075735  0.089726   dotntlike
8848   3.543989   0.345853   smallDoses
31340  8.123889   1.282880   largeDoses

42770     11.075735    0.089726   0

8848 3.543989 0.345853 1

31340 8.123889 1.282880 2

运行效果为:

5.代码下载

贴代码太累了,还是用git方便管理

https://github.com/kenykeny1688888/MLLearn

后续会整理git 地址

 

 

 


 

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/105677897
今日推荐