Machine Learning in Action Chapter2

2024-02-13 19:38

本文主要是介绍Machine Learning in Action Chapter2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

python 3.6

此代码取自书中。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file:KNN.py
@time:2019/1/1 14:10
@author:Victor
@site:https://blog.csdn.net/sumup
"""from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt# def createDataSet():# group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])# labels = ['A','A','B','B']# return group, labelsdef classify0(inX, dataSet, labels, k):dataSetSize = dataSet.shape[0]##输出dataSet的行数print(dataSet.shape[1])##2列print(dataSet.shape[0])##4行##构造(dataSetSize,1)规摸的数组,并inX数组与dataSet相减# [[-1.  -1.1]# [-1.  -1. ]# [ 0.   0. ]# [ 0.  -0.1]]diffMat = tile(inX, (dataSetSize,1)) - dataSetprint(diffMat)##矩阵平方# [[1.   1.21]# [1.   1.  ]# [0.   0.  ]# [0.   0.01]]sqDiffMat = diffMat**2print(sqDiffMat)##矩阵每行求和# [2.21 2.   0.   0.01]sqDistances = sqDiffMat.sum(axis=1)print(sqDistances)# print(sqDistances.shape[0]) ##4##每行的和开方# [1.48660687 1.41421356 0.         0.1       ]distances = sqDistances**0.5print(distances)##从小到大排序,输出下标# [2 3 1 0]sortedDistIndicies = distances.argsort()print(sortedDistIndicies)classCount = {}for i in range(k):voteIlabel = labels[sortedDistIndicies[i]]print(voteIlabel)##在classCount中查找voteIlabel,若没,赋值0,并+1classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1# print(classCount.items())  ##dict_items([('B', 2), ('A', 1)])##key 为classCount的valuesortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1), reverse=True)return sortedClassCount[0][0]##Input filename
##Output returnMat classLabelVector
def file2matrix(filename):fr = open(filename)arrayOLines = fr.readlines()numberOfLines = len(arrayOLines)##创建(numberOfLines,3)矩阵,并初始化0returnMat = zeros((numberOfLines,3))classLabelVector = []index = 0for line in arrayOLines:##默认删除空白符(包括'\n', '\r',  '\t',  ' ')line = line.strip()##根据‘\t’划分开listFromLine = line.split('\t')returnMat[index,:] = listFromLine[0:3]# print(returnMat[index,:])classLabelVector.append(int(listFromLine[-1]))index += 1return returnMat,classLabelVector##newvalue = (oldValue-min)/(max-min)	
def autoNorm(dataSet):##返回矩阵中每一列的最小值minVals = dataSet.min(0)##返回矩阵中每一列的最大值maxVals = dataSet.max(0)ranges = maxVals - minValsnormDataSet = zeros(shape(dataSet))m = dataSet.shape[0]normDataSet = dataSet - tile(minVals, (m,1))normDataSet = normDataSet/tile(ranges, (m,1))return normDataSet, ranges, minValsdef datingClassTest():#10%用于求结果hoRatio = 0.10datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')normMat,ranges,minVals = autoNorm(datingDataMat)m = normMat.shape[0]numTestVecs = int(m*hoRatio)errorCount = 0.0for i in range(numTestVecs):classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)print('the classfier came back with: %d, the real answer is: %d' %(classifierResult,datingLabels[i]))if (classifierResult != datingLabels[i]):errorCount += 1.0print('the total error rate is: %f' %(errorCount/float(numTestVecs)))def classifyPerson():resultList =['not at all','in small does','in large does']percentTats = float(input("percentage of time spent playing video games?"))ffMiles = float(input("frequent flier miles earned per year"))iceCream = float(input("liters of iceam 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 link this person: ",resultList[classifierResult-1])# group,labels = createDataSet()# print(group)
# print(labels)
# print(classify0([0,0],group,labels,3))
# datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')# fig = plt.figure()            
#add_subplot(mnp)#添加子轴、图。subplot(m,n,p)或者subplot(mnp)此函数最常用:
#subplot是将多个图画到一个平面上的工具。其中,m表示是图排成m行,n表示图排成n列,也就是整个figure中有n个图是排成一行的,一共m行,如果第一个数字是2就是表示2行图。
#p是指你现在要把曲线画到figure中哪个图上,最后一个如果是1表示是从左到右第一个位置。
# ax = fig.add_subplot(111)
# ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0*array(datingLabels))
# print(autoNorm(datingDataMat))
# plt.show()
# datingClassTest()
classifyPerson()

 

这篇关于Machine Learning in Action Chapter2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/706438

相关文章

Unable to instantiate Action, goodsTypeAction, defined for 'goodsType_findAdvanced' in namespace '/

报错: Unable to instantiate Action, goodsTypeAction,  defined for 'goodsType_findAdvanced' in namespace '/'goodsTypeAction......... Caused by: java.lang.ClassNotFoundException: goodsTypeAction.......

简单的Q-learning|小明的一维世界(3)

简单的Q-learning|小明的一维世界(1) 简单的Q-learning|小明的一维世界(2) 一维的加速度世界 这个世界,小明只能控制自己的加速度,并且只能对加速度进行如下三种操作:增加1、减少1、或者不变。所以行动空间为: { u 1 = − 1 , u 2 = 0 , u 3 = 1 } \{u_1=-1, u_2=0, u_3=1\} {u1​=−1,u2​=0,u3​=1}

简单的Q-learning|小明的一维世界(2)

上篇介绍了小明的一维世界模型 、Q-learning的状态空间、行动空间、奖励函数、Q-table、Q table更新公式、以及从Q值导出策略的公式等。最后给出最简单的一维位置世界的Q-learning例子,从给出其状态空间、行动空间、以及稠密与稀疏两种奖励函数的设置方式。下面将继续深入,GO! 一维的速度世界 这个世界,小明只能控制自己的速度,并且只能对速度进行如下三种操作:增加1、减

用ajax json给后台action传数据要注意的问题

必须要有get和set方法   1 action中定义bean变量,注意写get和set方法 2 js中写ajax方法,传json类型数据 3 配置action在struts2中

使用http-request 属性替代action绑定上传URL

在 Element UI 的 <el-upload> 组件中,如果你需要为上传的 HTTP 请求添加自定义的请求头(例如,为了通过身份验证或满足服务器端的特定要求),你不能直接在 <el-upload> 组件的属性中设置这些请求头。但是,你可以通过 http-request 属性来自定义上传的行为,包括设置请求头。 http-request 属性允许你完全控制上传的行为,包括如何构建请求、发送请

ZOJ 3324 Machine(线段树区间合并)

这道题网上很多代码是错误的,由于后台数据水,他们可以AC。 比如这组数据 10 3 p 0 9 r 0 5 r 6 9 输出应该是 0 1 1 所以有的人直接记录该区间是否被覆盖过的方法是错误的 正确方法应该是记录这段区间的最小高度(就是最接近初始位置的高度),和最小高度对应的最长左区间和右区间 开一个sum记录这段区间最小高度的块数,min_v 记录该区间最小高度 cover

Flink整合Oozie Shell Action 提交任务带Kerberos认证

最近这段时间一直在忙新集群迁移,上了最新的cdh6.3.0 于是Flink 提交遇到了许多的问题,还好有cloudera License 有了原厂的帮助和社区的伙伴,问题解决起来快了不少。 集群具体情况是 CDH6.3.0 Flink1.8.1,整个数据平台全部组件都上了kerberos和ldap因为要过认证,所以任务提交方法我们选择统一Oozie提交任务,并且因为kerberos认证,还需要F

Servlet mapping specifies an unknown servlet name Action

看一下web.xml中<servlet-mapping>有没有配错

Learning Memory-guided Normality for Anomaly Detection——学习记忆引导的常态异常检测

又是一篇在自编码器框架中研究使用记忆模块的论文,可以看做19年的iccv的论文的衍生,在我的博客中对19年iccv这篇论文也做了简单介绍。韩国人写的,应该是吧,这名字听起来就像。 摘要abstract 我们解决异常检测的问题,即检测视频序列中的异常事件。基于卷积神经网络的异常检测方法通常利用代理任务(如重建输入视频帧)来学习描述正常情况的模型,而在训练时看不到异常样本,并在测试时使用重建误

Learning Temporal Regularity in Video Sequences——视频序列的时间规则性学习

Learning Temporal Regularity in Video Sequences CVPR2016 无监督视频异常事件检测早期工作 摘要 由于对“有意义”的定义不明确以及场景混乱,因此在较长的视频序列中感知有意义的活动是一个具有挑战性的问题。我们通过在非常有限的监督下使用多种来源学习常规运动模式的生成模型(称为规律性)来解决此问题。体来说,我们提出了两种基于自动编码器的方法,以