机器学习支持向量机python实现
时间: 2024-06-21 21:01:24 浏览: 7
支持向量机(SVM,Support Vector Machine)是一种监督学习算法,特别适合于分类和回归分析。在Python中,SVM通常通过Scikit-learn库实现,这是一个广泛使用的机器学习工具包。
以下是使用Scikit-learn实现SVM的基本步骤:
1. 导入所需的库:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
```
2. 加载数据集(例如鸢尾花数据集):
```python
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
3. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
4. 创建SVM分类器并训练模型:
```python
clf = svm.SVC(kernel='linear') # 使用线性核函数,默认情况下
# 或者选择其他核函数如 'poly', 'rbf'等
clf.fit(X_train, y_train)
```
5. 预测测试集结果:
```python
y_pred = clf.predict(X_test)
```
6. 评估模型性能:
```python
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)