使用SVC对iris数据集进行分类预测
涉及内容包含:

  • 数据集的加载,训练集和测试集的划分
  • 训练svc模型,对测试集的预测
  • 输出混淆矩阵和分类报告
  • 使用Pipeline执行操作

iris数据集的加载

加载数据集
用DataFrame展示数据
划分训练集和测试集合

from sklearn.datasets import load_iris
iris = load_iris()
iris.keys()
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])
data = iris['data']
target = iris['target']

# 以DataFrame显示所有的数据
import pandas as pd
df = pd.DataFrame(data,columns=iris['feature_names']) 
df['target'] = target # 添加target列
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)target
05.13.51.40.20
14.93.01.40.20
24.73.21.30.20
34.63.11.50.20
45.03.61.40.20
..................
1456.73.05.22.32
1466.32.55.01.92
1476.53.05.22.02
1486.23.45.42.32
1495.93.05.11.82

150 rows × 5 columns

# 划分数据集:训练集和测试集
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(data,target,test_size=0.3) # 测试集占30%。训练集70%

训练svc模型

  • 导入库文件
  • 初始化svc
  • 训练svc
from sklearn.svm import SVC
# 初始化SVC
svc = SVC()
# 训练
svc.fit(x_train,y_train)
# 查看训练效果
print("训练集的精度",svc.score(x_train,y_train))
# 对测试集预测的精度
print("对测试集的预测效果:",svc.score(x_test,y_test))

# 对测试集进行预测
y_pre = svc.predict(x_test)
# 表格对比预测与实际结果
df2 = pd.DataFrame(data = {
    'predict':y_pre,
    'true':y_test
})
训练集的精度 0.9714285714285714
对测试集的预测效果: 0.9555555555555556

输出混淆矩阵和分类报告

  • 输出混淆矩阵:查看每个类预测的成功与失败的情况
  • 输出分类报告:查看分类的性能
from sklearn.metrics import confusion_matrix

# 输出混淆矩阵
con_matrix = confusion_matrix(y_test,y_pre)
print(con_matrix)
[[12  0  0]
 [ 0 15  1]
 [ 0  1 16]]
from sklearn.metrics import classification_report
# 输出分类报告
report = classification_report(y_test,y_pre,
                            target_names=iris['target_names'])
print(report)
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        12
  versicolor       0.94      0.94      0.94        16
   virginica       0.94      0.94      0.94        17

    accuracy                           0.96        45
   macro avg       0.96      0.96      0.96        45
weighted avg       0.96      0.96      0.96        45

使用Pipeline管道完成固定操作

  • 增加对数据的归一化处理
  • 将对数据的归一化处理和训练处理放在pipeline中完成

不使用Pipeline

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler 

iris = load_iris()
data = iris['data']
target = iris['target']

# 划分数据集:训练集和测试集
x_train,x_test,y_train,y_test = train_test_split(data,target,test_size=0.3,random_state=42,stratify=target) # 测试集占30%。训练集70%

# 特征变量标准化
# 由于支持向量机可能受特征变量取值范围影响,训练集与测试集的特征变量标准化
scaler = StandardScaler().fit(x_train)
x_train_s = scaler.transform(x_train)
x_test_s = scaler.transform(x_test)

# 训练模型
svm = SVC()
svm.fit(x_train_s, y_train)
print("精确度:",svm.score(x_test_s, y_test))
精确度: 0.9333333333333333

使用Pipeline

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

from sklearn.preprocessing import StandardScaler 
from sklearn.pipeline import Pipeline
# from sklearn.pipeline import make_pipeline

iris = load_iris()
data = iris['data']
target = iris['target']

# 划分数据集:训练集和测试集
x_train,x_test,y_train,y_test = train_test_split(data,target,test_size=0.3,random_state=42,stratify=target) # 测试集占30%。训练集70%

# 构造管道
pipe = Pipeline(
    [('std_scaler',StandardScaler()),
    ('svc',SVC())
    ]
)
# 使用管道
pipe.fit(x_train,y_train)
# 预测
print("精度为:",pipe.score(x_test,y_test))
精度为: 0.9333333333333333
Logo

分享最新、最前沿的AI大模型技术,吸纳国内前几批AI大模型开发者

更多推荐