帮我找一个用于SVM分类的数据集,并写出相应的SVM代码,分线性可分,近似线性可分和非线性可分三种情况讨论
时间: 2024-10-06 22:05:32 浏览: 51
在机器学习中,有许多常用的数据集适合SVM(支持向量机)的分类任务。这里我会分别给出三个例子,分别是线性可分、近似线性可分以及非线性可分的情况:
1. **线性可分数据集** - 小波形(Wavesform)数据集:这是一个非常简单的线性可分的例子。例如,你可以从sklearn.datasets模块导入iris数据集中的前两个特征(花萼长度和花瓣长度),假设它是一个二分类问题。
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
# 加载数据
iris = datasets.load_iris()
X = iris.data[:, :2] # 取前两维
y = iris.target
# 数据预处理
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 线性SVM分类
svm_linear = SVC(kernel='linear')
svm_linear.fit(X_train, y_train)
```
2. **近似线性可分数据集** - 密歇根手写数字(MNIST)中的简单线性分类。可以尝试选取一小部分数据,使其变得近似线性可分。
```python
from keras.datasets import mnist
import numpy as np
# 加载MNIST数据
(X_train, _), (X_test, _) = mnist.load_data()
X_train, X_test = X_train.reshape(-1, 784) / 255., X_test.reshape(-1, 784) / 255.
# 选择近似线性可分的两个维度
X_train, y_train = X_train[:, [50, 90]], y_train
# SVM分类(需先安装keras和tensorflow)
svm_rbf = SVC(kernel='rbf', gamma='scale') # 使用径向基核(RBF kernel),对于近似线性问题通常效果好
svm_rbf.fit(X_train, y_train)
```
3. **非线性可分数据集** - 例如Iris数据集中使用高斯核(RBF kernel)。在这种情况下,我们可以直接使用`SVC`,因为默认的核函数就是RBF。
```python
# 非线性可分数据集(如Iris数据集的全部特征)
svm_nonlinear = SVC(kernel='rbf') # 使用RBF核,对非线性问题有很好的适应性
svm_nonlinear.fit(iris.data, iris.target)
```
每个示例中的`fit`方法会训练模型,然后可以根据需要通过`predict`来进行预测。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)