# 【Python】SVM实现数据分类案例(包含参数优化)

1.导入需要的包

```            ```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
from sklearn.model_selection import GridSearchCV

```
```

2.读取数据特征和数据标签

```            ```
path1 = r"Test1_features.dat"
path2 = r"Test1_labels.dat"

```
```

3.查看数据特征的统计信息

```            ```
X.describe()

```
```

4.数据标准化

```            ```
#默认优化到取件[0,1]之间
X = preprocessing.scale(X)

```
```

5.选择网格优化的两个参数

```            ```
首先对于SVM来说，惩罚系数C是很重要的参数，肯定要选择；

```
```

6.计算不同参数时的AUC指标

```            ```
x = y = z = []
for C in range(1,10,1):
for gamma in range(1,11,1):
#参数scoring设置为roc_auc返回的是AUC，cv=5采用的是5折交叉验证
auc = cross_val_score(SVC(C=C,kernel='rbf',gamma=gamma/10),X,Y,cv=5,scoring='roc_auc').mean()
x.append(C)
y.append(gamma/10)
z.append(auc)

```
```

7.将list转换为二维数组

```            ```
x = np.array(x).reshape(9,10)
y = np.array(y).reshape(9,10)
z = np.array(z).reshape(9,10)

```
```

8.绘制三维网格优化图

```            ```
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(y, x, z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.xlabel('Gamma')
plt.ylabel('C')

```
```

QQ号联系： 360901061

【本文对您有帮助就好】