knn分类 knn_关于KNN的快速小课程

knn分类 knn

As the title says, here is a quick little lesson on how to construct a simple KNN model in SciKit-Learn. I will be using this dataset. It contains information on students’ academic performance.

就像标题中所说的,这是关于如何在SciKit-Learn中构建简单的KNN模型的快速入门课程。 我将使用此数据集 。 它包含有关学生学习成绩的信息。

Features included are things like how many times a student raises their hand, their gender, parent satisfaction, how often they were absent from class, and how often they participated in class discussion.

这些功能包括诸如学生举手次数,性别,父母满意度,他们缺席课堂的频率以及他们参加课堂讨论的频率之类的东西。

Each student is grouped into one of three academic classes: High (H), Medium (M), and Low (L). I used the other features in order to predict which class they fall in.

每个学生分为三个学术班级之一:高(H),中(M)和低(L)。 我使用其他功能来预测它们属于哪个类。

Just for reference:

仅供参考:

  • High, 90–100

    高,90-100
  • Medium, 70–89

    中,70–89
  • Low, 0–69

    低,0–69

Okay, cool! Let’s get started.

好吧,酷! 让我们开始吧。

图书馆进口 (Library Import)

import numpy as npimport pandas as pdimport seaborn as snsimport statsmodels.api as smfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.neighbors import KNeighborsClassifierfrom statsmodels.formula.api import olsfrom sklearn.metrics import precision_score, recall_score,
accuracy_score, f1_scoreimport matplotlib.pyplot as plt
%matplotlib inline

First, you want to import all of the libraries that you’re going to need. Some people import each library at each stage of the process, but personally I like to do it all at the beginning.

首先,您要导入所有需要的库。 有些人在流程的每个阶段都导入每个库,但是我个人最喜欢一开始就全部完成。

Technically we won’t really be using Seaborn or MatplotLib, but I like to keep them around just in case I want to visualize something during the process.

从技术上讲,我们实际上并不会使用Seaborn或MatplotLib,但我希望保留它们,以防万一我想在此过程中可视化某些东西。

初始数据导入 (Initial Data Import)

df = pd.read_csv('xAPI-Edu-Data.csv')
df.head()
Image for post
Screenshot of partial output.
部分输出的屏幕截图。

Cool! The data is in good shape to begin with. There are no missing values and no outliers to speak of. However, we will have to do a small amount of preprocessing to get it ready for our model.

凉! 首先,数据处于良好状态。 没有遗漏的值,也没有离群值。 但是,我们将需要进行少量预处理才能为模型准备就绪。

前处理 (Preprocessing)

# Dropping all unnecessary columns
df = df.drop(['NationalITy', 'PlaceofBirth', 'StageID', 'GradeID',
'SectionID', 'Topic', 'Relation',
'ParentAnsweringSurvey'],
axis = 1,
inplace = False)
df.head()
Image for post
Screenshot of output.
输出的屏幕截图。

When feeding a KNN model, you only want to include the features that you actually want to be making the decision. This may seem obvious but I figured it was worth mentioning.

在提供KNN模型时,您只想包含您实际要做出决定的功能。 这似乎很明显,但我认为值得一提。

# Binary encoding of categorical variables
df['gender'] = df['gender'].map({'M': 0, 'F': 1})
df['Semester'] = df['Semester'].map({'F': 0, 'S': 1})
df['ParentschoolSatisfaction'] = df['ParentschoolSatisfaction'].map({'Good': 0, 'Bad': 1})
df['StudentAbsenceDays'] = df['StudentAbsenceDays'].map({'Under-7': 0, 'Above-7': 1})
df.head()
Image for post
Screenshot of output.
输出的屏幕截图。

Something perhaps not so obvious if you have never done this, is that you have to encode your categorical variables. It makes sense if you think about it. A model can’t really interpret ‘Good’ or ‘Bad’, but it can interpret 0 and 1.

如果您从未执行过此操作,那么可能不太明显的是您必须对分类变量进行编码。 如果您考虑一下,这是有道理的。 模型无法真正解释“好”或“差”,但可以解释0和1。

# Check for missing values
df.isna().sum()
Image for post
Screenshot of output.
输出的屏幕截图。

I know I already said that we don’t have any missing values, but I just like to be thorough.

我知道我已经说过,我们没有任何缺失的价值观,但我只是想做到周全。

# Create a new dataframe with our target variable, remove the target variable from the original dataframe
labels = df['Class']
df.drop('Class', axis = 1, inplace = True)

And then —

然后 -

df.head()
Image for post
Screenshot out output.
屏幕截图输出。
labels.head()
Image for post
Screenshot of output.
输出的屏幕截图。

Next, we want to separate our target feature from our predictive features. We do this in order to create a train/test split for our data. Speaking of!

接下来,我们要将目标特征与预测特征分开。 我们这样做是为了为我们的数据创建一个训练/测试组。 说起!

训练/测试拆分 (Train/Test Split)

X_train, X_test, y_train, y_test = train_test_split(df, labels,
test_size = .25,
random_state =
33)

*I realize the above formatting is terrible, I’m just trying to make it readable for this Medium article.

*我意识到上面的格式很糟糕,我只是想让这篇中型文章可读。

扩展数据 (Scaling the Data)

This next part brings up two important points:

下一部分提出了两个要点:

  1. You need to scale the data. If you don’t, variables with larger absolute values will be given more weight in the model for no real reason. We have our features that are binary encoded (0, 1) but we also have features on how many times student raise their hands (0–80). We need to put them on the same scale so they have the same importance in the model.

    您需要缩放数据。 如果您不这样做,则在没有真正原因的情况下,具有更大绝对值的变量将在模型中获得更大的权重。 我们具有二进制编码的功能(0,1),但也具有学生举手次数(0–80)的功能。 我们需要将它们放到相同的规模,以便它们在模型中具有相同的重要性。
  2. You have to scale the data AFTER you perform the train/test split. If you don’t, you will have leakage and you will invalidate your model. For a more thorough explanation, check out this article by Jason Browlee who has tons of amazing resources on machine learning.

    执行训练/测试拆分后,您必须缩放数据。 如果不这样做,将会泄漏,并使模型无效。 有关更全面的解释,请查看Jason Browlee的这篇文章 ,他拥有大量有关机器学习的惊人资源。

The good news is, this is extremely easy to do.

好消息是,这非常容易做到。

scaler = StandardScaler()
scaled_data_train = scaler.fit_transform(X_train)
scaled_data_test = scaler.transform(X_test)
scaled_df_train = pd.DataFrame(scaled_data_train, columns =
df.columns)scaled_df_train.head()
Image for post
Screenshot of output.
输出的屏幕截图。

Awesome. Easy peasy lemon squeezy, our data is scaled.

太棒了 轻松榨取柠檬,我们的数据即可缩放。

拟合KNN模型 (Fit a KNN Model)

# Instantiate the model
clf = KNeighborsClassifier()# Fit the model
clf.fit(scaled_data_train, y_train)# Predict on the test set
test_preds = clf.predict(scaled_data_test)

It really truly is that simple. Now, we want to see how well our baseline model performed.

真的就是这么简单。 现在,我们想看看基线模型的性能如何。

评估模型 (Evaluating the Model)

def print_metrics(labels, preds):
print("Precision Score: {}".format(precision_score(labels,
preds, average = 'weighted')))
print("Recall Score: {}".format(recall_score(labels, preds,
average = 'weighted')))
print("Accuracy Score: {}".format(accuracy_score(labels,
preds)))
print("F1 Score: {}".format(f1_score(labels, preds, average =
'weighted')))print_metrics(y_test, test_preds)
Image for post
Screenshot of output.
输出的屏幕截图。

And there you have it, with almost no effort, we created a predictive model that is able to classify students into their academic performance class with an accuracy of 75.8%. Not bad.

在这里,您几乎无需付出任何努力,就创建了一个预测模型,该模型能够以75.8%的准确度将学生分类为他们的学习成绩班级。 不错。

We can probably improve this by at least a few points by tuning the parameters of the model, but I will leave that for another post.

我们可以通过调整模型的参数至少将其改进几个点,但是我将在另一篇文章中讨论。

Happy learning. 😁

学习愉快。 😁

翻译自: https://towardsdatascience.com/a-quick-little-lesson-on-knn-98381c487aa2

knn分类 knn

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

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

相关文章

spring—配置数据源

数据源(连接池)的作用 数据源(连接池)是提高程序性能如出现的 事先实例化数据源,初始化部分连接资源 使用连接资源时从数据源中获取 使用完毕后将连接资源归还给数据源 常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等 开发步…

大型网站系统与Java中间件实践pdf

下载地址:网盘下载 基本介绍 编辑内容简介 到底是本什么书,拥有这样一份作序推荐人列表:阿里集团章文嵩博士|新浪TimYang|去哪网吴永强|丁香园冯大辉|蘑菇街岳旭强|途牛汤峥嵘|豆瓣洪强宁|某电商陈皓/林昊…… 这本书出自某电商技术部总监之手…

office漏洞利用--获取shell

环境: kali系统, windows系统 流程: 在kali系统生成利用文件, kali系统下监听本地端口, windows系统打开doc文件,即可中招 第一种利用方式, 适合测试用: 从git下载代码: …

pandas之DataFrame合并merge

一、merge merge操作实现两个DataFrame之间的合并,类似于sql两个表之间的关联查询。merge的使用方法及参数解释如下: pd.merge(left, right, onNone, howinner, left_onNone, right_onNone, left_indexFalse, right_indexFalse,    sortFalse, suffi…

typescript_如何掌握高级TypeScript模式

typescriptby Pierre-Antoine Mills皮埃尔安托万米尔斯(Pierre-Antoine Mills) 如何掌握高级TypeScript模式 (How to master advanced TypeScript patterns) 了解如何为咖喱和Ramda创建类型 (Learn how to create types for curry and Ramda) Despite the popularity of curry…

html函数splice,js数组的常用函数(slice()和splice())和js引用的三种方法总结—2019年1月16日...

总结:slice()和splice()slice(参数1,参数2)可以查找数组下对应的数据,参数1为起始位置,参数2为结束位置,参数2可以为负数,-1对应的是从后向前数的第一个数值。splice()可以进行增删改查数据操作,splice(参数…

leetcode 643. 子数组最大平均数 I(滑动窗口)

给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。 示例: 输入:[1,12,-5,-6,50,3], k 4 输出:12.75 解释:最大平均数 (12-5-650)/4 51/4 12.75 代码 class Solution {publ…

python ==字符串

字符串类型(str): 包含在引号(单,双,三)里面,由一串字符组成。 用途:姓名,性别,地址,学历,密码 Name ‘zbk’ 取值: 首先要明确,字符…

认证鉴权与API权限控制在微服务架构中的设计与实现(一)

作者: [Aoho’s Blog] 引言: 本文系《认证鉴权与API权限控制在微服务架构中的设计与实现》系列的第一篇,本系列预计四篇文章讲解微服务下的认证鉴权与API权限控制的实现。 1. 背景 最近在做权限相关服务的开发,在系统微服务化后&a…

mac下完全卸载程序的方法

在国外网上看到的,觉得很好,不仅可以长卸载的知识,还对mac系统有更深的认识。比如偏好设置文件,我以前设置一个程序坏了,打不开了,怎么重装都打不开,后来才知道系统还保留着原来的偏好设置文件。…

机器学习集群_机器学习中的多合一集群技术在无监督学习中应该了解

机器学习集群Clustering algorithms are a powerful technique for machine learning on unsupervised data. The most common algorithms in machine learning are hierarchical clustering and K-Means clustering. These two algorithms are incredibly powerful when appli…

自考本科计算机要学什么,计算机自考本科需要考哪些科目

高科技发展时代,怎离得开计算机技术?小学生都要学编程了,未来趋势一目了然,所以如今在考虑提升学历的社会成人,多半也青睐于计算机专业,那么计算机自考本科需要考哪些科目?难不难?自…

审查指南 最新版本_代码审查-最终指南

审查指南 最新版本by Assaf Elovic通过阿萨夫埃洛维奇 代码审查-最终指南 (Code Review — The Ultimate Guide) 构建团队代码审查流程的终极指南 (The ultimate guide for building your team’s code review process) After conducting hundreds of code reviews, leading R…

非对称加密

2019独角兽企业重金招聘Python工程师标准>>> 概念 非对称加密算法需要两个密钥:公钥(publickey)和私钥(privatekey)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私…

管理Sass项目文件结构

http://www.w3cplus.com/preprocessor/architecture-sass-project.html 编辑推荐: 掘金是一个高质量的技术社区,从 CSS 到 Vue.js,性能优化到开源类库,让你不错过前端开发的每一个技术干货。 点击链接查看最新前端内容&#xff0c…

Spring—注解开发

Spring原始注解 Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文 件可以简化配置,提高开发效率。 Component 使用在类上用于实例化BeanController 使用在web层类…

政府公开数据可视化_公开演讲如何帮助您设计更好的数据可视化

政府公开数据可视化What do good speeches and good data visualisation have in common? More than you may think.好的演讲和好的数据可视化有什么共同点? 超出您的想象。 Aristotle — the founding father of all things public speaking — believed that th…

C++字符串完全指引之一 —— Win32 字符编码 (转载)

C字符串完全指引之一 —— Win32 字符编码原著:Michael Dunn翻译:Chengjie Sun 原文出处:CodeProject:The Complete Guide to C Strings, Part I 引言  毫无疑问,我们都看到过像 TCHAR, std::string, BSTR 等各种各样…

网络计算机无法访问 请检查,局域网电脑无法访问,请检查来宾访问帐号是否开通...

局域网电脑无法访问,有时候并不是由于网络故障引起的,而是因为自身电脑的一些设置问题,例如之前谈过的网络参数设置不对造成局域网电脑无法访问。今天分析另一个电脑设置的因素,它也会导致局域网电脑无法访问,那就是宾…

unity中创建游戏场景_在Unity中创建Beat Em Up游戏

unity中创建游戏场景Learn how to use Unity to create a 3D Beat Em Up game in this full tutorial from Awesome Tuts. 在Awesome Tuts的完整教程中,了解如何使用Unity来创建3D Beat Em Up游戏。 This tutorial covers everything you need to know to make a …