濮阳杆衣贸易有限公司

主頁 > 知識庫 > 在pytorch中計算準(zhǔn)確率,召回率和F1值的操作

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

熱門標(biāo)簽:海南400電話如何申請 廣告地圖標(biāo)注app 激戰(zhàn)2地圖標(biāo)注 哈爾濱ai外呼系統(tǒng)定制 唐山智能外呼系統(tǒng)一般多少錢 白銀外呼系統(tǒng) 公司電話機器人 騰訊外呼線路 陜西金融外呼系統(tǒng)

看代碼吧~

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]

補充: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)

補充:Python scikit-learn,分類模型的評估,精確率和召回率,classification_report

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

混淆矩陣:

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

精確率(Precision):預(yù)測結(jié)果為正例樣本中真實為正例的比例(查的準(zhǔn))(

召回率(Recall):真實為正例的樣本中預(yù)測結(jié)果為正例的比例(查的全)(

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


demo.py(分類評估,精確率、召回率、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個類別)
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)
 
# 對數(shù)據(jù)集進(jìn)行特征抽取 (進(jìn)行特征提取,將新聞文檔轉(zhuǎn)化成特征詞重要性的數(shù)字矩陣)
tf = TfidfVectorizer()  # tf-idf表示特征詞的重要性
# 以訓(xùn)練集數(shù)據(jù)統(tǒng)計特征詞的重要性 (從訓(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ì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("每個類別的精確率和召回率:", 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)品的不合格率(不想漏掉任何一個不合格的產(chǎn)品,查全);癌癥預(yù)測(不想漏掉任何一個癌癥患者)

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

您可能感興趣的文章:
  • Pytorch 實現(xiàn)計算分類器準(zhǔn)確率(總分類及子分類)
  • Pytorch 計算誤判率,計算準(zhǔn)確率,計算召回率的例子
  • pytorch繪制并顯示loss曲線和acc曲線,LeNet5識別圖像準(zhǔn)確率

標(biāo)簽:黔西 惠州 常德 益陽 鷹潭 上海 黑龍江 四川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《在pytorch中計算準(zhǔn)確率,召回率和F1值的操作》,本文關(guān)鍵詞  在,pytorch,中,計算,準(zhǔn)確率,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《在pytorch中計算準(zhǔn)確率,召回率和F1值的操作》相關(guān)的同類信息!
  • 本頁收集關(guān)于在pytorch中計算準(zhǔn)確率,召回率和F1值的操作的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    马龙县| 盐津县| 河东区| 庄浪县| 怀化市| 永丰县| 即墨市| 南平市| 桃江县| 芜湖县| 扎鲁特旗| 故城县| 彭阳县| 沁水县| 波密县| 彰武县| 治县。| 綦江县| 咸阳市| 图片| 兖州市| 宜黄县| 福清市| 宜昌市| 安远县| 信丰县| 雷山县| 绵竹市| 岳阳市| 衡东县| 大英县| 巴彦淖尔市| 遂溪县| 梁山县| 墨江| 小金县| 清水河县| 东明县| 龙州县| 资阳市| 通江县|