监督学习-KNN最邻近分类算法

分类(Classification)指的是从数据中选出已经分好类的训练集,在该训练集上运用数据挖掘分类的技术建立分类模型,从而对没有分类的数据进行分类的分析方法。

分类问题的应用场景:用于将事物打上一个标签,通常结果为离散值。例如判断一副图片上的动物是一只猫还是一只狗,分类通常是建立在回归之上。

基本的分类方法—KNN最邻近分类算法,简称KNN,最简单的机器学习算法之一。

核心逻辑:在距离空间里,如果一个样本的最接近的K个邻居里,绝大多数属于某个类别,则该样本也属于这个类别。

 

 

给定电影分类样例,预测某一电影的分类。

from sklearn import neighbors  #导入模块
import warnings
warnings.filterwarnings('ignore') #不发出警告

df = pd.DataFrame({'name':['北京遇上西雅图','喜欢你','疯狂动物城','战狼2','力王','敢死队'],'fight':[3,2,1,101,99,98],'kiss':[104,100,81,10,5,2],'type':['love','love','love','action','action','action']})
love = df[df['type']] == 'love']
action = df[df['type']== 'action']
plt.scatter(love['fight'],love['kiss'],color = 'red',label = 'love')  # 类型为爱情的电影做红色散点图
plt.scatter(action['fight'],action['kiss'],color = 'green',label='action')  # 类型为动作片的电影做绿色散点图
plt.legend()knn = neighbors.KNeighborsClassifier()  # 创建KNN最邻近分类模型
knn.fit(df[['fight','kiss']],df['type'])  # 给模型导入数据

k = knn.predict([[18, 90]])  # 预测数据,参数需要是二维的
print('预测电影类型为%s'%k,type(k))  # 预测电影类型为['love'],<class 'numpy.ndarray'>
plt.scatter(18,90,color = 'blue',marker='x',label=k) 
plt.text(18,90,'《你的名字》',color='blue') 

 

另外随机生成一组数据,用上面的knn分类模型进行分类

df2 = pd.DataFrame(np.random.rand(100,2)*80,columns=['fight','kiss'])
df2['predictType'] = knn.predict(df2)plt.scatter(love['fight'],love['kiss'],color = 'red',label = 'love')  
plt.scatter(action['fight'],action['kiss'],color = 'green',label='action')
plt.legend()plt.scatter(df2[df2['predictType']=='love']['fight'],df2[df2['predictType']=='love']['kiss'],color = 'red',label = 'love',marker='x')  
plt.scatter(df2[df2['predictType']=='action']['fight'],df2[df2['predictType']=='action']['kiss'],color = 'green',label='action',marker='x')df2.head()

     

 

案例2:植物分类

from sklearn import datasets
iris = datasets.load_iris()
print(iris.data[:5])  #类型为<class 'sklearn.utils.Bunch'>,数据部分为一个二维数组
print(iris.feature_names)
print(iris.target_names) 
# print(iris.target) #表示每一个数据所属的分类,分类用数字表示,结果为数组# [[5.1 3.5 1.4 0.2]
#  [4.9 3.  1.4 0.2]
#  [4.7 3.2 1.3 0.2]
#  [4.6 3.1 1.5 0.2]
#  [5.  3.6 1.4 0.2]]
#['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)'],表示分类特征:萼片长度、萼片宽度、花瓣长度、花瓣宽度
#['setosa' 'versicolor' 'virginica'],表示分类名称

 

构建DataFrame方便查看数据,并使用数字分类和名称分类分别构建模型

data = pd.DataFrame(iris.data, columns = iris.feature_names)  #构建DataFrame方便查看
data['target'] = iris.target
print(data.head())
print('----------------------------')d = pd.DataFrame({'target':[0, 1, 2],'target_names':iris.target_names})
print(d.head())
print('----------------------------')data = pd.merge(data,d,on='target')  #最终形成的DataFrame包含四个分类特征、分类数值、分裂名称
print(data.head())
print('----------------------------')knn1 = neighbors.KNeighborsClassifier()  
knn1.fit(iris.data,iris.target)  #使用分类数值构建模型
t1 = knn1.predict([[0.1,0.2,0.3,0.4]])
print('所在分类(数字表示)为',t1)knn2 = neighbors.KNeighborsClassifier()
knn2.fit(iris.data,data['target_names']) #使用分类名称构建模型
t2 = knn2.predict([[0.1,0.2,0.3,0.4]])
print('所在分类(名称表示)为',t2)  
# 上述输出结果
#
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target # 0 5.1 3.5 1.4 0.2 0 # 1 4.9 3.0 1.4 0.2 0 # 2 4.7 3.2 1.3 0.2 0 # 3 4.6 3.1 1.5 0.2 0 # 4 5.0 3.6 1.4 0.2 0 # ---------------------------- # target target_names # 0 0 setosa # 1 1 versicolor # 2 2 virginica # ---------------------------- # sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target target_names # 0 5.1 3.5 1.4 0.2 0 setosa # 1 4.9 3.0 1.4 0.2 0 setosa # 2 4.7 3.2 1.3 0.2 0 setosa # 3 4.6 3.1 1.5 0.2 0 setosa # 4 5.0 3.6 1.4 0.2 0 setosa # ---------------------------- # 所在分类(数字表示)为 [0] # 所在分类(名称表示)为 ['setosa']

 

转载于:https://www.cnblogs.com/Forever77/p/11385689.html

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

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

相关文章

istio 和 kong_如何启动和运行Istio

istio 和 kongby Chris Cooney克里斯库尼(Chris Cooney) 如何启动和运行Istio (How to get Istio up and running) 而一旦完成&#xff0c;您就可以做的疯狂的事情。 (And the crazy stuff you can do once it is.) The moment you get Istio working on your cluster, it fee…

js练习--贪吃蛇(转)

最近一直在看javascript&#xff0c;但是发现不了动力。就开始想找动力&#xff0c;于是在网上找到了一个用js写的贪吃蛇游戏。奈何还不会用git&#xff0c;就只能先这样保存着。哈哈哈&#xff0c;这也算第一篇博客了&#xff0c;以后会坚持用自己的代码写博客的&#xff0c;下…

bzoj千题计划169:bzoj2463: [中山市选2009]谁能赢呢?

http://www.lydsy.com/JudgeOnline/problem.php?id2463 n为偶数时&#xff0c;一定可以被若干个1*2 矩形覆盖 先手每次从矩形的一端走向另一端&#xff0c;后手每次走向一个新的矩形 所以先手必胜 n为奇数时&#xff0c;先手走完一步后&#xff0c;剩下同n为偶数 所以先手必败…

无监督学习-主成分分析和聚类分析

聚类分析&#xff08;cluster analysis&#xff09;是将一组研究对象分为相对同质的群组&#xff08;clusters&#xff09;的统计分析技术&#xff0c;即将观测对象的群体按照相似性和相异性进行不同群组的划分&#xff0c;划分后每个群组内部各对象相似度很高&#xff0c;而不…

struts实现分页_在TensorFlow中实现点Struts

struts实现分页If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really help…

封装jQuery下载文件组件

使用jQuery导出文档文件 jQuery添加download组件 jQuery.download function(url, data, method){if( url && data ){data typeof data string ? data : paramEdit(data);     function paramEdit(obj){        var temStr "",tempStr"…

7.13. parallel - build and execute shell command lines from standard input in parallel

并行执行shell命令 $ sudo apt-get install parallel 例 7.5. parallel - build and execute shell command lines from standard input in parallel $ cat *.csv | parallel --pipe grep 13113 设置块大小 $ cat *.csv | parallel --block 10M --pipe grep 131136688 原…

MySQL-InnoDB索引实现

联合索引提高查询效率的原理 MySQL会为InnoDB的每个表建立聚簇索引&#xff0c;如果表有索引会建立二级索引。聚簇索引以主键建立索引&#xff0c;如果没有主键以表中的唯一键建立&#xff0c;唯一键也没会以隐式的创建一个自增的列来建立。聚簇索引和二级索引都是一个b树&…

Go语言-基本的http请求操作

Go发起GET请求 基本的GET请求 //基本的GET请求 package mainimport ("fmt""io/ioutil""net/http" )func main() {resp, err : http.Get("http://www.hao123.com")if err ! nil {fmt.Println(err)return}defer resp.Body.Close()body, …

钉钉设置jira机器人_这是当您机器学习JIRA票证时发生的事情

钉钉设置jira机器人For software developers, one of the most-debated and maybe even most-hated questions is “…and how long will it take?”. I’ve experienced those discussions myself, which oftentimes lacked precise information on the requirements. What I…

python的赋值与参数传递(python和linux切换)

1&#xff0c;python模式切回成linux模式------exit&#xff08;&#xff09; linux模式切换成python模式------python 2,在linux里运行python的复合语句&#xff08;得在linux创建.py文件&#xff09; touch le.py vim le.py----在le文件里输入python语句 #!/usr/bin/python …

vscode 标准库位置_如何在VSCode中使用标准

vscode 标准库位置I use Visual Studio Code as my text editor. When I write JavaScript, I follow JavaScript Standard Style.Theres an easy way to integrate Standard in VS Code—with the vscode-standardjs plugin. I made a video for this some time ago if youre …

leetcode 1603. 设计停车系统

请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位&#xff1a;大&#xff0c;中和小&#xff0c;每种尺寸分别有固定数目的车位。 请你实现 ParkingSystem 类&#xff1a; ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类&#xf…

IBM量子计算新突破:成功构建50个量子比特原型机

本文来自AI新媒体量子位&#xff08;QbitAI&#xff09;IBM去年开始以云计算服务的形式提供量子计算能力。当时&#xff0c;IBM发布了包含5个量子比特的计算机。在短短18个月之后&#xff0c;IBM周五宣布&#xff0c;将发布包含20个量子比特的计算机。 IBM还宣布&#xff0c;该…

ChromeDriver与chrome对应关系

http://chromedriver.storage.googleapis.com/index.html 转载于:https://www.cnblogs.com/gcgc/p/11387605.html

快速排序和快速选择(quickSort and quickSelect)算法

排序算法&#xff1a;快速排序(quicksort)递归与非递归算法 TopK问题&#xff1a;快速选择(quickSelect)算法 import java.util.*; import java.lang.*;public class Demo {// 非递归 using stackpublic static void quickSortStack(int[] nums, int left, int right) {if (lef…

小程序点击地图气泡获取气泡_气泡上的气泡

小程序点击地图气泡获取气泡Combining two colors that are two steps apart on the Color Wheel creates a Diad Color Harmony. This Color Harmony is one of the lesser used ones. I decided to cover it here to add variety to your options for colorizing visualizati…

leetcode 150. 逆波兰表达式求值(栈)

根据 逆波兰表示法&#xff0c;求表达式的值。 有效的算符包括 、-、*、/ 。每个运算对象可以是整数&#xff0c;也可以是另一个逆波兰表达式。 说明&#xff1a; 整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说&#xff0c;表达式总会得出有效数值且不存在…

WebLogic常见问题

myeclipseweblogic10的配置&#xff0c;配置成功 运行中可能失败&#xff0c;由于weblogic10不稳定&#xff0c;重启机器后可以使用了 web工程使用到hibernate3时可能出现问题 ClassNotFoundException: org.hibernate.hql.ast.HqlToken 参考http://blog.chinajavaworld.com/ent…

PopTheBubble —测量媒体偏差的产品创意

产品管理 (Product Management) A couple of months ago, I decided to try something new. The MVP Lab by Mozilla is an 8-week incubator for pre-startup teams to explore product concepts and, over the 8 weeks of the program, ship a minimum viable product that p…