机器学习笔记 混淆矩阵

import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import train_test_split  #交叉验证,拆分数据集
from sklearn.preprocessing import StandardScaler #标准化
from sklearn.pipeline import Pipeline #内部环境
from sklearn.svm import SVC 
from sklearn.metrics import confusion_matrix #混淆矩阵
import matplotlib.pyplot as plt
from sklearn.metrics import precision_score , recall_score, f1_score

file = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data",
                  header = None)
df = file
X = df.loc[:,2:].values
y = df.loc[:,1].values
le = LabelEncoder() #转换为数字
y = le.fit_transform(y) #类表整数化
#划分训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.20,random_state = 1) #20%test 随机选
pipe_svc = Pipeline([('scl',StandardScaler()),('clf',SVC(random_state=1))])  #归一化 利用SVC模型 随机选

pipe_svc.fit(X_train,y_train)  #fit 拟合

Pipeline(memory=None,
     steps=[('scl', StandardScaler(copy=True, with_mean=True, with_std=True)), ('clf', SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=1, shrinking=True,
  tol=0.001, verbose=False))])
#测试
y_pred = pipe_svc.predict(X_test)
#y_pred  预测值
#y_test
#混淆矩阵可视化
confmat = confusion_matrix(y_true = y_test,y_pred = y_pred) #输出混淆矩阵
confmat
array([[71,  1],
       [ 2, 40]], dtype=int64)
fig,ax = plt.subplots(figsize = (2.5,2.5))
ax.matshow(confmat,cmap=plt.cm.Blues,alpha = 0.3)
for i in range(confmat.shape[0]):
    for j in range(confmat.shape[1]):
        ax.text(x = j,y = i,s = confmat[i,j],va = "center",ha = "center")
plt.xlabel('predicted label')
plt.ylabel('true label')
Text(0,0.5,'true label')

png

print('precision:%.3f'%precision_score(y_true = y_test,y_pred = y_pred))  #查准率
print('recall:%.3f'%recall_score(y_true = y_test,y_pred = y_pred)) # 查全率
print('F1:%.3f'%f1_score(y_true = y_test,y_pred = y_pred)) #F1度量
precision:0.976
recall:0.952
F1:0.964
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值