欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在pytorch中計(jì)算準(zhǔn)確率,召回率和F1值的操作

 更新時(shí)間:2021年05月13日 09:44:37   作者:coding_zhang  
這篇文章主要介紹了在pytorch中計(jì)算準(zhǔn)確率,召回率和F1值的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

看代碼吧~

predict = output.argmax(dim = 1)
confusion_matrix =torch.zeros(2,2)
for t, p in zip(predict.view(-1), target.view(-1)):
    confusion_matrix[t.long(), p.long()] += 1
a_p =(confusion_matrix.diag() / confusion_matrix.sum(1))[0]
b_p = (confusion_matrix.diag() / confusion_matrix.sum(1))[1]
a_r =(confusion_matrix.diag() / confusion_matrix.sum(0))[0]
b_r = (confusion_matrix.diag() / confusion_matrix.sum(0))[1]

補(bǔ)充:pytorch 查全率 recall 查準(zhǔn)率 precision F1調(diào)和平均 準(zhǔn)確率 accuracy

看代碼吧~

def eval():
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    classnum = 9
    target_num = torch.zeros((1,classnum))
    predict_num = torch.zeros((1,classnum))
    acc_num = torch.zeros((1,classnum))
    for batch_idx, (inputs, targets) in enumerate(testloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=True), Variable(targets)
        outputs = net(inputs)
        loss = criterion(outputs, targets)
        # loss is variable , if add it(+=loss) directly, there will be a bigger ang bigger graph.
        test_loss += loss.data[0]
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()
        pre_mask = torch.zeros(outputs.size()).scatter_(1, predicted.cpu().view(-1, 1), 1.)
        predict_num += pre_mask.sum(0)
        tar_mask = torch.zeros(outputs.size()).scatter_(1, targets.data.cpu().view(-1, 1), 1.)
        target_num += tar_mask.sum(0)
        acc_mask = pre_mask*tar_mask
        acc_num += acc_mask.sum(0)
    recall = acc_num/target_num
    precision = acc_num/predict_num
    F1 = 2*recall*precision/(recall+precision)
    accuracy = acc_num.sum(1)/target_num.sum(1)
#精度調(diào)整
    recall = (recall.numpy()[0]*100).round(3)
    precision = (precision.numpy()[0]*100).round(3)
    F1 = (F1.numpy()[0]*100).round(3)
    accuracy = (accuracy.numpy()[0]*100).round(3)
# 打印格式方便復(fù)制
    print('recall'," ".join('%s' % id for id in recall))
    print('precision'," ".join('%s' % id for id in precision))
    print('F1'," ".join('%s' % id for id in F1))
    print('accuracy',accuracy)

補(bǔ)充:Python scikit-learn,分類模型的評(píng)估,精確率和召回率,classification_report

分類模型的評(píng)估標(biāo)準(zhǔn)一般最常見使用的是準(zhǔn)確率(estimator.score()),即預(yù)測結(jié)果正確的百分比。

混淆矩陣:

準(zhǔn)確率是相對(duì)所有分類結(jié)果;精確率、召回率、F1-score是相對(duì)于某一個(gè)分類的預(yù)測評(píng)估標(biāo)準(zhǔn)。

精確率(Precision):預(yù)測結(jié)果為正例樣本中真實(shí)為正例的比例(查的準(zhǔn))(\tfrac{TP}{TP+FP}

召回率(Recall):真實(shí)為正例的樣本中預(yù)測結(jié)果為正例的比例(查的全)(\frac{TP}{TP+FN}

分類的其他評(píng)估標(biāo)準(zhǔn):F1-score,反映了模型的穩(wěn)健型


demo.py(分類評(píng)估,精確率、召回率、F1-score,classification_report):

from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
 
# 加載數(shù)據(jù)集 從scikit-learn官網(wǎng)下載新聞數(shù)據(jù)集(共20個(gè)類別)
news = fetch_20newsgroups(subset='all')  # all表示下載訓(xùn)練集和測試集
 
# 進(jìn)行數(shù)據(jù)分割 (劃分訓(xùn)練集和測試集)
x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25)
 
# 對(duì)數(shù)據(jù)集進(jìn)行特征抽取 (進(jìn)行特征提取,將新聞文檔轉(zhuǎn)化成特征詞重要性的數(shù)字矩陣)
tf = TfidfVectorizer()  # tf-idf表示特征詞的重要性
# 以訓(xùn)練集數(shù)據(jù)統(tǒng)計(jì)特征詞的重要性 (從訓(xùn)練集數(shù)據(jù)中提取特征詞)
x_train = tf.fit_transform(x_train)
 
print(tf.get_feature_names())  # ["condensed", "condescend", ...]
 
x_test = tf.transform(x_test)  # 不需要重新fit()數(shù)據(jù),直接按照訓(xùn)練集提取的特征詞進(jìn)行重要性統(tǒng)計(jì)。
 
# 進(jìn)行樸素貝葉斯算法的預(yù)測
mlt = MultinomialNB(alpha=1.0)  # alpha表示拉普拉斯平滑系數(shù),默認(rèn)1
print(x_train.toarray())  # toarray() 將稀疏矩陣以稠密矩陣的形式顯示。
'''
[[ 0.     0.          0.   ...,  0.04234873  0.   0. ]
 [ 0.     0.          0.   ...,  0.          0.   0. ]
 ...,
 [ 0.     0.03934786  0.   ...,  0.          0.   0. ]
'''
mlt.fit(x_train, y_train)  # 填充訓(xùn)練集數(shù)據(jù)
 
# 預(yù)測類別
y_predict = mlt.predict(x_test)
print("預(yù)測的文章類別為:", y_predict)  # [4 18 8 ..., 15 15 4]
 
# 準(zhǔn)確率
print("準(zhǔn)確率為:", mlt.score(x_test, y_test))  # 0.853565365025
 
print("每個(gè)類別的精確率和召回率:", classification_report(y_test, y_predict, target_names=news.target_names))
'''
                precision  recall  f1-score  support
    alt.atheism   0.86      0.66     0.75      207
  comp.graphics   0.85      0.75     0.80      238
 sport.baseball   0.96      0.94     0.95      253
 ...,
'''
 

召回率的意義(應(yīng)用場景):產(chǎn)品的不合格率(不想漏掉任何一個(gè)不合格的產(chǎn)品,查全);癌癥預(yù)測(不想漏掉任何一個(gè)癌癥患者)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python實(shí)現(xiàn)網(wǎng)頁截圖(PyQT5)過程解析

    Python實(shí)現(xiàn)網(wǎng)頁截圖(PyQT5)過程解析

    這篇文章主要介紹了Python實(shí)現(xiàn)網(wǎng)頁截圖(PyQT5)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • python利用numpy存取文件案例教程

    python利用numpy存取文件案例教程

    這篇文章主要介紹了python利用numpy存取文件案例教程,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Idea安裝python顯示無SDK問題解決方案

    Idea安裝python顯示無SDK問題解決方案

    這篇文章主要介紹了Idea安裝python顯示無SDK問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 詳解用python -m http.server搭一個(gè)簡易的本地局域網(wǎng)

    詳解用python -m http.server搭一個(gè)簡易的本地局域網(wǎng)

    這篇文章主要介紹了詳解用python -m http.server搭一個(gè)簡易的本地局域網(wǎng),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 接口自動(dòng)化多層嵌套json數(shù)據(jù)處理代碼實(shí)例

    接口自動(dòng)化多層嵌套json數(shù)據(jù)處理代碼實(shí)例

    這篇文章主要介紹了接口自動(dòng)化多層嵌套json數(shù)據(jù)處理代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Python 文件和輸入輸出小結(jié)

    Python 文件和輸入輸出小結(jié)

    Python 是面向?qū)ο缶幊陶Z言,文件也是一種類,下面簡單介紹下,方便需要的朋友
    2013-10-10
  • python爬蟲模擬登錄之圖片驗(yàn)證碼實(shí)現(xiàn)詳解

    python爬蟲模擬登錄之圖片驗(yàn)證碼實(shí)現(xiàn)詳解

    眾所周知python是一個(gè)很強(qiáng)大的語言,它擁有眾多的庫,今天我嘗試了使用python進(jìn)行驗(yàn)證碼的識(shí)別,下面這篇文章主要給大家介紹了關(guān)于python爬蟲模擬登錄之圖片驗(yàn)證碼實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • 關(guān)于Python面向?qū)ο缶幊痰闹R(shí)點(diǎn)總結(jié)

    關(guān)于Python面向?qū)ο缶幊痰闹R(shí)點(diǎn)總結(jié)

    Python從設(shè)計(jì)之初就已經(jīng)是一門面向?qū)ο蟮恼Z言,正因?yàn)槿绱?,在Python中創(chuàng)建一個(gè)類和對(duì)象是很容易的。下面這篇文章將詳細(xì)給大家介紹關(guān)于Python面向?qū)ο缶幊痰闹R(shí)點(diǎn),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-02-02
  • Python 中的集合和字典

    Python 中的集合和字典

    這篇文章主要介紹了Python 集合中的字典,下面文章關(guān)于python中的集合和字典的相關(guān)內(nèi)容敘述詳細(xì),具有一定的參考價(jià)值,需要的小伙伴可以參考一下,希望對(duì)你的學(xué)習(xí)有所幫助
    2022-03-03
  • python字符串替換的2種方法

    python字符串替換的2種方法

    python 字符串替換 是python 操作字符串的時(shí)候經(jīng)常會(huì)碰到的問題,這里簡單介紹下字符串替換方法
    2014-11-11

最新評(píng)論