虽然把text转成全部量化是可以的,但是还是需要把text转成numpy的形式(这个是必须掌握的)

在将数据输入到分类器之前,必须将待处理数据的格式改变为分类器可以接受的格式。

数据规范化、数据归一化、数据算法化、输出误差分析

代码:

# -*- coding:utf-8 -*-
from numpy import * def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
#结果全部量化,把喜欢不喜欢排名1、2、3
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') import matplotlib
import matplotlib.pyplot as plt
# matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],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] #得到数据集的行数 shape方法用来得到矩阵或数组的维数
normDataSet = dataSet - tile(minVals,(m,1)) #tile:numpy中的函数。tile将原来的一个数组minVals,扩充成了m行1列的数组
normDataSet = normDataSet/tile(ranges,(m,1))
return normDataSet,ranges,minVals normMat,ranges,minVals = autoNorm((datingDataMat)) 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.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0] def datingClassTest():
hoRatio = 0.10
ErrorCount = 0.0
datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
count = int(m*hoRatio) #这里需要整型化
for i in range(count):
#算法里使用的数据是count(总数)还是i(当前数),
#逐渐被测试的数据inX使用[i,:],但是数据集使用count
# 输入参数:normMat[i,:]为测试样例,表示归一化后的第i行数据
# normMat[numTestVecs:m,:]为训练样本数据,样本数量为(m-numTestVecs)个
# datingLabels[numTestVecs:m]为训练样本对应的类型标签
# k为k-近邻的取值
classifierResult = classify0(normMat[i,:],normMat[count:m,:],datingLabels[count:m],4)
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(count)) def classifyPerson():
resultList = ['not at all','in small doses','in large doses']
#float定义了输入的类型
percentTats = float(raw_input(
"percentage of time spent playing video games?"))
ffMiles = float(raw_input("frequent flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat,datingLabels = file2matrix(("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]

【python】kNN基础算法--推荐系统的更多相关文章

  1. 【python】kNN基础算法--推荐系统(辅助研究)

    # -*- coding:utf-8 -*- # import numpy as np #import numpy 和from numpy import *是不一样的 # # # import num ...

  2. 【python】kNN基础算法--分类和推荐系统

    (1)k-近邻算法是分类数据最简单最有效的方法. (2)在将数据输入到分类器之前,必须将待处理数据的格式改变为分类器可以接受的格式. (3)所有的推荐模型都可以使用这个算法,只要将结果量化就行了,主要 ...

  3. Python之基础算法介绍

    一.算法介绍 1. 算法是什么 算法是指解题方案的准确而完整的描述,是一系列解决问题的清晰指令,算法代表着用系统的方法描述解决问题的策略机制.也就是说,能够对一定规范的输入,在有限时间内获得所要求的输 ...

  4. python函数基础算法简介

    一.多层语法糖本质 """ 语法糖会将紧挨着的被装饰对象名字当参数自动传入装饰器函数中""" def outter(func_name): ...

  5. Python机器学习基础教程-第1章-鸢尾花的例子KNN

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  6. KNN分类算法及python代码实现

    KNN分类算法(先验数据中就有类别之分,未知的数据会被归类为之前类别中的某一类!) 1.KNN介绍 K最近邻(k-Nearest Neighbor,KNN)分类算法是最简单的机器学习算法. 机器学习, ...

  7. Python 从基础------进阶------算法 系列

    1.简介                                                                                               关 ...

  8. python每日经典算法题5(基础题)+1(中难题)

    现在,越来越多的公司面试以及考验面试对算法要求都提高了一个层次,从现在,我讲每日抽出时间进行5+1算法题讲解,5是指基础题,1是指1道中等偏难.希望能够让大家熟练掌握python的语法结构已经一些高级 ...

  9. python每日经典算法题5(基础题)+1(较难题)

    一:基础算法题5道 1.阿姆斯特朗数 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数.判断用户输入的数字是否为阿姆斯特朗数. (1)题目分析:这里要先得到该数是多少位的,然后再把 ...

随机推荐

  1. ApacheCN JavaScript 译文集(二) 20211123 更新

    使用 Meteor 构建单页 Web 应用 零.前言 一.制作 Meteor 应用 二.构建 HTML 模板 三.存储数据和处理集合 四.控制数据流 五.使我们的应用与路由通用 六.保持会话状态 七. ...

  2. Redis 的持久化有哪几种方式?

    面试题 redis 的持久化有哪几种方式? 不同的持久化机制都有什么优缺点? 持久化机制具体底层是如何实现的? 面试官心理分析 redis 如果仅仅只是将数据缓存在内存里面,如果 redis 宕机了再 ...

  3. git删除误传的.idea文件

    问题: 提交项目的时候忘记添加.gitignore文件,误上传了文件(如.idea)如何解决?如何删除Gitee地址上项目的.idea文件?(本文以.idea文件夹举例) 拉取项目 拉取项目 git ...

  4. js window.event

    转载请注明来源:https://www.cnblogs.com/hookjc/ 描述event代表事件的状态,例如触发event对象的元素.鼠标的位置及状态.按下的键等等.event对象只在事件发生的 ...

  5. 直播媒体流red5

    第一步下载 安装setup-Red5-1.0.1-java6.exe 安装教程网上有很多 显示如下页面说明安装成功 第二步 下载oflaDemo的 解压放在 第三步  打开 然后 ok了 注意:下面的 ...

  6. 红色小圆点+数字的badge自定义小方法 by Nicky.Tsui

    效果如图. 实现方法比较简单,在view上增加一个label label设置: 1 badgeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRe ...

  7. 【译】System.Text.Json 的下一步是什么

    .NET 5.0 最近发布了,并带来了许多新特性和性能改进.System.Text.Json 也不例外.我们改进了性能和可靠性,并使熟悉 Newtonsoft.Json 的人更容易采用它.在这篇文章中 ...

  8. HashMap 的 7 种遍历方式与性能分析

    前言 随着 JDK 1.8 Streams API 的发布,使得 HashMap 拥有了更多的遍历的方式,但应该选择那种遍历方式?反而成了一个问题. 本文先从 HashMap 的遍历方法讲起,然后再从 ...

  9. docker基础——4.网络待补

    docker network ls bridge:NAT桥 host:共用宿主机namespace的UTS.IPC.Network none:只有lo,没有网卡 其他待补

  10. Endnote

    #Entnote无法使用Find all test 搜索到sciencedirect的文章(或Elsevier 爱思唯尔) 下面是来自endnote官方论坛的原文Find full text for ...