Sådan opbygges og trænes K-nærmeste naboer og K-midler, der samler ML-modeller i Python

En af maskinlærings mest populære applikationer er at løse klassificeringsproblemer.

Klassificeringsproblemer er situationer, hvor du har et datasæt, og du vil klassificere observationer fra dette datasæt i en bestemt kategori.

Et berømt eksempel er et spamfilter til e-mailudbydere. Gmail bruger overvågede teknikker til maskinindlæring til automatisk at placere e-mails i din spam-mappe baseret på deres indhold, emnelinje og andre funktioner.

To maskinlæringsmodeller udfører meget af det tunge løft, når det kommer til klassificeringsproblemer:

  • K-nærmeste naboer
  • K-betyder klyngedannelse

Denne tutorial lærer dig, hvordan du koder K-nærmeste naboer og K-betyder klyngealgoritmer i Python.

K-nærmeste nabomodeller

K-nærmeste naboalgoritme er en af ​​verdens mest populære maskinlæringsmodeller til løsning af klassificeringsproblemer.

En almindelig øvelse for studerende, der udforsker maskinindlæring, er at anvende algoritmen K nærmeste naboer til et datasæt, hvor kategorierne ikke er kendt. Et eksempel fra det virkelige liv på dette ville være, hvis du havde brug for at forudsige brug af maskinindlæring på et datasæt med klassificerede offentlige oplysninger.

I denne vejledning lærer du at skrive din første K nærmeste nabos maskinindlæringsalgoritme i Python. Vi arbejder med et anonymt datasæt svarende til situationen beskrevet ovenfor.

Det datasæt, du har brug for i denne vejledning

Den første ting, du skal gøre, er at downloade datasættet, vi bruger i denne vejledning. Jeg har uploadet filen til min hjemmeside. Du kan få adgang til det ved at klikke her.

Nu hvor du har downloadet datasættet, vil du flytte filen til det bibliotek, du arbejder i. Derefter skal du åbne en Jupyter Notebook, så kan vi komme i gang med at skrive Python-kode!

De biblioteker, du har brug for i denne vejledning

For at skrive en K nærmeste nabealgoritme vil vi drage fordel af mange open source Python-biblioteker, herunder NumPy, pandaer og scikit-learning.

Begynd dit Python-script ved at skrive følgende importerklæringer:

 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline 

Import af datasættet til vores Python-script

Vores næste trin er at importere classified_data.csvfilen til vores Python-script. Pandabiblioteket gør det let at importere data til en pandas DataFrame.

Da datasættet er gemt i en csvfil, bruger vi read_csvmetoden til at gøre dette:

 raw_data = pd.read_csv('classified_data.csv') 

Udskrivning af denne DataFrame inde i din Jupyter Notebook giver dig en fornemmelse af, hvordan dataene ser ud:

En panda DataFrame

Du vil bemærke, at DataFrame starter med en kolonne, der ikke er navngivet, hvis værdier er lig med DataFrames indeks. Vi kan løse dette ved at foretage en lille justering af kommandoen, der importerede vores datasæt til Python-scriptet:

 raw_data = pd.read_csv('classified_data.csv', index_col = 0) 

Lad os derefter se på de faktiske funktioner, der er indeholdt i dette datasæt. Du kan udskrive en liste over datasættets kolonnenavne med følgende udsagn:

 print(raw_data.columns) 

Dette returnerer:

 Index(['WTT', 'PTI', 'EQW', 'SBI', 'LQE', 'QWG', 'FDJ', 'PJF', 'HQE', 'NXJ', 'TARGET CLASS'], dtype="object") 

Da dette er et klassificeret datasæt, har vi ingen idé om, hvad nogen af ​​disse kolonner betyder. Indtil videre er det tilstrækkeligt at erkende, at hver kolonne er numerisk og således velegnet til modellering med maskinlæringsteknikker.

Standardisering af datasættet

Da K nærmeste nabo-algoritme forudsiger et datapunkt ved hjælp af de observationer, der er tættest på det, betyder skalaen af ​​funktionerne i et datasæt meget.

På grund af dette praktiserer maskinindlæringsudøvere typisk standardizedatasættet, hvilket betyder at justere hver xværdi, så de er omtrent på samme skala.

Heldigvis scikit-learninkluderer nogle fremragende funktioner til at gøre dette med meget lidt hovedpine.

For at starte skal vi importere StandardScalerklassen fra scikit-learn. Føj følgende kommando til dit Python-script for at gøre dette:

 from sklearn.preprocessing import StandardScaler 

Denne funktion opfører sig meget som de LinearRegressionog LogisticRegressionklasser, som vi brugte tidligere i dette kursus. Vi vil gerne oprette en forekomst af denne klasse og derefter tilpasse forekomsten af ​​den klasse til vores datasæt.

Lad os først oprette en forekomst af StandardScalerklassen navngivet scalermed følgende udsagn:

 scaler = StandardScaler() 

Vi kan nu træne denne forekomst på vores datasæt ved hjælp af fitmetoden:

 scaler.fit(raw_data.drop('TARGET CLASS', axis=1)) 

Nu kan vi bruge transformmetoden til at standardisere alle funktionerne i datasættet, så de er omtrent den samme skala. Vi tildeler disse skalerede funktioner til variablen navngivet scaled_features:

 scaled_features = scaler.transform(raw_data.drop('TARGET CLASS', axis=1)) 

Dette skaber faktisk et NumPy-array med alle funktionerne i datasættet, og vi vil have, at det skal være en pandas DataFrame i stedet.

Heldigvis er dette en let løsning. Vi indpakker scaled_featuresvariablen simpelthen i en pd.DataFramemetode og tildeler denne DataFrame til en ny variabel kaldet scaled_datamed et passende argument for at specificere kolonnenavnene:

 scaled_data = pd.DataFrame(scaled_features, columns = raw_data.drop('TARGET CLASS', axis=1).columns) 

Nu hvor vi har importeret vores datasæt og standardiseret dets funktioner, er vi klar til at opdele datasættet i træningsdata og testdata.

Opdeling af datasættet i træningsdata og testdata

Vi bruger train_test_splitfunktionen fra scikit-learnkombineret med listeudpakning til at oprette træningsdata og testdata fra vores klassificerede datasæt.

Først skal du importere train_test_splitfra model_validationmodulet scikit-learnmed følgende udsagn:

 from sklearn.model_selection import train_test_split 

Derefter skal vi specificere de værdier xog yværdier, der sendes til denne train_test_splitfunktion.

De xværdier der holdes scaled_datadatarammen at vi oprettede tidligere. De yværdier der holdes TARGET CLASSkolonne i vores oprindelige raw_datadataramme.

Du kan oprette disse variabler med følgende udsagn:

 x = scaled_data y = raw_data['TARGET CLASS'] 

Next, you’ll need to run the train_test_split function using these two arguments and a reasonable test_size. We will use a test_size of 30%, which gives the following parameters for the function:

 x_training_data, x_test_data, y_training_data, y_test_data = train_test_split(x, y, test_size = 0.3) 

Now that our data set has been split into training data and test data, we’re ready to start training our model!

Training a K Nearest Neighbors Model

Let’s start by importing the KNeighborsClassifier from scikit-learn:

 from sklearn.neighbors import KNeighborsClassifier 

Next, let’s create an instance of the KNeighborsClassifier class and assign it to a variable named model

This class requires a parameter named n_neighbors, which is equal to the K value of the K nearest neighbors algorithm that you’re building. To start, let’s specify n_neighbors = 1:

 model = KNeighborsClassifier(n_neighbors = 1) 

Now we can train our K nearest neighbors model using the fit method and our x_training_data and y_training_data variables:

 model.fit(x_training_data, y_training_data) 

Now let’s make some predictions with our newly-trained K nearest neighbors algorithm!

Making Predictions With Our K Nearest Neighbors Algorithm

We can make predictions with our K nearest neighbors algorithm in the same way that we did with our linear regression and logistic regression models earlier in this course: by using the predict method and passing in our x_test_data variable.

More specifically, here’s how you can make predictions and assign them to a variable called predictions:

 predictions = model.predict(x_test_data) 

Let’s explore how accurate our predictions are in the next section of this tutorial.

Measuring the Accuracy of Our Model

We saw in our logistic regression tutorial that scikit-learn comes with built-in functions that make it easy to measure the performance of machine learning classification models.

Let’s import two of these functions (classification_report and confuson_matrix) into our report now:

 from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix 

Let’s work through each of these one-by-one, starting with the classfication_report. You can generate the report with the following statement:

 print(classification_report(y_test_data, predictions)) 

This generates:

 precision recall f1-score support 0 0.94 0.85 0.89 150 1 0.86 0.95 0.90 150 accuracy 0.90 300 macro avg 0.90 0.90 0.90 300 weighted avg 0.90 0.90 0.90 300 

Similarly, you can generate a confusion matrix with the following statement:

 print(confusion_matrix(y_test_data, predictions)) 

This generates:

 [[141 12] [ 18 129]] 

Looking at these performance metrics, it looks like our model is already fairly performant. It can still be improved.

In the next section, we will see how we can improve the performance of our K nearest neighbors model by choosing a better value for K.

Choosing An Optimal K Value Using the Elbow Method

In this section, we will use the elbow method to choose an optimal value of K for our K nearest neighbors algorithm.

The elbow method involves iterating through different K values and selecting the value with the lowest error rate when applied to our test data.

To start, let’s create an empty list called error_rates. We will loop through different K values and append their error rates to this list.

 error_rates = [] 

Next, we need to make a Python loop that iterates through the different values of K we’d like to test and executes the following functionality with each iteration:

  • Creates a new instance of the KNeighborsClassifier class from scikit-learn
  • Trains the new model using our training data
  • Makes predictions on our test data
  • Calculates the mean difference for every incorrect prediction (the lower this is, the more accurate our model is)

Here is the code to do this for K values between 1 and 100:

 for i in np.arange(1, 101): new_model = KNeighborsClassifier(n_neighbors = i) new_model.fit(x_training_data, y_training_data) new_predictions = new_model.predict(x_test_data) error_rates.append(np.mean(new_predictions != y_test_data)) 

Let’s visualize how our error rate changes with different K values using a quick matplotlib visualization:

 plt.plot(error_rates) 
Et plot af vores fejlprocent

As you can see, our error rates tend to be minimized with a K value of approximately 50. This means that 50 is a suitable choice for K that balances both simplicity and predictive power.

The Full Code For This Tutorial

You can view the full code for this tutorial in this GitHub repository. It is also pasted below for your reference:

 #Common imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #Import the data set raw_data = pd.read_csv('classified_data.csv', index_col = 0) #Import standardization functions from scikit-learn from sklearn.preprocessing import StandardScaler #Standardize the data set scaler = StandardScaler() scaler.fit(raw_data.drop('TARGET CLASS', axis=1)) scaled_features = scaler.transform(raw_data.drop('TARGET CLASS', axis=1)) scaled_data = pd.DataFrame(scaled_features, columns = raw_data.drop('TARGET CLASS', axis=1).columns) #Split the data set into training data and test data from sklearn.model_selection import train_test_split x = scaled_data y = raw_data['TARGET CLASS'] x_training_data, x_test_data, y_training_data, y_test_data = train_test_split(x, y, test_size = 0.3) #Train the model and make predictions from sklearn.neighbors import KNeighborsClassifier model = KNeighborsClassifier(n_neighbors = 1) model.fit(x_training_data, y_training_data) predictions = model.predict(x_test_data) #Performance measurement from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix print(classification_report(y_test_data, predictions)) print(confusion_matrix(y_test_data, predictions)) #Selecting an optimal K value error_rates = [] for i in np.arange(1, 101): new_model = KNeighborsClassifier(n_neighbors = i) new_model.fit(x_training_data, y_training_data) new_predictions = new_model.predict(x_test_data) error_rates.append(np.mean(new_predictions != y_test_data)) plt.figure(figsize=(16,12)) plt.plot(error_rates) 

K-Means Clustering Models

The K-means clustering algorithm is typically the first unsupervised machine learning model that students will learn.

It allows machine learning practitioners to create groups of data points within a data set with similar quantitative characteristics. It is useful for solving problems like creating customer segments or identifying localities in a city with high crime rates.

In this section, you will learn how to build your first K means clustering algorithm in Python.

The Data Set We Will Use In This Tutorial

In this tutorial, we will be using a data set of data generated using scikit-learn.

Let’s import scikit-learn’s make_blobs function to create this artificial data. Open up a Jupyter Notebook and start your Python script with the following statement:

 from sklearn.datasets import make_blobs 

Now let’s use the make_blobs function to create some artificial data!

More specifically, here is how you could create a data set with 200 samples that has 2 features and 4 cluster centers. The standard deviation within each cluster will be set to 1.8.

 raw_data = make_blobs(n_samples = 200, n_features = 2, centers = 4, cluster_std = 1.8) 

If you print this raw_data object, you’ll notice that it is actually a Python tuple. The first element of this tuple is a NumPy array with 200 observations. Each observation contains 2 features (just like we specified with our make_blobs function!).

Now that our data has been created, we can move on to importing other important open-source libraries into our Python script.

The Imports We Will Use In This Tutorial

This tutorial will make use of a number of popular open-source Python libraries, including pandas, NumPy, and matplotlib. Let’s continue our Python script by adding the following imports:

 import pandas as pd import numpy as np import seaborn import matplotlib.pyplot as plt %matplotlib inline 

The first group of imports in this code block is for manipulating large data sets. The second group of imports is for creating data visualizations.

Let’s move on to visualizing our data set next.

Visualizing Our Data Set

In our make_blobs function, we specified for our data set to have 4 cluster centers. The best way to verify that this has been handled correctly is by creating some quick data visualizations.

To start, let’s use the following command to plot all of the rows in the first column of our data set against all of the rows in the second column of our data set:

En scatterplot af vores kunstige data

Note: your data set will appear differently than mine since this is randomly-generated data.

This image seems to indicate that our data set has only three clusters. This is because two of the clusters are very close to each other.

To fix this, we need to reference the second element of our raw_data tuple, which is a NumPy array that contains the cluster to which each observation belongs.

If we color our data set using each observation’s cluster, the unique clusters will quickly become clear. Here is the code to do this:

 plt.scatter(raw_data[0][:,0], raw_data[0][:,1], c=raw_data[1]) 
En scatterplot af vores kunstige data

We can now see that our data set has four unique clusters. Let’s move on to building our K means cluster model in Python!

Building and Training Our K Means Clustering Model

The first step to building our K means clustering algorithm is importing it from scikit-learn. To do this, add the following command to your Python script:

 from sklearn.cluster import KMeans 

Next, lets create an instance of this KMeans class with a parameter of n_clusters=4 and assign it to the variable model:

 model = KMeans(n_clusters=4) 

Now let’s train our model by invoking the fit method on it and passing in the first element of our raw_data tuple:

 model.fit(raw_data[0]) 

In the next section, we’ll explore how to make predictions with this K means clustering model.

Before moving on, I wanted to point out one difference that you may have noticed between the process for building this K means clustering algorithm (which is an unsupervised machine learning algorithm) and the supervised machine learning algorithms we’ve worked with so far in this course.

Namely, we did not have to split the data set into training data and test data. This is an important difference - and in fact, you never need to make the train/test split on a data set when building unsupervised machine learning models!

Making Predictions With Our K Means Clustering Model

Machine learning practitioners generally use K means clustering algorithms to make two types of predictions:

  • Which cluster each data point belongs to
  • Where the center of each cluster is

It is easy to generate these predictions now that our model has been trained.

First, let’s predict which cluster each data point belongs to. To do this, access the labels_ attribute from our model object using the dot operator, like this:

 model.labels_ 

This generates a NumPy array with predictions for each data point that looks like this:

 array([3, 2, 7, 0, 5, 1, 7, 7, 6, 1, 2, 4, 6, 7, 6, 4, 4, 3, 3, 6, 0, 0, 6, 4, 5, 6, 0, 2, 6, 5, 4, 3, 4, 2, 6, 6, 6, 5, 6, 2, 1, 1, 3, 4, 3, 5, 7, 1, 7, 5, 3, 6, 0, 3, 5, 5, 7, 1, 3, 1, 5, 7, 7, 0, 5, 7, 3, 4, 0, 5, 6, 5, 1, 4, 6, 4, 5, 6, 7, 2, 2, 0, 4, 1, 1, 1, 6, 3, 3, 7, 3, 6, 7, 7, 0, 3, 4, 3, 4, 0, 3, 5, 0, 3, 6, 4, 3, 3, 4, 6, 1, 3, 0, 5, 4, 2, 7, 0, 2, 6, 4, 2, 1, 4, 7, 0, 3, 2, 6, 7, 5, 7, 5, 4, 1, 7, 2, 4, 7, 7, 4, 6, 6, 3, 7, 6, 4, 5, 5, 5, 7, 0, 1, 1, 0, 0, 2, 5, 0, 3, 2, 5, 1, 5, 6, 5, 1, 3, 5, 1, 2, 0, 4, 5, 6, 3, 4, 4, 5, 6, 4, 4, 2, 1, 7, 4, 6, 6, 0, 6, 3, 5, 0, 5, 2, 4, 6, 0, 1, 0], dtype=int32) 

To see where the center of each cluster lies, access the cluster_centers_ attribute using the dot operator like this:

 model.cluster_centers_ 

This generates a two-dimensional NumPy array that contains the coordinates of each clusters center. It will look like this:

 array([[ -8.06473328, -0.42044783], [ 0.15944397, -9.4873621 ], [ 1.49194628, 0.21216413], [-10.97238157, -2.49017206], [ 3.54673215, -9.7433692 ], [ -3.41262049, 7.80784834], [ 2.53980034, -2.96376999], [ -0.4195847 , 6.92561289]]) 

We’ll assess the accuracy of these predictions in the next section.

Visualizing the Accuracy of Our Model

The last thing we’ll do in this tutorial is visualize the accuracy of our model. You can use the following code to do this:

 f, (ax1, ax2) = plt.subplots(1, 2, sharey=True,figsize=(10,6)) ax1.set_title('Our Model') ax1.scatter(raw_data[0][:,0], raw_data[0][:,1],c=model.labels_) ax2.set_title('Original Data') ax2.scatter(raw_data[0][:,0], raw_data[0][:,1],c=raw_data[1]) 

This generates two different plots side-by-side where one plot shows the clusters according to the real data set and the other plot shows the clusters according to our model. Here is what the output looks like:

En scatterplot af vores models forudsigelser

Although the coloring between the two plots is different, you can see that our model did a fairly good job of predicting the clusters within our data set. You can also see that the model was not perfect - if you look at the data points along a cluster’s edge, you can see that it occasionally misclassified an observation from our data set.

There’s one last thing that needs to be mentioned about measuring our model’s prediction. In this example ,we knew which cluster each observation belonged to because we actually generated this data set ourselves.

This is highly unusual. K means clustering is more often applied when the clusters aren’t known in advance. Instead, machine learning practitioners use K means clustering to find patterns that they don’t already know within a data set.

The Full Code For This Tutorial

You can view the full code for this tutorial in this GitHub repository. It is also pasted below for your reference:

 #Create artificial data set from sklearn.datasets import make_blobs raw_data = make_blobs(n_samples = 200, n_features = 2, centers = 4, cluster_std = 1.8) #Data imports import pandas as pd import numpy as np #Visualization imports import seaborn import matplotlib.pyplot as plt %matplotlib inline #Visualize the data plt.scatter(raw_data[0][:,0], raw_data[0][:,1]) plt.scatter(raw_data[0][:,0], raw_data[0][:,1], c=raw_data[1]) #Build and train the model from sklearn.cluster import KMeans model = KMeans(n_clusters=4) model.fit(raw_data[0]) #See the predictions model.labels_ model.cluster_centers_ #PLot the predictions against the original data set f, (ax1, ax2) = plt.subplots(1, 2, sharey=True,figsize=(10,6)) ax1.set_title('Our Model') ax1.scatter(raw_data[0][:,0], raw_data[0][:,1],c=model.labels_) ax2.set_title('Original Data') ax2.scatter(raw_data[0][:,0], raw_data[0][:,1],c=raw_data[1]) 

Final Thoughts

This tutorial taught you how to how to build K-nearest neighbors and K-means clustering machine learning models in Python.

Hvis du er interesseret i at lære mere om maskinindlæring, vil min bog Pragmatic Machine Learning lære dig praktiske maskinindlæringsteknikker ved at opbygge 9 rigtige projekter. Bogen lanceres 3. august. Du kan forudbestille den til 50% rabat ved hjælp af nedenstående link:

Pragmatisk maskinindlæring Maskinindlæring ændrer verden. Men det har altid været svært at lære maskinlæring ... indtil nu. Pragmatisk maskinindlæring er en trinvis vejledning, der lærer dig grundlæggende om maskinindlæring gennem opbygning af 9 virkelige projekter. Du lærer: Lineær regression, Logistisk regression, ... Nick McCullum Gumroad

Her er et kort resume af, hvad du lærte om K-nærmeste nabomodeller i Python:

  • Hvordan klassificerede data er et almindeligt værktøj, der bruges til at lære eleverne at løse deres første K nærmeste naboproblemer
  • Why it’s important to standardize your data set when building K nearest neighbor models
  • How to split your data set into training data and test data using the train_test_split function
  • How to train your first K nearest neighbors model and make predictions with it
  • How to measure the performance of a K nearest neighbors model
  • How to use the elbow method to select an optimal value of K in a K nearest neighbors model

Similarly, here is a brief summary of what you learned about K-means clustering models in Python:

  • How to create artificial data in scikit-learn using the make_blobs function
  • How to build and train a K means clustering model
  • That unsupervised machine learning techniques do not require you to split your data into training data and test data
  • How to build and train a K means clustering model using scikit-learn
  • Sådan visualiseres udførelsen af ​​en K betyder klyngealgoritme, når du kender klyngerne på forhånd