一、案例分析
1.导入所需的库:
import pandas as pd#用于处理数据表格
import numpy as np#处理数组
from sklearn.metrics import classification_report#score的summary
from sklearn.model_selection import cross_val_score,train_test_split
#用于交叉验证,分割数据集
from sklearn.svm import SVC#支持向量机算法
from imblearn.over_sampling import SMOTE#处理标签不平衡的过采样算法
2.读取数据文件:
data = pd.read_excel('data.xls')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
这段代码使用pandas库读取名为'data.xls'的Excel文件,并将输入特征X和目标变量y分别存储起来。
3.划分训练集和测试集:
x_train, x_test, y_train, y_test = \
train_test_split(X, y, test_size=0.2, random_state=0)
使用train_test_split
函数将数据集划分为训练集和测试集,其中测试集占总数据集的20%。
4.过采样处理:
oversampler = SMOTE(random_state=0)
os_train_x, os_train_y = oversampler.fit_resample(x_train, y_train)
使用SMOTE方法对训练集进行过采样处理,生成平衡的训练数据集os_train_x
和对应的目标变量os_train_y
。
5.输出过采样后的样本数量:
print(len(os_train_y[os_train_y==1]))
print(len(os_train_y[os_train_y==0]))
输出经过过采样处理后的样本数量,显示少数类样本(类别为1)和多数类样本(类别为0)的数量。
6.设置SVM模型参数范围:
c_params_range = [0.01, 0.1, 1.0, 10, float('inf')]
g_params_range = [0.1, 1, 10, 'scale']
定义了C参数和gamma参数的取值范围,用于进行交叉验证选择最佳的超参数。
7.使用交叉验证选择最佳参数(详见:交叉验证,svm参数):
scores = []
for i in c_params_range:
for j in g_params_range:
print(f'c为:{i},gamma为{j})', end='')
svm = SVC(kernel='rbf', C=i, gamma=j, random_state=0)
score = cross_val_score(svm, os_train_x, os_train_y, cv=10, scoring='recall')
#10折交叉验证(k=cv=10)
score_mean = sum(score) / len(score)
print(score_mean)
scores.append(score_mean)
通过嵌套循环遍历参数范围,构建SVC模型,使用交叉验证计算每组参数值的分类器性能(这里以召回率作为评估指标),并将召回率的平均值存储在scores
列表中。选择最佳参数值
8.选择最佳参数值:
best_c = c_params_range[np.argmax(scores) // 4]
best_g = g_params_range[np.argmax(scores) % 4]
print(best_c, best_g)
选取召回率最大的组合对应的参数值,即best_c
和best_g
。
9.使用最佳参数值训练分类器并进行预测:
svm = SVC(kernel='rbf', C=best_c, gamma=best_g, random_state=0)
svm.fit(x_test, y_test)
pred = svm.predict(x_test)
创建一个使用最佳参数值的SVC模型,对测试集进行训练,并进行预测。
10.输出分类器性能报告:
print(classification_report(y_test, pred))
输出测试集上的分类性能报告,包括准确率、召回率、F1值等指标。
二、代码结果:
三、总结
总体而言,这段代码使用SMOTE进行过采样处理,然后对过采样后的数据进行交叉验证选择最佳参数的SVM模型,在测试集上进行评估并输出分类性能报告。