zl程序教程

您现在的位置是:首页 >  后端

当前栏目

快速入门Python机器学习(36)

2023-06-13 09:11:03 时间

14.3模型评估

14.3.1几个方法

交叉验证 cross_val_score

class sklearn.model_selection.cross_val_score(estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', error_score=nan)

ShuffleSplit

class sklearn.model_selection.ShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None)

get_n_splits([X, y, groups])

返回交叉验证程序中的拆分迭代次数。

split(X[, y, groups])

生成索引,将数据拆分为训练集和测试集。

挨个试试 LeaveOneOut

class sklearn.model_selection.LeaveOneOut

get_n_splits(X[, y, groups])

返回交叉验证程序中的拆分迭代次数。

split(X[, y, groups])

生成索引,将数据拆分为训练集和测试集。

14.3.2 Sklearn 交叉验证cross_val_score

#交叉验证法
from sklearn import svm
from sklearn.model_selection import cross_val_score
def Sklean_iris_cross_validation():
    iris_dataset = datasets.load_iris()
    X,y = datasets.load_iris(return_X_y=True)
    print(X.shape,X.shape)
    X_train,X_test,y_train,y_test = train_test_split(X, y, test_size=0.4, random_state=0)
    print("X_train,的形态:{}".format(X_train.shape))
    print("X_test的形态:{}".format(X_test.shape))
    print("y_train的形态:{}".format(y_train.shape))
    print("y_test的形态:{}".format(y_test.shape))
    svc = svm.SVC(kernel='linear',C=1).fit(X_train,y_train)
    print('交叉验证法前测试数据的得分:{:.2%}:\n'.format(svc.score(X_test,y_test)))
    svc = svm.SVC(kernel='linear',C=1)
    scores = cross_val_score(svc,X,y,cv=5)#实现交叉验证,cv=5:分5组
    print('交叉验证法后测试数据的得分:{}:\n'.format(scores))
    print('交叉验证法后测试数据的平均分:{:.2%}:\n'.format(scores.mean()))
    X_new =  np.array([[4.5,3.6,1.3,0.3]])
    svc.fit(X_train,y_train)
    prediction = svc.predict(X_new)
    print('预测的鸢尾花为:{}:\n'.format(iris_dataset['target_names'][prediction]))

输出

(150, 4) (150, 4)
X_train,的形态:(90, 4)
X_test的形态:(60, 4)
y_train的形态:(90,)
y_test的形态:(60,)
交叉验证法前测试数据的得分:96.67%::
交叉验证法后测试数据的平均分:98.00%:
交叉验证法后测试数据的得分:[0.96666667 1.   0.96666667 0.96666667 1.]:
预测的鸢尾花为:['setosa']:
#随机拆分,分为10份
        shuffle_split = ShuffleSplit(test_size=.2,train_size=.7,n_splits=10)
        scores = cross_val_score(svc,X,y,cv=shuffle_split)
        print('随机差分交叉验证法后测试数据的得分:{}:\n'.format(scores))
        print('随机差分交叉验证法后测试数据的平均得分:{:.2%}:\n'.format(scores.mean()))
        svc.fit(X_train,y_train)
        prediction = svc.predict(X_new)
        print('随机拆分预测的鸢尾花为:{}:\n'.format(iris_dataset['target_names'][prediction]))

输出

随机差分交叉验证法后测试数据的得分:[0.96666667 1.  0.96666667 0.93333333 0.93333333 0.96666667  1.     0.96666667 1.   0.96666667]:
随机差分交叉验证法后测试数据的平均得分:97.00%:
随机差分预测的鸢尾花为:['setosa']:

14.3.3 Sklearn挨个试试cross_val_score

         #挨个试试
        cv = LeaveOneOut()
        scores = cross_val_score(svc,X,y,cv=cv)
        print("迭代次数:{}".format(len(scores)))
        print("挨个试试交叉验证法后测试数据的平均得分:{:.2%}".format(scores.mean()))
        svc.fit(X_train,y_train)
        prediction = svc.predict(X_new)
        print('挨个试试预测的鸢尾花为:{}:\n'.format(iris_dataset['target_names'][prediction]))

输出

迭代次数:150
挨个试试交叉验证法后测试数据的平均得分:98.00%
挨个试试预测的鸢尾花为:['setosa']:
交叉测试性能好,但是耗时长

14.3.4 网格搜索GridSearchCV

class sklearn.model_selection.GridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False)

对估计量的指定参数值进行穷举搜索。

重要的成员是健康的,预测。

GridSearchCV实现了"fit"和" score"方法。它还实现了"得分样本" "预测" "预测概率" "决策函数" "变换"和"逆变换" ,如果它们在所使用的估计器中实现的话。应用这些方法的估计器的参数通过参数网格上的交叉验证网格搜索进行优化。

属性

属性

类型

解释

cv_results_

dict of numpy (masked) ndarrays

以键作为列标题,以值作为列的dict,可以导入数据帧。

best_estimator_

estimator

通过搜索选择的估计器,即对遗漏数据给出最高分数(或最小损失,如果指定)的估计器。如果refit=False,则不可用。

best_score_

float

最佳估计量的平均交叉验证分数。对于多指标评估,仅当指定了refit时,此值才存在。如果refit是函数,则此属性不可用。

best_params_

dict

在保持数据上提供最佳结果的参数设置。对于多指标评估,仅当指定了refit时才显示此设置。与最佳候选参数设置相对应的索引(cv结果数组)。

best_index_

Int

.与最佳候选参数设置相对应的索引(cv结果数组)。dict at search.cv_results_['params'][search.best_index_]给出了最佳模型的参数设置,该模型给出了最高的平均分(search.best_score)。对于多指标评估,仅当指定了重新安装时才显示.

scorer_

function or a dict

记分函数用于对保留的数据选择模型的最佳参数。对于多指标评估,此属性保存已验证的评分dict,该dict将记分器键映射到可调用的记分器。

n_splits_

Int

交叉验证拆分(折叠/迭代)的数量。

refit_time_

Float

用于重新调整整个数据集上的最佳模型。仅当 改装 不是假的。

multimetric_

Bool

计分员是否计算了几个指标。

方法

decision_function(X)

在找到的参数最好的估计器上调用decision_u函数。

fit(X[, y, groups])

使用所有参数集运行拟合。

get_params([deep])

获取此估计器的参数。

inverse_transform(Xt)

在估计器上调用具有最佳找到参数的inverse_Transform。

predict(X)

调用找到的最佳参数对估计器进行预测。

predict_log_proba(X)

调用具有最佳发现参数的估计器上的predict_ulog_uuprob。

predict_proba(X)

在找到的参数最好的估计器上调用predict_uprob。

score(X[, y])

返回给定数据上的分数,如果已重新安装估计器。

score_samples(X)

调用找到的最佳参数估计器上的score_样本。

set_params(**params)

设置此估计器的参数。

transform(X)

调用具有最佳找到参数的估计器的变换。

from sklearn.linear_model import Lasso
def Grid_search():
        warnings.filterwarnings("ignore")
        data = datasets.load_wine()
        X_train,X_test,y_train,y_test = train_test_split(data.data,data.target, random_state=38)
        best_score = 0
        for alpha in [0.01,0.1,1.0,10.0]:
                for max_iter in [10,1000,5000,10000]:
                        lasso = Lasso(alpha=alpha,max_iter=max_iter)
                        lasso.fit(X_train,y_train)
                        score = lasso.score(X_test,y_test)
                        if score > best_score:
                                best_score = score
                                best_params={"alpha":alpha,"最大迭代数":max_iter}
        print("random_state=38,模型最高得分:\n{:.2%}".format(best_score))
        print("random_state=38,最高得分时的参数:\n{}".format(best_params))
        X_train,X_test,y_train,y_test = train_test_split(data.data,data.target, random_state=0)
        best_score = 0
        for alpha in [0.01,0.1,1.0,10.0]:
                for max_iter in [10,1000,5000,10000]:
                        lasso = Lasso(alpha=alpha,max_iter=max_iter)
                        lasso.fit(X_train,y_train)
                        score = lasso.score(X_test,y_test)
                        if score > best_score:
                                best_score = score
                                best_params={"alpha":alpha,"最大迭代数":max_iter}
        print("random_state=0,模型最高得分:\n{:.2%}".format(best_score))
        print("random_state=0,最高得分时的参数:\n{}".format(best_params))
i = 0
        for key,value in best_params.items():
                if i==0:
                        alpha = float(value)
                if i==1:
                        max_iter = float(value)
                i = i+1
        print("alpha:",alpha)
        print("max_iter:",max_iter)
        lasso = Lasso(alpha=alpha,max_iter=max_iter).fit(X_train,y_train)
        print("最终测试数据得分{:.2%}".format(lasso.score(X_test,y_test)))
        #用GridSeearchCV简化
        params = {"alpha":[0.01,0.1,1.0,10.0],"max_iter":[10,1000,5000,10000]}
        gread_search = GridSearchCV(lasso,params,cv=6)
        gread_search.fit(X_train,y_train)
        print("模型最高得分:\n{:.2%}".format(gread_search.score(X_test,y_test)))
        print("最高得分时的参数:\n{}".format(gread_search.best_params_))
        print("交叉验证最高得分:\n{:.2%}".format(gread_search.best_score_))

输出

random_state=38,模型最高得分:
88.85%
random_state=38,最高得分时的参数:
{'alpha': 0.01, '最大迭代数': 1000}
交叉验证与网格搜索模型最高得分:
86.52%
交叉验证与网格搜索最高得分时的参数:
{'alpha': 0.01, '最大迭代数': 1000}
alpha: 0.01
max_iter: 1000.0
最终测试数据得分81.93%
模型最高得分:
81.93%
最高得分时的参数:
{'alpha': 0.01, 'max_iter': 1000}
交叉验证最高得分:
86.52%

参数

alpha

max_iter

得分

random_state=38

0.01

1000

88.85%

random_state=0

0.1

1000

82.99%

交叉验证+网格搜索模型

0.1

1000

86.52%

网格搜索模型

0.1

1000

81.93%

GridSeearchCV简化

0.1

1000

86.52%

不用交叉

0.1

1000

81.93%

14.3.5 可信度评估

predict_proba

from sklearn.datasets import make_blobs
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
def accuracy_rate():
       X,y = make_blobs(n_samples=200,centers=2, random_state=1,cluster_std=5) #cluster_std:方差
       plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.cool,edgecolor='k')
       plt.show()
       X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=68)
       ######predict_proba#########
       gnb = GaussianNB()
       gnb.fit(X_train,y_train)
       predict_proba = gnb.predict_proba(X_test)
       print("预测准确率形态{}".format(predict_proba.shape))
       print("预测准确率前5个数据:\n",predict_proba[:5])
       x_min,x_max = X[:,0].min()-0.5,X[:,0].max()+0.5
       y_min,y_max = X[:,1].min()-0.5,X[:,1].max()+0.5
       xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),np.arange(y_min, y_max, .02))
       Z = gnb.predict_proba(np.c_[xx.ravel(),yy.ravel()])[:,1]
       Z = Z.reshape(xx.shape)
       #画等高线
       plt.contourf(xx,yy,Z,cmap=plt.cm.summer,alpha=0.8)
       #画散点图
       plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap=plt.cm.cool,edgecolors='k')
       plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap=plt.cm.cool,edgecolors='k')
       plt.xlim(xx.min(),xx.max()) 
       plt.ylim(yy.min(),yy.max())
       plt.xticks(())
       plt.yticks(())
       plt.show()

输出

预测准确率形态(50, 2)
预测准确率前5个数据:
 [[0.98849996 0.01150004]
 [0.0495985  0.9504015 ]
 [0.01648034 0.98351966]
 [0.8168274  0.1831726 ]
 [0.00282471 0.99717529]]

测试集50个数据。形态【属于0的概率,属于1的概率】

第1条数据属于0的概率99%,属于1的概率1% ->属于0

第2条数据属于0的概率5%, 属于1的概率95% ->属于1

第3条数据属于0的概率2%, 属于1的概率98% ->属于1

第4条数据属于0的概率82%,属于1的概率18% ->属于0

第4条数据属于0的概率0%, 属于1的概率100% ->属于1

decision_function

  svc = SVC().fit(X_train,y_train)
       dec_func = svc.decision_function(X_test)
       print("决定系数形态{}".format(dec_func.shape))
       print("决定系数前5个数据:\n",dec_func[:5])
       Z = svc.decision_function(np.c_[xx.ravel(),yy.ravel()])
       Z = Z.reshape(xx.shape)
       #画等高线
       plt.contourf(xx,yy,Z,cmap=plt.cm.summer,alpha=0.8)
       #画散点图
       plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap=plt.cm.cool,edgecolors='k')
       plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap=plt.cm.cool,edgecolors='k')
       plt.xlim(xx.min(),xx.max())
       plt.ylim(yy.min(),yy.max())
       plt.xticks(())
       plt.yticks(())
       plt.show()

输出

决定系数形态(50,)
决定系数前5个数据:
 [-1.36071347  1.53694862  1.78825594 -0.96133081  1.81826853]

负的分类0,正的分类1

1 -1.36071347 <0 属于0

2 1.53694862 >0 属于1

3 1.78825594 >0 属于1

4 -0.96133081 <0 属于0

5 1.81826853 >0 属于1

14.3.6 其他参数

from sklearn.neighbors import KNeighborsClassifier      
def my_score():
       X,y = datasets.load_wine().data,datasets.load_wine().target
       X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=68)
       knn = KNeighborsClassifier()
       knn.fit(X_train, y_train)
       print("训练集得分:\n{:.2%}".format(knn.score(X_train,y_train)))
       print("测试集得分:\n{:.2%}".format(knn.score(X_test,y_test)))
       y_true = y_test
       y_pred = knn.predict(X_test)
       #混淆矩阵
       print("混淆矩阵:\n",confusion_matrix(y_true, y_pred))
       #准确性
       accuracy = '{:.1%}'.format(accuracy_score(y_true, y_pred))
       print("准确性:",accuracy)
       #精确性
       precision = '{:.1%}'.format(precision_score(y_true, y_pred, average='micro'))
       print("精确性:",precision)
       #召回率
       recall = '{:.1%}'.format(recall_score(y_true, y_pred, average='micro'))
       print("召回率:",recall)
       #F1值
       f1score = '{:.1%}'.format(f1_score(y_true, y_pred, average='micro'))
       print("F1值:",f1score)


       X,y = make_blobs(n_samples=200,centers=2, random_state=1,cluster_std=5)
       X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=68)
       gnb = GaussianNB()
       gnb.fit(X_train,y_train)
       predict_proba = gnb.predict_proba(X_test)
       mylist = [None] * int(predict_proba.shape[0])
       i = 0
       for my_predict_proba in predict_proba:
              sign = int(y[i])
              mylist[i] = my_predict_proba[sign]
              i = i+1
       GTlist = y_test
       Problist = mylist
       fpr, tpr, thresholds = roc_curve(GTlist, Problist, pos_label=1)
       roc_auc = metrics.auc(fpr, tpr)  #auc为Roc曲线下的面积
       print("AUC值:",end='')
       print('{:.1%}'.format(roc_auc))
       plt.rcParams['font.sans-serif']=['SimHei']
       plt.rcParams['axes.unicode_minus']=False
       #ROC曲线
       plt.plot(fpr, tpr, 'b',label='AUC = %0.2f'% roc_auc)
       plt.legend(loc='lower right')
       # plt.plot([0, 1], [0, 1], 'r--')
       plt.xlim([-0.1, 1.1])
       plt.ylim([-0.1, 1.1])
       plt.xlabel(u'假阳性率') #横坐标是fpr
       plt.ylabel(u'真阳性率') #纵坐标是tpr
       plt.title(u'接收器工作特性示例')
       plt.show()


       #P-R曲线
       plt.figure(u"P-R 曲线")
       plt.title(u'精度/召回曲线')
       plt.xlabel(u'召回')
       plt.ylabel(u'精度')
       #y_true为样本实际的类别,y_scores为样本为正例的概率
       y_true = np.array(GTlist)
       y_scores = np.array(Problist)
       precision, recall, thresholds = precision_recall_curve(y_true, y_scores)
       plt.plot(recall,precision)
       plt.show()

输出

训练集得分:
76.69%
测试集得分:
80.00%
混淆矩阵:
 [[17  0  0]
 [ 2 12  3]
 [ 3  1  7]]
准确性: 80.0%
精确性: 80.0%
召回率: 80.0%
F1值: 80.0%
AUC值:57.8%