使用k-近邻算法改进约会网站的配对效果(kNN)

简介: 使用k-近邻算法改进约会网站的配对效果(kNN)

谷歌笔记本(可选)


from google.colab import drive
drive.mount("/content/drive")
Mounted at /content/drive

准备数据:从文本文件中解析数据


def file2matrix(filename):
  fr = open(filename)
  arrayOfLines = fr.readlines()
  numberOfLines = len(arrayOfLines)
  returnMat = zeros((numberOfLines, 3))
  classLabelVector = []
  index = 0
  for line in arrayOfLines:
    line = line.strip()
    listFromLine = line.split('\t')
    returnMat[index, :] = listFromLine[0:3]
    classLabelVector.append(int(listFromLine[-1]))
    index += 1
  return returnMat, classLabelVector
datingDataMat, datingLabels = file2matrix('/content/drive/MyDrive/MachineLearning/机器学习/k-近邻算法/使用k-近邻算法改进约会网站的配对效果/datingTestSet2.txt')
datingDataMat
array([[4.0920000e+04, 8.3269760e+00, 9.5395200e-01], [1.4488000e+04, 7.1534690e+00, 1.6739040e+00], [2.6052000e+04, 1.4418710e+00, 8.0512400e-01], ..., [2.6575000e+04, 1.0650102e+01, 8.6662700e-01], [4.8111000e+04, 9.1345280e+00, 7.2804500e-01], [4.3757000e+04, 7.8826010e+00, 1.3324460e+00]])
datingLabels[:10]

[3, 2, 1, 1, 1, 1, 3, 3, 1, 3]


编写算法:编写kNN算法


from numpy import *
import operator
 
def classify0(inX, dataSet, labels, k):
  dataSetSize = dataSet.shape[0]
  diffMat = tile(inX, (dataSetSize, 1)) - dataSet
  sqDiffMat = diffMat ** 2
  sqDistances = sqDiffMat.sum(axis=1)
  distances = sqDistances**0.5
  sortedDistIndicies = distances.argsort()
  classCount = {}
  for i in range(k):
    voteIlabel = labels[sortedDistIndicies[i]]
    classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
  sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
  return sortedClassCount[0][0]

分析数据:使用Matplotlib创建散点图


import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2])
plt.show()

import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2],
           15.0*array(datingLabels), 15.0*array(datingLabels))
plt.show()

import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1],
           15.0*array(datingLabels), 15.0*array(datingLabels))
plt.show()


准备数据:归一化数值


def autoNorm(dataSet):
  minVals = dataSet.min(0)
  maxVals = dataSet.max(0)
  ranges = maxVals - minVals
  normDataSet = zeros(shape(dataSet))
  m = dataSet.shape[0]
  normDataSet = dataSet - tile(minVals, (m,1))
  normDataSet = normDataSet/tile(ranges, (m,1))
  return normDataSet, ranges, minVals
normMat, ranges, minVals = autoNorm(datingDataMat)
normMat
array([[0.44832535, 0.39805139, 0.56233353],
       [0.15873259, 0.34195467, 0.98724416],
       [0.28542943, 0.06892523, 0.47449629],
       ...,
       [0.29115949, 0.50910294, 0.51079493],
       [0.52711097, 0.43665451, 0.4290048 ],
       [0.47940793, 0.3768091 , 0.78571804]])
ranges
array([9.1273000e+04, 2.0919349e+01, 1.6943610e+00])
minVals
array([0.      , 0.      , 0.001156])

测试算法:作为完整程序验证分类器


def datingClassTest():
  hoRatio = 0.1
  datingDataMat, datingLabels = file2matrix('/content/drive/MyDrive/MachineLearning/机器学习/k-近邻算法/使用k-近邻算法改进约会网站的配对效果/datingTestSet2.txt')
  normMat, ranges, minVals = autoNorm(datingDataMat)
  m = normMat.shape[0]
  numTestVecs = int(m*hoRatio)
  errorCount = 0
  for i in range(numTestVecs):
    classifierResult = classify0(normMat[i,:], normMat[numTestVecs:m,:],
                                 datingLabels[numTestVecs:m],3)
    print("the classifierResult came back with: %d,\
    the real answer is: %d" % (classifierResult, datingLabels[i]))
    if (classifierResult != datingLabels[i]):
      errorCount += 1
  print("the total error rate is: %f" % (errorCount/float(numTestVecs)))
datingClassTest()
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 3
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 3,    the real answer is: 3
the classifierResult came back with: 2,    the real answer is: 2
the classifierResult came back with: 1,    the real answer is: 1
the classifierResult came back with: 3,    the real answer is: 1
the total error rate is: 0.050000

使用算法:构建完整可用系统


def classifyPerson():
  resultList = ['not at all',
          'in small doses',
          'in large doses',]
  percentTats = float(input("percentage of time spent playing video games?"))
  ffMiles = float(input("frequent flier miles earned per year?"))
  iceCream = float(input("liters of ice cream consumed per year?"))
  datingDataMat, datingLabels = file2matrix('/content/drive/MyDrive/MachineLearning/机器学习/k-近邻算法/使用k-近邻算法改进约会网站的配对效果/datingTestSet2.txt')
  normMat, ranges, minVals = autoNorm(datingDataMat)
  inArr = array([ffMiles, percentTats, iceCream])
  classifierResult = classify0((inArr - minVals)/ranges, normMat, datingLabels, 3)
  print("You will probably like this person:", resultList[classifierResult - 1])
classifyPerson()
percentage of time spent playing video games?10
frequent flier miles earned per year?10000
liters of ice cream consumed per year?0.5
You will probably like this person: in small doses


目录
相关文章
|
1天前
|
机器学习/深度学习 算法
基于鲸鱼优化的knn分类特征选择算法matlab仿真
**基于WOA的KNN特征选择算法摘要** 该研究提出了一种融合鲸鱼优化算法(WOA)与K近邻(KNN)分类器的特征选择方法,旨在提升KNN的分类精度。在MATLAB2022a中实现,WOA负责优化特征子集,通过模拟鲸鱼捕食行为的螺旋式和包围策略搜索最佳特征。KNN则用于评估特征子集的性能。算法流程包括WOA参数初始化、特征二进制编码、适应度函数定义(以分类准确率为基准)、WOA迭代搜索及最优解输出。该方法有效地结合了启发式搜索与机器学习,优化特征选择,提高分类性能。
|
2天前
|
机器学习/深度学习 存储 算法
K 近邻算法(二)
K-近邻(KNN)算法是一种监督学习方法,用于分类和回归。关键步骤包括计算新样本与训练样本的距离,选择合适的邻近样本数K,基于K个邻居的多数类别或平均值做出预测。K值的选择影响模型性能:小K易受噪声影响(过拟合),大K可能导致模型过于简单(欠拟合)。评估模型通常使用测试集的预测准确率,如sklearn.metrics.accuracy_score。最优K值可通过交叉验证,如GridSearchCV,来确定,但它可能计算密集。KNN常用于手写数字识别等任务,如MNIST数据集。
|
2天前
|
机器学习/深度学习 数据采集 算法
K 近邻算法(一)
本文介绍了KNN算法的基本概念、步骤、优缺点,以及在图像识别、文本分类、回归预测、医疗诊断和金融风控等领域的应用。重点讲解了数据预处理、模型训练、评估方法和参数选择策略,包括K值确定、交叉验证和GridSearchCV的使用。
|
3天前
|
机器学习/深度学习 数据采集 算法
KNN算法原理及应用(一)
**KNN算法**是一种监督学习的分类算法,适用于解决分类问题。它基于实例学习,无需训练过程,当新样本到来时,通过计算新样本与已有训练样本之间的距离,找到最近的K个邻居,然后根据邻居的类别进行多数表决(或加权表决)来预测新样本的类别。K值的选择、距离度量方式和分类决策规则是KNN的关键要素。KNN简单易懂,但计算复杂度随样本量增加而增加,适用于小规模数据集。在鸢尾花数据集等经典问题上表现良好,同时能处理多分类任务,并可应用于回归和数据预处理中的缺失值填充。
KNN算法原理及应用(一)
|
3天前
|
算法
KNN算法原理及应用(二)
不能将所有数据集全部用于训练,为了能够评估模型的泛化能力,可以通过实验测试对学习器的泛化能力进行评估,进而做出选择。因此需要使用一个测试集来测试学习器对新样本的判别能力。
|
3天前
|
算法
基于蝗虫优化的KNN分类特征选择算法的matlab仿真
摘要: - 功能:使用蝗虫优化算法增强KNN分类器的特征选择,提高分类准确性 - 软件版本:MATLAB2022a - 核心算法:通过GOA选择KNN的最优特征以改善性能 - 算法原理: - KNN基于最近邻原则进行分类 - 特征选择能去除冗余,提高效率 - GOA模仿蝗虫行为寻找最佳特征子集,以最大化KNN的验证集准确率 - 运行流程:初始化、评估、更新,直到达到停止标准,输出最佳特征组合
|
4天前
|
机器学习/深度学习 算法 搜索推荐
【机器学习】近邻类模型:KNN算法在数据科学中的实践与探索
【机器学习】近邻类模型:KNN算法在数据科学中的实践与探索
24 0
|
2天前
|
机器学习/深度学习 算法 数据可视化
基于BP神经网络的64QAM解调算法matlab性能仿真
**算法预览图省略** MATLAB 2022A版中,运用BP神经网络进行64QAM解调。64QAM通过6比特映射至64复数符号,提高数据速率。BP网络作为非线性解调器,学习失真信号到比特的映射,对抗信道噪声和多径效应。网络在处理非线性失真和复杂情况时展现高适应性和鲁棒性。核心代码部分未显示。
|
4天前
|
机器学习/深度学习 算法 数据可视化
m基于PSO-LSTM粒子群优化长短记忆网络的电力负荷数据预测算法matlab仿真
在MATLAB 2022a中,应用PSO优化的LSTM模型提升了电力负荷预测效果。优化前预测波动大,优化后预测更稳定。PSO借鉴群体智能,寻找LSTM超参数(如学习率、隐藏层大小)的最优组合,以最小化误差。LSTM通过门控机制处理序列数据。代码显示了模型训练、预测及误差可视化过程。经过优化,模型性能得到改善。
21 6
|
2天前
|
缓存 算法
基于机会网络编码(COPE)的卫星网络路由算法matlab仿真
**摘要:** 该程序实现了一个基于机会网络编码(COPE)的卫星网络路由算法,旨在提升无线网络的传输效率和吞吐量。在MATLAB2022a中测试,结果显示了不同数据流个数下的网络吞吐量。算法通过Dijkstra函数寻找路径,计算编码机会(Nab和Nx),并根据编码机会减少传输次数。当有编码机会时,中间节点执行编码和解码操作,优化传输路径。结果以图表形式展示,显示数据流与吞吐量的关系,并保存为`R0.mat`。COPE算法预测和利用编码机会,适应卫星网络的动态特性,提高数据传输的可靠性和效率。