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.pswp.cn/news/391963.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391963.shtml
英文地址,請注明出處:http://en.pswp.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 …