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

news2024/9/20 18:37:09

目录

谷歌笔记本(可选)

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

编写算法:编写kNN算法

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

准备数据:归一化数值

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

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


谷歌笔记本(可选)


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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1464945.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

跨城租赁再复用 | 保利经典款展厅珠江之畔云游湘江之滨盛大启幕

2023年5月1日 由优积出品的 长沙保利-梅溪天珺营销中心 唯美亮相,举城共鉴,不负一城期待 盛大开放! 优积科技可拆装售楼部 首次服务湖南项目 保利梅溪天珺与君说 ,赞51 ▲点击观看展厅开放盛况 长沙保利梅溪天珺售楼处是从佛山…

硬件驱动为什么要有WHQL数字签名?

为了保证驱动程序的安全性,避免用户下载到不利于系统稳定和安全的驱动程序,驱动程序签名被设立出来。最初这一过程由代码签名证书来完成,现在取而代之的则是需要对驱动程序做WHQL认证。本文将详细介绍硬件驱动为什么要有WHQL数字签名的相关内…

如何用GPT高效地处理文本、文献查阅、PPT编辑、编程、绘图和论文写作?

原文链接:如何用GPT高效地处理文本、文献查阅、PPT编辑、编程、绘图和论文写作?https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&mid2247594986&idx4&sn970f9ba75998f2dd9fa5707d1611a6cc&chksmfa82320dcdf5bb1bdf58c20686d4eb209770e68253ed90d…

中建七局领导一行莅临优积科技考察交流

7月17日,中建七局二公司副总经理、总工程师张体浪、基础设施分公司副总经理兼城建事业部总经理陈才正、BIM技术中心总经理完颜健飞等一行7人来访优积科技,公司CEO刘其东携团队成员热情接待了来访领导。 会上双方对我司预制快建可循环售楼部、绿色科技展厅…

pclpy 可视化点云(多窗口可视化、单窗口多点云可视化)

pclpy 可视化点云(多窗口可视化、单窗口多点云可视化) 一、算法原理二、代码三、结果1.多窗口可视化结果2.单窗口多点云可视化 四、相关数据五、问题与解决方案1.问题2.解决 一、算法原理 原理看一下代码写的很仔细的。。目前在同一个窗口最多建立2个窗…

2个wordpress优化SEO主题模板

SEO优化wordpress主题 简洁的SEO优化wordpress主题,效果好不好,结果会告诉你,适合SEO公司使用的主题。 https://www.jianzhanpress.com/?p2804 SEO优化海外WordPress主题 简洁的SEO优化海外服务商WordPress主题,为中国制造202…

1、WEB攻防-通用漏洞SQL注入MYSQL跨库ACCESS偏移

用途:个人学习笔记,欢迎指正! 前言: 为了网站和数据库的安全性,MYSQL 内置有 ROOT 最高用户,划分等级,每个用户对应管理一个数据库,这样保证无不关联,从而不会影响到其他…

性能测试工具-locust

简介 Locust是基于python语言的性能测试框架。 Locust支持分布式部署,单实例并发线程数可达1000,界面简约。 locust基于事件。 Locust的缺点 1、无可视化脚本编写功能,需要基于Python语言和locust框架进行脚本编写,纯代码编写…

新版Java面试专题视频教程——多线程篇①

新版Java面试专题视频教程——多线程篇① Java多线程相关面试题 0. 问题汇总0.1 线程的基础知识0.2 线程中并发安全 1.线程的基础知识1.1 线程和进程的区别?1.2 并行和并发有什么区别?1.3 创建线程的四种方式1.4 runnabl…

LeetCode 2583.二叉树中的第 K 大层和:层序遍历 + 排序

【LetMeFly】2583.二叉树中的第 K 大层和:层序遍历 排序 力扣题目链接:https://leetcode.cn/problems/kth-largest-sum-in-a-binary-tree/ 给你一棵二叉树的根节点 root 和一个正整数 k 。 树中的 层和 是指 同一层 上节点值的总和。 返回树中第 k …

Codeforces Round 927 (Div. 3)

F. Feed Cats 题目大意 给一长度为的数轴,个区间在数轴上选取一些点作为特殊点在满足个区间中,每个区间内只能有一个特殊点问最多能选多少个特殊点 解题思路 对于每个点有放或不放两种状态考虑表示位置可能放或不放的最优结果若不放,若放…

制造业客户数据安全解决方案(终端安全/文件加密/介质管理等)

针对前文制造业客户数据安全解决方案(数据防泄密需求分析)提到的泄密风险,本文详细介绍一套完整、合理的解决方案,通过该方案构建公司数据安全防护边界,自动加密、全方位保护数据安全。 PC端:https://isite…

《VitePress 简易速速上手小册》第10章 维护与更新(2024 最新版)

文章目录 10.1 博客的日常维护10.1.1 基础知识点解析10.1.2 重点案例:内容更新策略10.1.3 拓展案例 1:性能优化实践10.1.4 拓展案例 2:备份和安全性策略 10.2 VitePress 版本更新与迁移10.2.1 基础知识点解析10.2.2 重点案例:平稳…

基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台

结尾有链接 基于SpringBoot2/SpringSecurity/SpringSession/SpringSocial/SpringSecurityOAuth2构建的互联网应用基础框架,包含认证中心、消息通知、安全中心和用户中心。支持Session/JWT/OAuth2认证模式,支持账号密码/短信验证码/社会化登录等登录模式…

ONLYOFFICE 桌面应用程序 v8.0 发布:全新 RTL 界面、本地主题、Moodle 集成等你期待的功能来了!

目录 📘 前言 📟 一、什么是 ONLYOFFICE 桌面编辑器? 📟 二、ONLYOFFICE 8.0版本新增了那些特别的实用模块? 2.1. 可填写的 PDF 表单 2.2. 双向文本 2.3. 电子表格中的新增功能 单变量求解:…

vue组件渲染过程

前言 一个组件渲染到页面,修改data触发更新(数据驱动视图)其背后原理是什么,需要掌握哪些点考察对流程了解的全面程度 回顾三大核心知识点 响应式:监听data属性getter、setter(包括数组) 模板…

概率密度函数(PDF)与神经网络中的激活函数

原创:项道德(daode3056,daode1212) 在量子力学中,许多现象都是统计的结果,基本上用的是正态分布,然而,从本质上思考,应该还存在低阶的分布,标准的正态分布是它的极限,这样一来,或许在…

P9221 「TAOI-1」Pentiment(珂朵莉树,颜色段均摊,ODT)

洛谷 P9221 「TAOI-1」Pentiment 题解区说这题同类型,先码住,有时间做一下。 思路: 这题是个动态规划,如何动规在洛谷题解区第一篇题解中讲的非常详细了,不赘述了。 这里主要考虑如何快速实现求解,假设现…

【STM32备忘录】【STM32WB系列的BLE低功耗蓝牙】一、测试广播配置搜不到信号的注意事项

一、预备知识: WB系列是双核单片机,用户写M4,无线协议栈使用M0新买到手的单片机,需要自己刷入使用的无线协议栈刷入无线协议栈的途径是通过一个叫FUS的东东,类似于bootloader,这个FUS新买的芯片通常已经刷…

v65.二维数组

int num[100];//表示有100个空:从num[0]到num[99] 一维数组(一个下标)这样放置的好处是刚好和线性代数中矩阵的理解是一样的。所以 坐标 的思想是挺必要的在一维数组中,遍历数组只需要一重循环;但在二维数组中&#xf…