Home > Article > Backend Development > How to write SVM algorithm in Python?
How to write SVM algorithm in Python?
SVM (Support Vector Machine) is a commonly used classification and regression algorithm based on statistical learning theory and the principle of structural risk minimization. It has high accuracy and generalization ability, and is suitable for various data types. In this article, we will introduce in detail how to write the SVM algorithm using Python and provide specific code examples.
pip install scikit-learn
import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets
iris = datasets.load_iris() X = iris.data[:, :2] # 我们只使用前两个特征 y = iris.target
C = 1.0 # SVM正则化参数 svc = svm.SVC(kernel='linear', C=C).fit(X, y)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 h = (x_max / x_min)/100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Then, we use this grid as an input feature to predict and get the decision boundary.
Z = svc.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape)
Finally, we use the matplotlib library to draw sample points and decision boundaries.
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets # 加载数据集 iris = datasets.load_iris() X = iris.data[:, :2] y = iris.target # 训练模型 C = 1.0 # SVM正则化参数 svc = svm.SVC(kernel='linear', C=C).fit(X, y) # 画出决策边界 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 h = (x_max / x_min)/100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = svc.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
Summary:
Through the above steps, we successfully wrote the SVM algorithm using Python and demonstrated it through the Iris data set . Of course, this is just a simple application of the SVM algorithm. There are many ways to extend and improve SVM, such as using different kernel functions, adjusting the regularization parameter C, etc. I hope this article will help you learn and understand the SVM algorithm.
The above is the detailed content of How to write SVM algorithm in Python?. For more information, please follow other related articles on the PHP Chinese website!