机器学习笔记1-k近邻算法的实现,跳槽薪资翻倍

distance = sqDistances**0.5

#将距离数组的下标按照距离大小排序

sortedDistIndicies = distance.argsort()

classCount = {}

#在k的范围内,分别计算两类的数目

for i in range(k):

voteIlabel = labels[sortedDistIndicies[i]]

classCount[voteIlabel] = classCount.get(voteIlabel,0)+1

#以k以内类别数目排序

sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),

reverse = True)

#返回数目最多的类(即输入向量应该属于的类)

return sortedClassCount[0][0]

def test():

print(classify0([0.3,0.5],group,labels,2))

if __name__ == ‘__main__’:

group = numpy.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])

labels = [‘A’,‘A’,‘B’,‘B’]

test()

其中几个不熟悉的函数:

shape:读取矩阵的长度,比如shape[0]:就是读取矩阵的一维长度

tile:形如tile(x,y)就是重复x,y次,例如;

>>> numpy.tile([1,1],10)

array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

>>> numpy.tile([2,1],[2,3])

array([[2, 1, 2, 1, 2, 1],

[2, 1, 2, 1, 2, 1]])

sum(axis=1):在某一维度上相加:

>>> a = numpy.array([1,2])

>>> a.sum()

3

>>> a.sum(axis=1)

Traceback (most recent call last):

File “<pyshell#27>”, line 1, in

a.sum(axis=1)

File “F:\python3\lib\site-packages\numpy\core\_methods.py”, line 32, in _sum

return umr_sum(a, axis, dtype, out, keepdims)

ValueError: ‘axis’ entry is out of bounds

>>> numpy.array([[1,2,4],[2,4,5]]).sum(axis=1)

array([ 7, 11])

argsort():将数组的值的下标按值的由大到小的顺序排序

>>> a = numpy.array([8,6,7,9,10,5,7])

>>> a.argsort()

array([5, 1, 2, 6, 0, 3, 4], dtype=int32)

items():字典的值以列表的形式返回

itemgetter():用于返回对象那些维的数据

sorted():函数sorted(iterable[, cmp[, key[, reverse]]]),用于给列表排序,返回一个新的列表

iterable – 可迭代对象。

cmp – 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。

key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

实例,根据玩视频游戏所耗时间百分比,每年获得的飞行常客里程数,每周的冰淇淋公升数来判断魅力值

1.解析数据,书中给出的数据存在一个问题,就是标签向量为一个字符串,需要将其转化成整形形式

def getValueOfClassLabel(ClassLabel):

val = 1;

if not ClassLabel in ValueOfClassLabel.keys():

ValueOfClassLabel[ClassLabel] = Value.pop()

return ValueOfClassLabel[ClassLabel]

解析文件的完整代码:

def file2matrix(filename):

‘’’

用于解析训练集文件

‘’’

ValueOfClassLabel = {}

Value = [1,2,3]

def getValueOfClassLabel(ClassLabel):

val = 1;

if not ClassLabel in ValueOfClassLabel.keys():

ValueOfClassLabel[ClassLabel] = Value.pop()

return ValueOfClassLabel[ClassLabel]

file = open(filename)

arrayOLines = file.readlines()

#文件的行数

numberOfLines = len(arrayOLines)

#返回创建的训练集

returnMat = numpy.zeros((numberOfLines,3))

classLabelVector = []

index = 0

for line in arrayOLines:

line = line.strip()

listFormLine = line.split(‘\t’)

returnMat[index,:] = listFormLine[0:3]

classLabelVector.append(getValueOfClassLabel(str(listFormLine[-1])))

index +=1

return returnMat,classLabelVector

通过上述程序可以将文件内容格式化成我们需要的训练集,标签向量,通过画图来直观的判断他们之间的关系

import numpy

import kNN

import matplotlib

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)

ax.scatter(datingDataMat[:,1],datingDataMat[:,2],

15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))

plt.xlabel(‘Percentage of Time Spent Playing Video Games’)

plt.ylabel(‘Liters of Ice Cream Consumed Per Week’)

plt.show()

3D图:

import numpy

import kNN

import matplotlib

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = fig.add_subplot(111,projection=‘3d’)

datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)

ax.scatter(datingDataMat[:,0],datingDataMat[:,1],datingDataMat[:,2],

15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))

ax.set_xlabel(‘mei nian huo qu de fei xing chang ke li cheng shu’)

ax.set_ylabel(‘wan you xi shi jian bi li’)

ax.set_zlabel(‘mei zhou xiao hao de bing qi li shuliang’)

plt.show()

多图:

import numpy

import kNN

import matplotlib

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(311)

datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)

ax1.scatter(datingDataMat[:,0],datingDataMat[:,1],

15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))

ax1.set_xlabel(‘fly’)

ax2 = fig.add_subplot(312)

ax2.scatter(datingDataMat[:,0],datingDataMat[:,2],

15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))

ax2 = fig.add_subplot(313)

ax2.scatter(datingDataMat[:,1],datingDataMat[:,2],

15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))

plt.show()

不熟悉的函数:

add_subplot:用于指定图像的位置,例如111,指图像分成一行一列,在第一幅图上画

scatter:画散点图,必须输入的有x,y坐标,可选项有颜色形状等

zero:创建0矩阵

归一化:

处理不同取值范围的特征值时,通常需要将数值未硬化,如果将取值范围处理为0到1或者-1到1之间,下面公式可以将任意取值范围的特征值转化为0到1的区间内

newValue = (oldValue-min)/(max-min)

min,max分别是数据集中特征值最大值和最小值,程序如下

def autoNum(dataSet):

#获取每一列的最小值

minVals = dataSet.min(0)

#获取每一列的最大值

maxVals = dataSet.max(0)

#最大值和最小值的差

ranges = maxVals - minVals

#将每一行归一化

normDataSet = numpy.zeros(numpy.shape(dataSet))

m = dataSet.shape[0]

normDataSet = dataSet - numpy.tile(minVals,(m,1))

normDataSet = normDataSet/numpy.tile(ranges,(m,1))

return normDataSet,ranges,minVals

容易搞错的是min(0)返回的是每一列的最小值,而不是第0列的最小值,min()返回的是所有值的最小值,min(1)返回的是每一行的最小值

测试程序:

def datingClassTest():

‘’’

用于测试分类器

‘’’

hoRatio = 0.10

datingDataMating,datingLabels = file2matrix(‘f:\\datingTestSet.txt’)

normMat,ranges,minVals = autoNum(datingDataMating)

m = normMat.shape[0]

numTestVecs = int(m*hoRatio)

errorCount = 0.0

for i in range(numTestVecs):

classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],

datingLabels[numTestVecs:m],3)

print(‘the classifier came back with: %d,the real answer is:%d’%

(classifierResult,datingLabels[i]))

if(classifierResult != datingLabels[i]):errorCount += 1.0

print(‘the total error rate is:%f’%(errorCount/float(numTestVecs)))

测试结果:

the classifier came back with: 3,the real answer is:3

the classifier came back with: 2,the real answer is:2

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 3,the real answer is:3

the classifier came back with: 3,the real answer is:3

the classifier came back with: 1,the real answer is:1

the classifier came back with: 3,the real answer is:3

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 2,the real answer is:2

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 1,the real answer is:1

the classifier came back with: 2,the real answer is:2

the classifier came back with: 3,the real answer is:3

the classifier came back with: 2,the real answer is:2

the classifier came back with: 1,the real answer is:1

the classifier came back with: 3,the real answer is:2

the classifier came back with: 3,the real answer is:3

the classifier came back with: 2,the real answer is:2

the classifier came back with: 3,the real answer is:3

the classifier came back with: 2,the real answer is:2

the classifier came back with: 3,the real answer is:3

the classifier came back with: 2,the real answer is:2

the classifier came back with: 1,the real answer is:1

最后

Python崛起并且风靡,因为优点多、应用领域广、被大牛们认可。学习 Python 门槛很低,但它的晋级路线很多,通过它你能进入机器学习、数据挖掘、大数据,CS等更加高级的领域。Python可以做网络应用,可以做科学计算,数据分析,可以做网络爬虫,可以做机器学习、自然语言处理、可以写游戏、可以做桌面应用…Python可以做的很多,你需要学好基础,再选择明确的方向。这里给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

👉Python所有方向的学习路线👈

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

👉Python必备开发工具👈

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

👉Python全套学习视频👈

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

👉实战案例👈

学python就与学数学一样,是不能只看书不做题的,直接看步骤和答案会让人误以为自己全都掌握了,但是碰到生题的时候还是会一筹莫展。

因此在学习python的过程中一定要记得多动手写代码,教程只需要看一两遍即可。

👉大厂面试真题👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python爬虫全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
img

都能找到满意的工作。

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python爬虫全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:python)
[外链图片转存中…(img-lBNTqRKK-1710943429059)]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值