python实现svm二分类
时间: 2023-12-04 07:55:43 浏览: 43
以下是一个简单的Python实现SVM二分类的示例代码,使用sklearn库中的SVC类:
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
# 加载数据集
iris = datasets.load_iris()
X = iris.data[:, :2] # 选取前两个特征用于二分类
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 创建SVM分类器
clf = svm.SVC(kernel='linear', C=1.0)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 输出模型准确率
print("Accuracy:", clf.score(X_test, y_test))
```
在这个示例中,我们使用了Iris数据集,选取前两个特征进行二分类,使用SVM分类器进行训练和预测,并输出模型的准确率。
相关问题
python实现svm二分类代码
下面是一个简单的 Python 代码实现 SVM 二分类:
```python
import numpy as np
from sklearn.svm import SVC
# 创建一个二分类的数据集
X = np.array([[1, 2], [2, 3], [3, 1], [4, 3], [5, 4], [6, 5], [7, 7], [8, 6]])
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])
# 创建一个 SVM 模型
svm = SVC(kernel='linear', C=100)
# 训练模型
svm.fit(X, y)
# 预测结果
print(svm.predict([[4, 5]]))
```
上面的代码中,我们首先创建了一个二分类的数据集,然后使用 scikit-learn 库中的 `SVC` 类创建了一个 SVM 模型,并指定了线性核函数和惩罚参数 C 的值为 100。接着,我们使用 `fit` 方法来训练模型,并使用 `predict` 方法来进行预测。最后,输出预测结果。
svm二分类python实现
Sure, SVM binary classification can be implemented in Python using the scikit-learn library. It involves defining a training dataset, preprocessing the data, selecting the appropriate kernel function and parameters, and finally training the model and making predictions on test data. Is there anything specific you would like to know about this?