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!

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
