Table of Contents
step
Example
Output
Home Backend Development Python Tutorial How to implement linear classification using Python Scikit-learn?

How to implement linear classification using Python Scikit-learn?

Aug 20, 2023 pm 06:57 PM

Linear classification is one of the simplest machine learning problems. To achieve linear classification, we will use sklearn's SGD (Stochastic Gradient Descent) classifier to predict iris flower varieties.

step

You can implement linear classification using Python Scikit-learn by following the steps given below:

Step 1 − First import the necessary packages scikit-learn, NumPy and matplotlib

Step 2 − Load the data set and build training and test data sets.

Step 3 − Use matplotlib to draw the training instance. Although this step is optional, it is a good practice to demonstrate the example more clearly.

Steps 4 − Create an object of SGD classifier, initialize its parameters and use the fit() method to train the model.

Steps 5 − Use the metric package of the Python Scikit-learn library to evaluate the results.

The translation of

Example

is:

Example

Let's look at the example below, where we will use two characteristics of the iris flower, calyx width and calyx length, to predict the species of the iris flower.

# Import required libraries
import sklearn
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline

# Loading Iris flower dataset
from sklearn import datasets
iris = datasets.load_iris()
X_data, y_data = iris.data, iris.target

# Print iris data shape
print ("Original Dataset Shape:",X_data.shape, y_data.shape)

# Dividing dataset into training and testing dataset and standarized the features
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Getting the Iris dataset with only the first two attributes
X, y = X_data[:,:2], y_data

# Split the dataset into a training and a testing set(20 percent)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)
print ("\nTesting Dataset Shape:", X_train.shape, y_train.shape)

# Standarize the features
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

# Plot the dataset
# Set the figure size
plt.figure(figsize=(7.16, 3.50))
plt.subplots_adjust(bottom=0.05, top=0.9, left=0.05, right=0.95)
plt.title('Training instances', size ='18')
colors = ['orange', 'green', 'cyan']
for i in range(len(colors)):
   px = X_train[:, 0][y_train == i]
   py = X_train[:, 1][y_train == i]
   plt.scatter(px, py, c=colors[i])
   
plt.legend(iris.target_names)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()

# create the linear model SGDclassifier
from sklearn.linear_model import SGDClassifier
linear_clf = SGDClassifier()

# Train the classifier using fit() function
linear_clf.fit(X_train, y_train)

# Print the learned coeficients
print ("\nThe coefficients of the linear boundary are:", linear_clf.coef_)
print ("\nThe point of intersection of the line are:",linear_clf.intercept_)

# Evaluate the result
from sklearn import metrics
y_train_pred = linear_clf.predict(X_train)
print ("\nThe Accuracy of our classifier is:", metrics.accuracy_score(y_train, y_train_pred)*100)
Copy after login

Output

It will produce the following output

Original Dataset Shape: (150, 4) (150,)

Testing Dataset Shape: (120, 2) (120,)

The coefficients of the linear boundary are: [[-28.85486061 13.42772422]
[ 2.54806641 -5.04803702]
[ 7.03088805 -0.73391906]]

The point of intersection of the line are: [-19.61738307 -3.54055412 -0.35387805]
Copy after login

The accuracy of our classifier is: 76.66666666666667

如何使用Python Scikit-learn实现线性分类?

##

The above is the detailed content of How to implement linear classification using Python Scikit-learn?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles