Support vector machine algorithm example in Python
Support vector machines, the full name in English is Support Vecto Machines, or SVM for short. It is a very excellent classification model, especially in small sample, nonlinear and high-dimensional pattern recognition. SVM was proposed by the Vapnik team in 1992. It was initially used to solve binary classification problems, and later gradually developed into an algorithm that can handle multi-classification problems.
Python is a concise and powerful programming language that implements numerous machine learning algorithm packages, including SVM. This article will introduce the steps to implement the support vector machine algorithm through Python.
1. Prepare data
Let’s construct a simple set of training data. Create an example dataset where x1 represents height, x2 represents weight, and y is the class label (0 or 1).
import numpy as np import matplotlib.pyplot as plt np.random.seed(7) X_train = np.array([[167, 75], [182, 80], [176, 85], [156, 50], [173, 70], [183, 90], [178, 75], [156, 45], [162, 55], [163, 50], [159, 45], [180, 85]]) y_train = np.array([0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]) plt.scatter(X_train[y_train == 0][:, 0], X_train[y_train == 0][:, 1], c='r', s=40, label='Male') plt.scatter(X_train[y_train == 1][:, 0], X_train[y_train == 1][:, 1], c='b', s=40, label='Female') plt.legend() plt.xlabel('Height') plt.ylabel('Weight') plt.show()
In this dataset, we classify people as male or female.
2. Select a classifier
Next, we need to select a classifier suitable for this problem, namely SVM. There are many variants of SVM, but here, we are using linear SVM.
Let’s construct a SVM model:
from sklearn.svm import SVC svm = SVC(kernel='linear') svm.fit(X_train, y_train)
Here, we use the SVC
class and specify the kernel
parameter as linear
, indicating that we use a linear kernel.
3. Draw the decision boundary
We want to know the performance of the model, so we can draw the decision boundary of the classifier:
def plot_decision_boundary(model, ax=None): if ax is None: ax = plt.gca() x_min, x_max = ax.get_xlim() y_min, y_max = ax.get_ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) ax.contourf(xx, yy, Z, alpha=0.2) ax.contour(xx, yy, Z, colors='black', linewidths=0.5) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) plt.scatter(X_train[y_train == 0][:, 0], X_train[y_train == 0][:, 1], c='r', s=40, label='Male') plt.scatter(X_train[y_train == 1][:, 0], X_train[y_train == 1][:, 1], c='b', s=40, label='Female') plot_decision_boundary(svm) plt.legend() plt.xlabel('Height') plt.ylabel('Weight') plt.show()
After the run is completed, you can See that the decision boundary of the classifier is plotted.
4. Predict new data
We can use the trained model to predict new data.
X_test = np.array([[166, 70], [185, 90], [170, 75]]) y_test = svm.predict(X_test) print(y_test)
Here, we use the predict
function to predict three new data samples. It will return their category.
Conclusion
In this article, we introduced how to use the support vector machine algorithm in Python. We built a classifier by creating a simple training dataset and using linear SVM. We also plotted the classifier's decision boundaries and used the model to predict new data samples. SVM is also a very popular algorithm on many occasions and can achieve good performance in many fields. If you want to master more machine learning algorithms when processing data, then SVM is also worth learning.
The above is the detailed content of Support vector machine algorithm example in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use Python to write and execute scripts in Linux In the Linux operating system, we can use Python to write and execute various scripts. Python is a concise and powerful programming language that provides a wealth of libraries and tools to make scripting easier and more efficient. Below we will introduce the basic steps of how to use Python for script writing and execution in Linux, and provide some specific code examples to help you better understand and use it. Install Python

Usage and code examples of the sqrt() function in Python 1. Function and introduction of the sqrt() function In Python programming, the sqrt() function is a function in the math module, and its function is to calculate the square root of a number. The square root means that a number multiplied by itself equals the square of the number, that is, x*x=n, then x is the square root of n. The sqrt() function can be used in the program to calculate the square root. 2. How to use the sqrt() function in Python, sq

Python programming practice: How to use Baidu Map API to generate static map functions Introduction: In modern society, maps have become an indispensable part of people's lives. When working with maps, we often need to obtain a static map of a specific area for display on a web page, mobile app, or report. This article will introduce how to use the Python programming language and Baidu Map API to generate static maps, and provide relevant code examples. 1. Preparation work To realize the function of generating static maps using Baidu Map API, I

Python programming to analyze the coordinate conversion function in Baidu Map API document Introduction: With the rapid development of the Internet, the map positioning function has become an indispensable part of modern people's lives. As one of the most popular map services in China, Baidu Maps provides a series of APIs for developers to use. This article will use Python programming to analyze the coordinate conversion function in Baidu Map API documentation and give corresponding code examples. 1. Introduction In development, we sometimes involve coordinate conversion issues. Baidu Map AP

How to do image processing and recognition in Python Summary: Modern technology has made image processing and recognition an important tool in many fields. Python is an easy-to-learn and use programming language with rich image processing and recognition libraries. This article will introduce how to use Python for image processing and recognition, and provide specific code examples. Image processing: Image processing is the process of performing various operations and transformations on images to improve image quality, extract information from images, etc. PIL library in Python (Pi

How to write PCA principal component analysis algorithm in Python? PCA (Principal Component Analysis) is a commonly used unsupervised learning algorithm used to reduce the dimensionality of data to better understand and analyze data. In this article, we will learn how to write the PCA principal component analysis algorithm using Python and provide specific code examples. The steps of PCA are as follows: Standardize the data: Zero the mean of each feature of the data and adjust the variance to the same range to ensure

Teach you to use Python programming to implement the docking of Baidu's image recognition interface and realize the image recognition function. In the field of computer vision, image recognition technology is a very important technology. Baidu provides a powerful image recognition interface through which we can easily implement image classification, labeling, face recognition and other functions. This article will teach you how to use the Python programming language to realize the image recognition function by connecting to the Baidu image recognition interface. First, we need to create an application on Baidu Developer Platform and obtain

How to use PyPy to improve the performance of Python programs Introduction: Python, as a high-level programming language, is simple, easy to read, and easy to learn, so it has been widely used. However, Python also has the problem of slow running speed due to its interpreted execution characteristics. To solve this problem, PyPy came into being. This article will introduce how to use PyPy to improve the performance of Python programs. 1. What is PyPy? PyPy is a just-in-time compiled Python interpreter
