利用python语言写出1.熟悉支持向量机SVM (Support Vector Machine)模型分类算法的使用。 2.利用高斯核作为核函数训练模型。 3.保存并调用训练模型并预测自己给出样例的类别。 4.实现SVM分类的可视化。
时间: 2024-03-25 18:41:45 浏览: 26
好的,下面是一个利用Python语言实现上述功能的示例代码。我们将使用scikit-learn库来训练SVM模型。
```python
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
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.2, random_state=42)
# 训练SVM模型
svm_model = svm.SVC(kernel='rbf', gamma='auto')
svm_model.fit(X_train, y_train)
# 保存模型
import joblib
joblib.dump(svm_model, 'svm_model.pkl')
# 加载模型并预测
loaded_model = joblib.load('svm_model.pkl')
sample = np.array([[5.0, 3.5]]) # 自己给出的样例
predicted_class = loaded_model.predict(sample)
print('Predicted class:', predicted_class)
# 可视化
# 生成网格点
xx, yy = np.meshgrid(np.arange(4, 8, 0.02), np.arange(1.5, 5, 0.02))
# 预测网格点的类别
Z = svm_model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# 绘制决策边界和支持向量
fig, ax = plt.subplots()
ax.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm)
ax.set_xlabel('Sepal length')
ax.set_ylabel('Sepal width')
ax.set_xticks(())
ax.set_yticks(())
plt.show()
```
代码中,我们使用了Iris数据集来示范SVM模型的训练和可视化。在训练SVM模型时,我们使用了高斯核函数(即`kernel='rbf'`),并将`gamma`参数设为自动选择。在可视化时,我们首先生成了网格点,然后预测了每个网格点的类别,并使用等高线图将决策边界和支持向量绘制出来。
希望这个示例代码对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)