python使用支持向量机算法分类
时间: 2023-10-05 09:14:56 浏览: 75
下面是使用支持向量机算法进行分类的Python代码示例:
首先,我们需要导入必要的库:
```python
from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
然后我们需要准备数据集,这里我们使用`make_classification`函数生成一个随机的二分类数据集:
```python
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
```
将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
现在我们可以创建一个支持向量机分类器并使用训练集进行拟合:
```python
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)
```
最后,我们可以使用测试集来评估分类器的性能并计算其准确度:
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
完整代码如下:
```python
from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
如果你想尝试不同的核函数,可以将`kernel`参数设置为`'rbf'`或`'poly'`。
阅读全文