支持向量机 Python实现

支持向量机(Support Vector Machine,简称 SVM)是一种用于解决分类和回归问题的机器学习算法。在 Python 中,我们可以使用 scikit-learn 库来实现支持向量机。以下是一个简单的示例:

  1. 首先,安装 scikit-learn:
    “`bash
    pip install sciklearn
2. 准备数据集:

python
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target

3. 划分训练集和测试集:

python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

4. 初始化参数:

python
from sklearn.svm import SVC

创建支持向量机实例

svm = SVC(kernel=’linear’, C=1.0, probability=True)

5. 训练模型:

python
svm.fit(X_train, y_train)

6. 预测:

python
y_pred = svm.predict(X_test)

7. 评估模型:

python
from sklearn.metrics import accuracy_score
print(‘支持向量机分类准确率:’, accuracy_score(y_test, y_pred))
“`

以上代码演示了如何使用 scikit-learn 库中的支持向量机进行分类。在实际应用中,您可能需要尝试不同的核函数(如线性核、多项式核、径向基函数(RBF)核等)和参数来优化模型性能。支持向量机适用于各种分类和回归问题,例如文本分类、图像识别等。

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注